ansible automatic tool operation and maintenance of the ansible-playbook Detailed

http://www.yamllint.com/
Bowen convergence articles: Ansible automated installation and operation and maintenance of the common interpretation module

A, Playbook Profile

playbook configuration file using the YAML syntax, with concise, clear structure and so on. playbook profile similar to the shell script is a YAML formatted file to save the task list for specific needs. ansible command described above although you can complete various tasks, but when configuring a number of complex tasks, enter one by one it is a highly inefficient. More effective program is placed in the playbook configuration file all of the task code by ansible-playbook command to execute the file, you can automate the operation and maintenance. YAML file extension is usually .yaml or .yml.

Two, playbook core elements

playbook core elements include:

  • hosts: host target task, separated by a colon plurality of hosts, the general call packet information / etc / ansible / hosts in.
  • remote_user: on the remote host, the default identity to run this task to root.
  • tasks: the task, the task that is defined by the specific operation defined by a list of the module.
  • handlers: trigger, similar tasks, but the task will be triggered under certain conditions. State after running a task is changed, by "notify" notification trigger execution to the appropriate handlers.
  • roles: the role of the hosts stripped out, a specific structure of tasks, handlers and the like consisting of a collection.

Three, playbook format

playbook need points to note:

  • playbook written by YMAL language. YAML reference to other languages, including: XML, C language, Python, Perl and so on. MAL format is similar to JSON file format for people to understand and read, and easy to write.
  • By "-" to represent the entry by a colon ":" to separate the keys and values, the entire file to "---" and to begin "..." end.
  • All "-" and ":" followed by a space, but also to pay strict attention to alignment and indentation, or syntax may be able to error.
  • Each file before executing the playbook, be sure to use the "-C" option to pre-test. This option would survive a playbook file, but will not make any changes to the target host, the syntax is wrong or if the target host is missing a file, an error will be prompted.

1, perform simple playbook file:

[root@ansible ~]# grep -v ^# /etc/ansible/hosts | grep -v ^$              #查看hosts中的分组信息
[web1]
192.168.1.2
[web2]
192.168.1.3
[root@ansible ~]# vim /etc/ansible/a.yml                   #创建a.yml文件,写入以下内容
---
- hosts: web1                                                               #针对web1组中的操作
  remote_user: root                                                      #远端执行用户身份为root
  tasks:                                                                         #任务列表
        - name: adduser                                                  #任务名称
          user: name=user1 state=present                      #执行user模块,创建用户
          tags:                                                                  #创建tag标签
          - aaa                                                                  #tag标签为aaa
        - name: addgroup                                                #任务名称
          group: name=root system=yes                          #执行group模块,创建组
          tags:                                                                   #创建tag标签
          - bbb                                                                  #tag标签为bbb
- hosts: web2                                                               #针对web2组中的操作
  remote_user: root                                                      #远端执行用户身份为root
  tasks:                                                                         #任务列表
        - name: copy file to web                                      #任务名称
          copy: src=/etc/passwd dest=/home                   #执行copy模块,复制文件
          tags:                                                                   #创建tag标签
          - ccc                                                                   #tag标签为ccc
...

I wrote here playbook file as follows:

ansible automatic tool operation and maintenance of the ansible-playbook Detailed

Playbook file defines the task need to be invoked by ansible-playbook and execute the command, ansible-playbook command usage is as follows:

[root@ansible ~]# ansible-playbook  [ option ]/etc/ansible/a.yml

Where option in features include:

  • --syntax-check: syntax check yaml file.
  • -C: pre-test, without changing any settings of the target host.
  • --list-tasks: Task List lists yaml file.
  • --list-hosts: listed in the list of hosts affected yaml file.
  • --list-tags: Tags are listed yaml file.
  • -t TAGS: represent only perform tasks specified label.
  • --skip-tags = SKIP_TAGS: shows the tasks specified tag, perform other tasks.
  • --start-at-task = START_AT: starting at the specified task to run down.

Examples of execution a.yml file is as follows:

[root@ansible ~]# ansible-playbook --syntax-check /etc/ansible/a.yml    #语法检测

