Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Basic use and Quick start of playbook of Ansible

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

1. What are the benefits of using playbook

two。 Recognize playbook (automatically deploy nginx) (automatically deploy docker-ce Community Edition)

3.YAML syntax

4.playbook file structure

5. Perform an action when changing (handlers)

6. Task control (tags)

7.playbook file debugging

8. Case: automatic deployment of tomcat

Definition and use of 9.Playbook variable

10.playbok file reuse

11. Process control

12.jinja template rendering Profil

1. What are the benefits of using playbook

The real power of Ansible is to use playbook, also known as script, when we execute a command in a directory, then we can use ansible's ad hoc mode to execute quickly, without writing files or scripts, but for configuration management and application deployment, there are usually a lot of operations, writing ad hoc commands alone is troublesome, and ad hoc is suitable for the execution of simple commands So we use playbook to do this, if ansible is the tool used in the work, then ploybook is the equivalent of your instructions for using ansible, and your host is the raw material, writing playbook is like writing instructions, it is a process that is executed sequentially, playbook and ad hoc are not a mode at all, and they are powerful.

Characteristics of Playbook

Easy-to-read choreography language: it is written in the most mainstream yaml format to achieve application choreography, very suitable for configuration and application deployment, but also very suitable for deploying complex tasks, we can use declarative content to choreograph complex work through playbook.

This-syntax-check is to check the syntax of playbook

[root@ansible playbook-test] # ansible-playbook nginx.yaml-- syntax-check playbook: nginx.yaml [root@ansible playbook-test] # vim nginx.yaml [root@ansible playbook-test] # cat nginx.yaml-hosts: webservers vars: hello: Ansible tasks:-name: Add repo yum_repository: name: nginx description: nginx repo baseurl: http://nginx.org/packages/centos/7/$basearch/ gpgcheck: no Enabled:-name: Install nginx yum: name: nginx state: latest-name: Copy nginx configuration file copy: src:. / site.conf dest: / etc/nginx/conf.d/site.conf-name: Start nginx service: name: nginx state: started-name: Create wwwroot directory file: dest: / var/www/html state: directory-name: Create test page index.htmlshell: Echo "hello {{hello}}" > / var/www/html/index.html [root@ansible playbook-test] # lsnginx.yaml site.conf [root@ansible playbook-test] # vim site.confserver {listen 80 Server_name devops; location / {root / var/www/html;index index.html;}}

Execute playbook

[root@ansible playbook-test] # ansible-playbook nginx.yaml

Check that the process has been started

[root@ansible playbook-test] # ansible webservers-m shell-a "ps-ef | grep nginx" 10.4.7.22 | SUCCESS | rc=0 > > root 10713 10 16:46? 00:00:00 nginx: master process / usr/sbin/nginx-c / etc/nginx/nginx.confnginx 10714 10713 0 16:46? 00:00:00 nginx: worker processroot 10849 10848 10 16:49 pts/1 00:00:00 / bin/sh-c Ps-ef | grep nginxroot 10851 10849 0 16:49 pts/1 00:00:00 grep nginx10.4.7.21 | SUCCESS | rc=0 > > root 10953 10 16:46? 00:00:00 nginx: master process / usr/sbin/nginx-c / etc/nginx/nginx.confnginx 10954 10953 16:46? 00:00:00 nginx: worker processroot 11088 11087 0 16:49 pts/1 00:00:00 / bin/sh-c Ps-ef | grep nginxroot 11090 11088 0 16:49 pts/1 00:00:00 grep nginx

Batch deployment of docker-ce Community Edition

The modules used here are shell module and service, which is very simple.

-hosts: webservers gather_facts: no remote_user: root tasks:-name: install packages shell: yum- y install yum-utils device-mapper-persistent-data lvm2-name: docker packages shell: wget-O / etc/yum.repos.d/docker-ce.repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo-name: install docker-ce shell: yum- y install docker-ce-name: daocloud speed up shell: Curl-sSL https://get.daocloud.io/daotools/set_mirror.sh | sh-s http://f1361db2.m.daocloud.io-name: systemctl start docker service: name=docker state=started

Test to see if the installation is successful

[root@ansible ~] # ansible webservers-m shell-a "docker-v" 10.4.7.21 | SUCCESS | rc=0 > > Docker version 19.03.5, build 633a0ea10.4.7.22 | SUCCESS | rc=0 > > Docker version 19.03.5, build 633a0ea

YAML syntax format

Indentation represents a hierarchical relationship

Tab "tab" indentation is not supported

Usually indent 2 spaces at the beginning

Indent 1 space after the character, such as colon, comma, etc.

"- -" indicates YAML format, the beginning of a file.

"#" comment

Perform an action (handlers) processor on change

It is mainly used to help you trigger another task when you come out of an operation change.

Hosts: webservers

Gather_facts: no

This will collect the information of the list host, which will take a lot of time and generally disable it, so it will improve the efficiency of our playbook.

Automatically deploy tomcat

1. Install jdk

2. Download the tomcat package

3. Decompress tomcat

4. Start

Install tomcat

-hosts: webservers gather_facts: no vars: tomcat_version: 9.0.29 tomcat_install_dir: / usr/local tasks:-name: Install java-1.8.0-openjdk.x86_64 shell: yum-y install java-1.8.0-openjdk.x86_64 state=present-name: Download tomcat get_url: url= http://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-9/v9.0.29 / bin/apache-tomcat-9.0.29.tar.gz dest=/tmp-name: Unarchive tomcat- {{tomcat_version}}. Tar.gz unarchive: src: / tmp/apache-tomcat- {{tomcat_version}}. Tar.gz dest: "{{tomcat_install_dir}}" copy: no-name: Start tomcat shell: cd {{tomcat_install_dir}} & & Mv apache-tomcat- {{tomcat_version}} tomcat8 & & cd tomcat8/bin & & nohup. / startup.sh & [root@ansible tomcat-playbook] # ansible-playbook tomcat.yaml [root@ansible tomcat-playbook] # ansible webservers-m shell-a "ps-ef | grep tomcat"

Definition and use of Playbook variable

Command line definition in inventory definition in playbook definition in role definition of registration variable (register) system information variable (facts)

The command line defines variables

List the main variable information

[root@ansible tomcat-playbook] # ansible-playbook-- list-tags tomcat.yaml playbook: tomcat.yaml play # 1 (webservers): webservers TAGS: [] TASK TAGS: [] [root@ansible tomcat-playbook] # ansible-playbook-- list-tasks tomcat.yaml playbook: tomcat.yaml play # 1 (webservers): webservers TAGS: [] tasks: Install java-1.8.0-openjdk.x86_64 TAGS: [] Download tomcat TAGS: [] Unarchive tomcat- {{tomcat_version}}. Tar.gz TAGS: [] Start tomcat TAGS: []

The debug module prints statements during execution and can be used to debug variables or expressions without having to stop playbook.

[root@ansible tomcat-playbook] # vim 1.yaml root@ansible tomcat-playbook-hosts: webservers gather_facts: no remote_user: root tasks:-name: test var debug: msg= "{{work_dir}}" [root@ansible tomcat-playbook] # ansible-playbook 1.yaml-e work_dir=/usr/local

There are also certain requirements for defining this variable. The variable name should start with a letter.

There is another definition in inventory.

Define variables in / etc/ansible/hosts, passing different variables for a group of hosts or multiple hosts

You can also write it separately under / etc/ansible/group_vars/webservers.yml, which will read the variables in your group by default. It is more convenient to use yml mode.

Http_port: 8090

Server_name: xiabanle

[root@ansible group_vars] # ansible webservers-a "echo {{http_port}}" 10.4.7.22 | SUCCESS | rc=0 > > 809010.4.7.21 | SUCCESS | rc=0 > > 8090 [root@ansible group_vars] # ansible webservers-a "echo {{server_name}}" 10.4.7.22 | SUCCESS | rc=0 > > xiabanle10.4.7.21 | SUCCESS | rc=0 > > xiabanle

Use the debug module to define variables in playbook

-hosts: webservers gather_facts: no remote_user: root vars:-work_dir: / usr/local-nginx_version: 1.16 tasks:-name: Install nginxdebug: msg= "{{work_dir}} / nginx/ {{nginx_version}}" [root@ansible tomcat-playbook] # ansible-playbook 1.yaml-- syntax-checkplaybook: 1.yaml [root@ansible tomcat-playbook] # ansible-playbook 1.yaml

Create a file using the file module

-hosts: webservers gather_facts: no remote_user: root vars:-work_dir: / opt-nginx_version: 1.11 tasks:-name: create dir file: "dest= {{work_dir}} / nginx/ {{nginx_version}} state=directory"

Registration variable-register

To register a variable is to save the result of the execution of a task to a variable, so that you can dynamically obtain a variable, for example, after executing a task, there is a state returned, so you want to process it asynchronously according to this state. because the previous variables correspond, it is difficult to know what variables are acquired this time.

Here is a debug for debugging variables. Here, the file is created and the time of the file is defined dynamically.

In general, this is to start two services, these two services are dependent, only start the first service, the second can be started, in this case, you can add a registration variable under the startup service, if the first service starts, there will be pid, or other output and then use the defined registration variable.

-hosts: webservers gather_facts: no remote_user: root vars:-work_dir: / opt tasks:-name: register var command: date + "% F% T" register: datetime-name: touch file # debug: msg= {{datetime}} file: dest=/tmp/r_ {{datetime.stdout}} state=touch

System Information variable (fasts)