playbook: /etc/ansible/a.yml       #表示没有报错
[root@ansible ~]# ansible-playbook -C /etc/ansible/a.yml         #对a.yml进行预测试
PLAY [web1] **************************************************************************

TASK [Gathering Facts] ***************************************************************
ok: [192.168.1.2]

TASK [adduser] ***********************************************************************
changed: [192.168.1.2]

TASK [addgroup] **********************************************************************
ok: [192.168.1.2]

PLAY [web2] **************************************************************************

TASK [Gathering Facts] ***************************************************************
ok: [192.168.1.3]

TASK [copy file to web] **************************************************************
changed: [192.168.1.3]

PLAY RECAP ***************************************************************************
192.168.1.2                : ok=3    changed=1    unreachable=0    failed=0   
192.168.1.3                : ok=2    changed=1    unreachable=0    failed=0   
#返回结果表示没有错误,全部可以执行成功。
[root@ansible ~]# ansible-playbook --list-hosts /etc/ansible/a.yml    #列出a.yml文件中的主机
[root@ansible ~]# ansible-playbook --list-tasks /etc/ansible/a.yml       #列出任务
[root@ansible ~]# ansible-playbook --list-tags /etc/ansible/a.yml            #列出标签
[root@ansible ~]# ansible-playbook /etc/ansible/a.yml                #执行任务
[root@ansible ~]# ssh 192.168.1.2 tail -1 /etc/passwd              #确认执行结果
user1:x:1001:1001::/home/user1:/bin/bash
[root@ansible ~]# ssh 192.168.1.3 ls -ld /home/passwd
-rw-r--r--. 1 root root 2342 7月  23 16:06 /home/passwd
#一般情况先执行“-C”命令进行预测试,没有问题后再执行.yml文件。

2, flip-flop

Required to trigger the task to be performed, when the tasks before the task is executed successfully. If you want to trigger other tasks on this basis, which requires the definition of handlers. For example, when modified by ansible module configuration file on the target host, if the task is successful, it can trigger a trigger, define the service to restart the operation target host in a trigger, so that the configuration file to take effect. trigger handlers has the following characteristics:

  • handlers is one of the conditions provided by ansible mechanism. handlers and the task is very similar, but it only will trigger execution when notified task.
  • handlers is performed only after the completion of all tasks executed. And even if notice a lot of times, it will only be performed once.

As follows using the example of the trigger handlers:

[root@ansible ~]# ssh 192.168.1.2 netstat -anpt | grep 80                  #查询1.2主机监听的端口
tcp6       0      0 :::80         :::*          LISTEN      94858/httpd 
#可以看到是监听80端口,现在通过脚本改为8080端口,并使其生效。
[root@ansible ~]# vim /etc/ansible/httpd.yml          #编辑httpd.yml文件,写入以下内容

---
- hosts: web1
  remote_user: root
  tasks:
        - name: change port
          command: sed -i 's/Listen\ 80/Listen\ 8080/g' /etc/httpd/conf/httpd.conf
          notify:                                        #配置触发条件
                - restart httpd server           #完成该任务后调用名为“restart httpd server”的触发器
  handlers:                                          #配置触发器
        - name: restart httpd server       #指定触发器名字,要和上面“notify”指定的触发器名字一样
          service: name=httpd state=restarted           #触发任务为重启httpd服务。
...
#编写完成后,保存退出即可。
[root@ansible ~]# ansible-playbook -C /etc/ansible/httpd.yml           #进行预测试。
[root@ansible ~]# ansible-playbook  /etc/ansible/httpd.yml               #执行脚本。
[root@ansible ~]# ssh 192.168.1.2 netstat -anpt | grep 8080        #远端主机已经运行8080端口
tcp6       0      0 :::8080        :::*         LISTEN      103594/httpd

3. Role

The variety of different tasks centrally stored files in a directory, the directory is the role. Role generally stored in / etc / ansible / roles / directory may be adjusted by default roles ansible configuration files directory, there are many subdirectories / etc / ansible / roles / directory, wherein each subdirectory corresponding to a character, each role has its own directory structure, the structure is as follows:
ansible automatic tool operation and maintenance of the ansible-playbook Detailed

/ Etc / ansible / roles / role for the collection, there is a custom subdirectories under that directory:

  • mariadb: mysql role.
  • Apache: httpd role.
  • Nginx: Nginx role.
    The definition of each role are organized in a specific hierarchical directory structure. To mariadb (mysql role) as an example:
  • files: store files such as copy or called by the script module.
  • templates: template storage module directory to find the required template file, such as mysql configuration file template.
  • tasks: Task store directory.
  • handlers: storage directory associated trigger execution.
  • vars: variable storage directory.
  • meta: this role is used to store metadata.
  • default: The default directory to store the variables, file defines the default variable used in this role.

The above directory, tasks, handlers, vars, meta, default should contain at least a main.yml file, the catalog file may also have other .yml, but need include instructions main.yml file with the file additional .yml It included.

Once you have character, you can call direct role in yaml file (playbook configuration file), the examples are as follows:

---
- hosts: web1
  remote_user: root
  roles:            
  - mysql        #调用角色名
  - httpd             #调用角色名
...

You can call only one role, you can also call multiple roles, when the definition of a role, you can perform with ansible-playbook PALYBOOK file. At this point ansible role will be to catalog the collection (/ etc / ansible / roles) to find mysql and httpd directory, and will run all of the code in mysql and httpd directory.

The following example of installation and configuration to the database mariadb:

demand analysis:

  • Requirements management is automatically installed on the host mariadb, upload prepare in advance after the installation is complete good configuration file to the remote host, restart the service, and then create testdb database and allows users test their own all rights.
    • Configuration management is the host yum warehouse, self-configuring, if they manage client can connect to the Internet, then directly to the yum repository to point to the Internet.

Start on the ansible server implementation:

[root@ansible /]# mkdir -pv /etc/ansible/roles/mariadb/{files,tasks,handlers}
mkdir: 已创建目录 "/etc/ansible/roles/mariadb"
mkdir: 已创建目录 "/etc/ansible/roles/mariadb/files"
mkdir: 已创建目录 "/etc/ansible/roles/mariadb/tasks"
mkdir: 已创建目录 "/etc/ansible/roles/mariadb/handlers"
[root@ansible /]# cd /etc/ansible/roles/mariadb/tasks/       #切换至指定目录
[root@ansible tasks]# ls
[root@ansible tasks]# vim main.yml                     #编写main.yml文件
---
- name: install mariadb
  yum: name=mariadb-server state=present
- name: move config file
  shell: "[ -e /etc/my.cnf ] && mv /etc/my.cnf /etc/my.cnf.bak"
- name:
  copy: src=my.cnf dest=/etc/my.cnf
- name: reload mariadb
  shell: systemctl restart mariadb
- name: create database testdb
  shell: mysql -u root -e "create database testdb;grant all on testdb.* to 'test'@'192.168.1.%' identified by 'test123';flush privileges;"
  notify:
  - restart mariadb
...
#编写完毕,保存退出即可。
[root@ansible tasks]# cd ../handlers/            #切换至触发器目录
[root@ansible handlers]# vim main.yml              #编写main.yml文件,写入以下内容
---
- name: restart mariadb
  service: name=mariadb state=restarted
...
#编写完毕,保存退出即可。
[root@ansible handlers]# cd ../files     #进入mariadb角色文件夹的files
[root@ansible files]# pwd
/etc/ansible/roles/mariadb/files
[root@ansible files]# ls            #准备好配置好的mysql数据库配置文件,需要分发到远程主机的
my.cnf
[root@ansible files]# cd /etc/ansible/
[root@ansible ansible]# vim mariadb.yml         #编写.yml文件
---
- hosts: web
  remote_user: root
  roles:
  - mariadb
...
##编写完毕,保存退出即可。
[root@ansible ansible]# ansible-playbook -C mariadb.yml          #进行预检测
                                  ........................          #省略部分内容
PLAY RECAP ***************************************************************************
192.168.1.2                : ok=3    changed=1    unreachable=0    failed=0 
#返回结果表示没问题
[root@ansible ansible]# ansible-playbook mariadb.yml           #执行安装

After the installation is complete, whether viewed on the remote host testdb database has been created and tested in order to test the user logs on, self-test it.

Guess you like

Origin blog.51cto.com/14154700/2422908