Call hostname / host IP with system variable and create a file

This can be called through set up to check the interface api of our ansible

[root@ansible test] # ansible webservers-m setup---- hosts: webservers gather_facts: yes remote_user: root tasks:-name: touch file file: dest=/tmp/devops_ {{ansible_hostname}} state=touch

Playbok file reuse

To reuse our files, we can import them using incloud_tasks and import_tasks in playbook. The advantage is that when we write a relatively large playbook, we can break it down into many small tasks, which can be referenced elsewhere. The second advantage is that we can organize these functional modules of playbook. If we want to write a big script, it may be hundreds of lines. It is not easy to maintain and manage, so there is the implementation of include_tasks and import_tasks to meet these requirements.

The difference between Include and import

They all import files.

Include (dynamic): importing at run time

-- list-tags,-- list-tasks will not be displayed to the output

 cannot use notify to trigger from the handler name within include (handlers)

Import* (static): import in advance during playbook parsing, that is, import the advance before playbook.

 cannot be used with loops

When  uses variables for target files or role names, you cannot use variables in inventory (host / host group, etc.)

Reuse cases:

Install lnmp/lnmt

All you need is the yaml used by the-import call

Vim lnmp.yaml----import_playbook: nginx.yaml- import_playbook: mysql.yaml-import_playbook: php.yamlvim nginx.yaml---- hosts: webservers gather_facts: no remote_user: root tasks:-name: Install nginx debug: msg= "install nginx..." [root@ansible web] # ansible-playbook lnmp.yaml

Import imports playbook, while include imports task files

[root@ansible web] # ansible-playbook test.yaml---- hosts: webservers gather_facts: no remote_user: root tasks:-name: task1 debug: msg= "test1"-name: task2 debug: msg= "test2"

However, the tasks of the deployed tasks can be decomposed when there are more tasks, and can be divided into separate files. For example, there are two tasks. I decompose the first tasks into a file, and the second one is decomposed into a file and then imported with include.

Vim test.yaml---- hosts: webservers gather_facts: no remote_user: root tasks:-include_tasks: task1.yaml- include_tasks: task2.yamlvim task1.yaml---- name: tasks1 debug: msg= "test1" vim task2.yaml---- name: tasks2 debug: msg= "test2"

Process control

Cycle

Batch creation of users / files / copies of files can also be used

-name: create file file: path=/tmp/ {{item}} state=touch with_items:-"1.txt"-"2.txt"-"3.txt"-"4.txt" execution effect [root@hdss7-200 test-roles] # ansible-playbook-I hosts site.yaml-- tags nginxPLAY [roles] * * * TASK [nginx: create file] * * * changed: [10.4.7.22] = > (item=1.txt) changed: [10.4.7.22] = > (item=2.txt) changed: [10.4.7.22] = > (item=3.txt) changed: [10.4.7.22] = > (item=4.txt) PLAY RECAP * * 10.4.7.22: ok=1 changed=1 Common loop statements in unreachable=0 failed=0 skipped=0 rescued=0 ignored=0:

Like copying files.

-name: copy html copy: src=/tmp/ {item}} dest=/tmp with_items:-"a.html"-"b.html"-"c.html"

Or wildcards, such as some compressed packages of tar.gz that copy some directories, for example, you can use fileglob or item for for loop and batch execution to simplify the operation steps.

-name: copy html copy: src= {{item}} dest=/tmp with_fileglob:-"/ tmp/*.html"

Template

For example, to deploy an application, nginx,etcd, all have their own configuration files. For example, if you render the configuration files of nginx and virtual hosts to our nginx, you can use template. This module specifically supports jr templates.

Define the template of j2 here, and then copy this file to render

[root@hdss7-200 test-roles] # cat / tmp/nginx.conf {% set domain_name = domain%} server {listen 80; server_name {{domain_name}}; location / {root / usr/share/html;}}

Defined variables, passing them

[root@hdss7-200test-roles] # cat group_vars/roles.yaml domain: www.xxxxx.com

Defined task type

-name: vire hosts template: src=/tmp/nginx.conf dest=/etc/nginx/conf.d/

For example, pass the variables of the port again, and use {{}} between the variables that use ansible in jinja.

[root@hdss7-200test-roles] # cat / tmp/nginx.conf {% set domain_name = domain%} server {listen {{http_port}}; server_name {{domain_name}}; location / {root / usr/share/html;}}

I define this variable in ansible.

[root@hdss7-200test-roles] # cat group_vars/roles.yaml domain: "www.maidi.com" http_port: "80"

Successful execution will copy our configuration file using J2 template, and we can render many of our functions and requirements through j2 template and ansible definition variables.

[root@hdss7-22 conf.d] # cat nginx.conf server {listen 80; server_name www.maidi.com; location / {root / usr/share/html;}}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report