Don’t make the operation and maintenance too busy. This article explains the automatic operation and maintenance of ansible in detail


1、 Ansible overview

Ansible is an increasingly popular open source operation and maintenance automation tool in recent years. Through ansible, operation and maintenance automation can be realized, the work efficiency of operation and maintenance engineers can be improved, and human errors can be reduced.

Ansible can achieve various management tasks through its own integrated modules, with more than 1000 modules. What’s more, its operation is very simple, even Xiaobai can easily get started, but it provides very rich functions. In the field of operation and maintenance, it can do almost anything.

1. Ansible features

Ansible has been popular in the world since it was released in 2012. Its characteristics are as follows:

  • Ansible is developed based on python, and it is relatively easy for operation and maintenance engineers to develop secondary development;
  • Ansible has rich built-in modules, which can meet almost all requirements;
  • The management mode is very simple. One command can affect thousands of hosts;
  • There is no client mode, and the bottom layer communicates through SSH;
  • Ansible has been accepted and put into use by AWS, Google cloud platform, Microsoft azure, Cisco, HP, VMware, twitter and other large companies after its release;

2、 Ansible’s role

  • User: how to use ansible to realize automatic operation and maintenance?
  • Ansible toolset: what can ansible do?
  • Target: which hosts can ansible affect?

1. Users

As shown in the figure below: ansible users can interact with ansible in various ways. The figure shows four ways:

  • CMDB: the CMDB stores and manages the configuration information in the enterprise IT architecture, and is the core tool for building ITIL projects. The operation and maintenance personnel can combine CMDB and ansible, and directly issue instructions through the CMDB to call ansible tool set to achieve the desired goal of the operator;
  • Public / private mode: ansible not only has rich built-in modules, but also provides rich API language interfaces, such as PHP, python, Perl and other popular languages. Based on public / private, ansible runs as an API call;
  • Ad hoc command set: users call ansible toolset directly through ad hoc command set to complete tasks;
  • Playbooks: users have written ansible playbooks in advance and executed them
  • In playbooks, the task set is arranged in advance, and the tasks are executed in order;

Don't make the operation and maintenance too busy. This article explains the automatic operation and maintenance of ansible in detail

2. Ansible Toolset

Ansible toolset includes inventory, modules, plugins and API.

Among them: Inventory: used to manage the device list, which can be realized by grouping, and the call to the group directly affects all hosts in the group; modules: various execution modules, almost all management tasks are executed through modules; plugins: provides various additional functions; API: provides an interface for programmers, which can be based on this The secondary development of ansible is as follows:

  • Ansible playbooks: task script, which arranges and defines ansible tasks and configuration files, which are executed sequentially by ansible, usually YML files in JSON format;
  • Inventory: ansible management host list;
  • Modules: ansible executive command function module, most of which are built-in core modules and can be customized;
  • Plugins: supplement of module functions, such as connection type plug-in, loop plug-in, variable plug-in, filter plug-in, etc., which are not commonly used;
  • API: application programming interface for third-party program call;
  • Ansible: this part of the diagram is not obvious. The combination of inventory, API, modules and plugins can be understood as ansible command tool, which is the core execution tool;

3. Object of action

Ansible is not only the host of Linux and non Linux operating systems, but also the network facilities of various public / private, commercial and non-commercial devices.

When users use Ansible or Ansible-Playbooks, after entering the Ad-Hoc command set or Playbooks of Ansible at the server terminal, Ansible will follow the prearranged rules to disassemble the Playbooks step by step to Play, and then organize Play into a task that Ansible can recognize, then invoke all modules and plug-ins involved in the task, according to the Inventory The host list defined in SSH will transfer the task set in the form of temporary files or commands to the remote client for execution and return the execution results. If it is a temporary file, it will be automatically deleted after the execution.

3、 Ansible configuration

1. Ansible installation

The installation and deployment of ansible is very simple. Take RPM installation as an example, its dependent software is only Python and SSH, and the system is installed by default. The management side of ansible can only be Linux, such as RedHat, Debian and CentOS.

1) Installing ansible through yum

You can download ansible software package directly from the Internet. This blog provides the dependent software package for installing ansible automatic operation and maintenance tools

[[email protected] ~]# cd /mnt/ansiblerepo/ansiblerepo/repodata/
[[email protected] ansiblerepo]# vim /etc/yum.repos.d/local.repo
Baseurl = file: // / MNT / ansiblerepo / ansiblerepo <! -- modify the yum path -- >
[ [email protected] ~] # Yum - y install ansible

2) Verify installation results

[[email protected] ~]# ansible --version    
<! -- if the command can be executed normally, the ansible tool is successfully installed -- >
config file = /etc/ansible/ansible.cfg  
configured module search path = Default w/o overrides  
python version = 2.7.5 (default, Nov  6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]

3) Create SSH interactive login free

Ansible manages the device through SSH, and SSH includes two authentication methods: one is through password authentication, the other is through key pair authentication. The former must interact with the system, while the latter is interactive free login. If you want to manage the device automatically through ansible, it should be configured to avoid interactive login of the managed device.

[[email protected] ~]# ssh-keygen -t rsa  
<! -- generate key pair -- >
Generating public/private rsa key pair.Enter file in which to save the key (/root/.ssh/id_rsa):
<! -- key pair storage path -- >
Created directory '/root/.ssh'.Enter passphrase (empty for no passphrase):       
<! -- enter the private key protection password, and press enter directly to indicate no password -- >
Enter same passphrase again:    
<! -- enter again -- >
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/
The key fingerprint is:
SHA256:cJz6NRTrvMDxX+Jpce6LRnWI3vVEl/zvARL7D10q9WY [email protected]
The key's randomart image is:
+---[RSA 2048]----+
|          .   . .|
|       . . +   oo|
|      . = o o. oo|
|       = * o..+ *|
|      . S *.=+=*+|
|       . o =+XooE|
|        . ..=.++.|
|           ..o ..|
|           .. o. |
[[email protected] ~]# ssh-copy-id -i .ssh/  [email protected]  
<! -- copy public key to remote -- >
[[email protected] ~]# ssh-copy-id -i .ssh/  [email protected]    
<! -- copy public key to remote -- >

So far, the deployment of ansible has been completed. Next, you can manage the device through ansible.

2. Ansible configuration

Inventory is an ansible configuration file for managing host information, which is equivalent to the function of system hosts file. It is stored in / etc / ansible / hosts by default.

In the hosts file, devices are organized by grouping, ansible defines hosts and groups through inventory, and uses options in ansible command-ior—inventory-fileTo specify inventory.

[[email protected] ~]# ansible -i /etc/ansible/hosts web -m ping

If you use the default inventory file (/ etc / ansible / hosts), you can also not specify the inventory file, for example:

[[email protected] ~]# ansible web -m ping

Ansible can add the device list to the / etc / ansible / hosts file in a grouping way to realize the management of the device, so before the formal management, the hosts file should be written first. In the hosts file, the group name is represented by the part contained in [] and the host name and IP address are supported in the device list.

By default, devices are managed by accessing port 22 (SSH). If the target host uses a non default SSH port, you can also use a colon and port after the host name to separate the configuration by behavior units. In addition, the hosts file also supports wildcards.

[[email protected] ~]# vim /etc/ansible/hosts
... <! -- part of the content is omitted here -- >
<! -- manage devices through port 222 -- >
<! -- [2:5] denotes all numbers between 2 and 5, that is, YJ2 、yj3. …… All hosts of -- >

You can group a host in different groups at the same time.

After the configuration is completed, you can perform remote operations against the groups defined by hosts, or operate against one or more hosts in the group. For example:

1) Only hosts in the web group are operated, and the change of hosts is limited by the – limit parameter.

[[email protected] ~]# ansible web -m command -a "systemctl status httpd" --limit "" | SUCCESS | rc=0 >>
<! -- you will know success when you see success, so the following content -- >
<! -- if the httpd service is tested, the host under test must have installed and started the httpd Service -- >

2) Only for host. Change of host is limited by IP.

[[email protected] ~]# ansible -m command -a "systemctl status httpd" | SUCCESS | rc=0 >>

3) Only for segment hosts, which requires the use of wildcards to limit host changes.

[[email protected] ~]# ansible 192.168.1.* -m command -a "systemctl status httpd" | SUCCESS | rc=0 >>
... <! -- omit some contents here -- > | SUCCESS | rc=0 >>
... <! -- omit some contents here -- >
<! -- experimental environment, the effect is the same, so I won't say much here -- >

3. Ansible command

Most ansible maintenance commands start with ansible. After inputting ansible at the terminal, pressing the tab key twice continuously will complete all ansible related commands.

[ [email protected] ~]? Ansible <! -- press the tab key continuously -- >
ansible               ansible-console-2     ansible-galaxy        
ansible-playbook-2.7  ansible-vault-2ansible-2             
ansible-console-2.7   ansible-galaxy-2      ansible-pull          
ansible-vault-2.7ansible-2.7           ansible-doc           
ansible-galaxy-2.7    ansible-pull-2ansible-connection    
ansible-doc-2         ansible-playbook      
ansible-doc-2.7       ansible-playbook-2    ansible-vault


Ansible is one of the most frequently used commands in the production environment. It is mainly used in the following scenarios:

Non curing requirements;

Temporary one-time operation;

Second development interface call;

Non fixed requirements refer to temporary maintenance, such as checking the disk usage of web server group, copying a file to other machines, etc. Similar to these irregular and temporary tasks, we become non fixed requirements and temporary one-time operation. The syntax is as follows:

Ansible  <host-pattern> [options]
  • -V (- verb): output detailed information of execution process, and all information of execution process can be obtained;
  • -I path (- inventory = path): Specifies the inventory information, which is / etc / ansible / hosts by default;
  • -F num (- forks = Num): the number of concurrent threads, 5 threads by default;
  • —private-key=PRIVATE_ KEY_ File: specify the key file;
  • -M name, – module name = name: Specifies the module used for execution;
  • -M directory (- module path = directory): specify the module storage path, and the default is / usr / share / ansible;
  • -A arguments (- args = arguments): specify module parameters;
  • -U user name (- user = username): Specifies the remote host to run commands with username;
  • -L subset (- limit = subset): limit the running host;

① Check whether all hosts are alive. Execute the following command:

[[email protected] ~]# ansible all -f 5 -m ping
<! -- call the Ping module, all means all hosts in the / etc / ansible / hosts file without creating all group (it exists by default) -- > | success = > {<! -- indicates successful execution -- >    
"Changed": false, <! -- no changes have been made to the host -- >   
"Ping": "Pong" <! -- indicates the return result of executing ping command -- >} | SUCCESS => {    
"changed": false,    
"ping": "pong"

② List all hosts in the web group, and execute the following command:

[ [email protected] ~] ා ansible web -- List <! -- List: List host list information -- >  
hosts (2):

③ Display the disk space in Web group in batch, and execute the following command:

[[email protected] ~]# ansible web -m command -a "df -hT" | SUCCESS | rc=0 >>  
File system type capacity used available used% mount point  
/dev/mapper/cl-root xfs        17G  4.4G   13G   26% /  
devtmpfs            devtmpfs  897M     0897M    0% /dev  
tmpfs               tmpfs     912M   84K  912M    1% /dev/shm  
tmpfs               tmpfs     912M     0912M    0% /sys/fs/cgroup  
/dev/sda1           xfs      1014M  173M  842M   18% /boot  
tmpfs               tmpfs     183M   16K  183M    1% /run/user/42  
tmpfs               tmpfs     183M     0183M    0% /run/user/0 | SUCCESS | rc=0 >>  
File system type capacity used available used% mount point  
/dev/mapper/cl-root xfs        17G  4.3G   13G   26% /  
devtmpfs            devtmpfs  897M     0897M    0% /dev  
tmpfs               tmpfs     912M   84K  912M    1% /dev/shm  
tmpfs               tmpfs     912M     0912M    0% /sys/fs/cgroup  
/dev/sda1           xfs      1014M  173M  842M   18% /boot  
tmpfs               tmpfs     183M   16K  183M    1% /run/user/42  
tmpfs               tmpfs     183M     0183M    0% /run/user/0  
/dev/sr0            iso9660   4.1G  4.1G     0100% /mnt

The web keyword needs to define groups in the / etc / ansible / hosts file in advance.

Ansible’s return result is very friendly. Generally, three colors are used to represent the execution result

  • Red: indicates that the execution process is abnormal;
  • Orange color: indicates that the target has state change after the command is executed;
  • Green: it means that the execution is successful and there is no target machine to modify it;


Ansible doc is used to query the description of ansible module documents, similar to the man command. For each module, there are detailed instructions and application cases. The syntax is as follows:

ansible-doc [options] [module……]

List the supported modules:

[[email protected] ~]#ansible-doc -l

Query the description information of Ping module

[[email protected] ~]# ansible-doc ping  
> PING    (/usr/lib/python2.7/site-packages/ansible/modules/system/  
  A trivial test module, this module always returns `pong' on successful contact. It  
  does not make sense in playbooks, but it is useful from `/usr/bin/ansible' to verify  
  the ability to login and that a usable python is configured. This isNOT ICMP ping,  
  this is just a trivial test module.  
# Test we can logon to 'webservers' and execute python with json lib.  
ansible webservers -m ping  
MAINTAINERS: Ansible Core Team, Michael DeHaan  
        Status: ['stableinterface']  
        Supported_by: core


Ansible playbook is the most frequently used command in daily applications, similar to the SH or source command in Linux, which is used to perform a series of tasks.

Its working mechanism: through reading the pre written playbook file, the centralized processing task is realized. The ansible playbook command is followed by a playbook file in YML format. The playbook file stores the task code to be executed. The command is used as follows:

Ansible-playbook playbook.yml
<!-- playbook.yml The file should be written in advance. It is recommended to use the absolute path -- >


Ansible console is an interactive tool provided by ansible for users, which is similar to windows CMD or Linux shell. Users can use ansible built-in commands like shell on the virtual terminal of ansible console, which provides a good experience for users who are accustomed to using shell interactive mode. After entering the ansible console command at the terminal, the display is as follows:

[[email protected] ~]# ansible-console
Welcome to the ansible console.
Type help or ? to list commands.
<! -- type help or? Get help -- >
[email protected] (2) [F: 5] $CD web <! -- use the CD command to switch hosts or groups -- >
[email protected] (2) [F: 5] $list <! -- list current devices -- >
<! -- support tab key completion, shortcut key Ctrl + D or Ctrl + C to exit the current virtual terminal -- >

4. Ansible module

1) Command module

The command module executes commands on the remote host and does not support the shell features such as pipeline and redirection. The commonly used parameters are as follows:

  • Chdir: the directory to be entered in advance before running the command on the remote host;
  • Create: create a file when the command is running. If the file already exists, the create task will not be executed;
  • Remove: remove a file when the command is running. If the file does not exist, the removal task will not be executed;
  • Executable: indicates the shell program to run the command;

Run the “ls. /” command on all hosts and switch to the / home directory before running. The operation is as follows:

[[email protected] ~]# ansible web -m command -a "chdir=/ ls ./"

2) Shell module

The shell module executes commands in the remote host, which is equivalent to calling the shell process of the remote host, and then opens a subshell to run the command under the shell. It differs from the command module in that it supports shell features such as pipes, redirection, and so on.

Examples are as follows:

[[email protected] ~]# ansible web -m shell -a "echo hello world "        
<! -- output to screen -- > | SUCCESS | rc=0 >>
hello world | SUCCESS | rc=0 >>
hello world

[[email protected] ~]# ansible web -m shell -a "echo hello world > /1.txt"   
<! -- output to 1.txt file -- > | SUCCESS | rc=0 >> | SUCCESS | rc=0 >>

3) Copy module

The copy module is used to copy the specified host file to the specified location of the remote host. Common parameters are as follows:

  • Dest: indicates the location of the destination directory for the copied files, using the absolute path. If the source is a directory, the target is also a directory. If the target file already exists, the original content will be overwritten;
  • SRC: indicates the path of the source file. Relative path and absolute path can be used, and directory can be specified directly. If the source is a directory, the target is also a directory;
  • Mode: indicates the permission of the target file when copying, optional;
  • Owner: indicates the owner of the target file when copying, optional;
  • Group: indicates the group of the target file when copying; optional;
  • Content: indicates that the content copied to the target host cannot be used with SRC, which is equivalent to copying the data specified by content to the target file;

Examples are as follows:

[[email protected] ~]# ansible web -m copy -a "src=/etc/hosts  
dest=/root/a1.hosts mode=777 owner=root group=root"  
<! -- / copy the hosts file of the local computer to the a1.hosts directory under the home directory on all hosts in the web group,  
The authority is 777, the owner is root, and the group is root -- >

4) Host name module

The host name module is used to manage the host names on remote hosts. The commonly used parameters are as follows:


Indicates the host name;

Examples are as follows:

[[email protected] ~]# ansible -m hostname -a "name=test"
<! -- change the host name of to test, but needs bash to take effect -- >

5) Yum module

The yum module is based on the yum mechanism to manage the package of remote host. The commonly used parameters are as follows:

  • Name: package name, with version number. If no version is specified, it will be the latest version by default;
  • State = present | atest | absent: indicates the action to be performed on the package: present indicates the package is installed, latest means the package of the latest version is installed, and absent means the package is unloaded;
  • Disablerepo: when installing with yum, temporarily disable the ID of a warehouse;
  • Enable repo: when installing with yum, temporarily enable the ID of a warehouse;
  • conf_ File: Yum runtime configuration file, instead of using the default configuration file;
  • disable_ gpg_ Check = yes | No: whether to enable the integrity check function;

Examples are as follows:

[[email protected] ~]# ansible web -m shell -a "/usr/bin/rm -rf  
<! -- delete the yum source of Web group host in batch -- >  
[[email protected] ~]# ansible web -m shell -a "/usr/bin/mount  
/Dev / CDROM / MNT "<! -- mass mount disks -- >  
 [WARNING]: Consider using mount module rather than running mount | SUCCESS | rc=0 >>  
Mount: / dev / sr0 is write protected and will be mounted read-only | SUCCESS | rc=0 >>  
Mount: / dev / sr0 is write protected and will be mounted read-only  
[[email protected] ~]# ansible web -m yum -a "name=httpd  
State = present "<! -- batch installation of httpd programs -- >  
[[email protected] ~]# ansible web -m shell -a "rpm -qa | grep httpd"  
<! -- batch view installed httpd packages -- >  
 [WARNING]: Consider using yum, dnf or zypper module rather than running rpm | SUCCESS | rc=0 >>  
httpd-tools-2.4.6-67.el7.centos.x86_64 | SUCCESS | rc=0 >>  
[ [email protected] ~] ා ansible Web - M shell - a "systemctl start httpd" <! -- batch start service -- >  
[ [email protected] ~] # ansible Web - M shell - a "netstat - anptu | grep httpd" <! -- batch monitoring whether the httpd service is started successfully -- > | SUCCESS | rc=0 >>  
tcp6       0      0 :::80                   :::*                    LISTEN      2072/httpd | SUCCESS | rc=0 >>  
tcp6       0      0 :::80                   :::*                    LISTEN      3098/httpd

The management side only sends the yum instruction to the managed end. The managed end can be installed successfully only if there is a available Yum warehouse.

6) Service module

The service module is used to manage the services on the remote host. Common parameters are as follows:

  • Name: the name of the managed service;
  • State = started|stopped| restarted: the action includes start, close or restart;
  • Enable = yes | No: indicates whether to set the service to boot automatically;
  • Runlevel: if enabled is set to boot automatically, you need to define the running targets under which to start automatically;

Examples are as follows:

[[email protected] ~]# ansible web -m service -a "name=httpd
enabled=yes state=restarted"
<! -- set httpd service restart and boot auto start -- >

7) User module

The user module is mainly used to manage the user account on the remote host. Common parameters are as follows:

Name: required parameter, account name;

State = present|absent: create or delete an account. Present means create and absent means delete;

System = yes | No: whether it is a system account or not;

Uid: user uid;

Group: the user’s basic group

Groups: additional groups of users;

Shell: the shell used by default;

Home: user’s home directory;


If the set home directory already exists, whether to move the existing home directory;

Pssworrd: password of the user. Encrypted string is recommended;


User’s annotation information;


Do you want to delete the user’s home directory when state = absent

An example of creating a user is as follows:

[ [email protected]  ~]# ansible web -m user -a "name=user01system=yes uid=502 group=root groups=root shell=/etc/nologinhome=/home/user01  [email protected] "<! -- create a new system user on all hosts of the web group, with uid 502, root as the membership group, user01 as the name and password as the password [email protected] >

4、 PlayBook configuration file

1. Execution profile

Using yaml syntax, playbook configuration file has the characteristics of concise and clear structure. The playbook configuration file, similar to a shell script, is a yaml format file used to hold a task list for specific requirements. Although the ansible command described above can complete a variety of tasks, it is very inefficient to input one by one when configuring some complex tasks.

A more effective solution is to place all the task codes in the playbook configuration file and execute the file with ansible playbook command, which can realize automatic operation and maintenance. Yaml files usually have an extension of. Yaml or. YML.

Yaml syntax is similar to other high-level languages. Its structure is shown by indenting, and items are represented by ‘-‘, ‘:’ is used to separate keys and values, and the whole file begins with ‘-‘ and begins with ‘…’ At the end, as follows:

[ [email protected] ~] # grep - V ^ # / etc / ansible / hosts | grep - V ^ $<! -- view the group information in hosts -- >
[web1][web2][[email protected] ~]# vim /etc/ansible/a.yml                   
<! -- create a.yml file and write the following -- >
----Hosts: web1 <! -- for operations in web1 group -- >  
remote_ User: root <! -- the remote execution user is root -- >  
Tasks: <! -- task list -- >        
-Name: addUser <! -- task name -- >          
User: name = user1 state = present <! -- execute user module and create user -- >          
Tags: <! -- create tag tag -- >          
-AAA <! -- tag is AAA -- >        
-Name: addgroup <! -- task name -- >          
Group: name = root system = yes <! -- execute the group module and create a group -- >          
Tags: <! -- create tag tag -- >          
-BBB <! -- tag is BBB -- >
-< web2: for web2  
remote_ User: root <! -- the remote execution user is root -- >  
Tasks: <! -- task list -- >        
-Name: copy file to Web          
Copy: SRC = / etc / passwd dest = / home <          
Tags: <! -- create tag tag -- >          
-CCC <! -- tag is CCC -- >

There are spaces after all “-” and “:”, and pay attention to indenting and alignment, as shown in the following figure:

The core elements of playbook include:

Hosts: the target host of the task. Multiple hosts are separated by colons. Generally, the grouping information in / etc / ansible / hosts is called;

remote_ User: on the remote host, the default identity of running this task is root;

Tasks: tasks, i.e. specific tasks defined and operation lists defined by modules;

Handlers: triggers, similar to tasks, are only triggered under specific conditions.

When the status of a task is changed after running, it can be triggered by notifying the corresponding handler;

Roles: role, which separates hosts and is a specific structure set composed of tasks, handlers, etc;

The tasks defined in the playbook file need to be called and executed through the ansible playbook command. The ansible playbook command is used as follows:

ansible-playbook [option] /PATH/TO/PLAYBOOK.yaml

The functions of the [option] section include:

  • – syntax check: check the syntax of yaml file;
  • -C (- check): pre test, will not change any settings of the target host;
  • – list hosts: list the hosts affected by yaml file;
  • – list tasks: list the tasks of yaml file;
  • – list Tags: List tags in yaml file;
  • -T tags (- tags = tags): only tasks with specified tags are executed;
  • —skip-tags=SKIP_ Tags: it means to execute other tasks in addition to the task with the specified tag;
  • —start-at-task=START_ At: run down from the specified task;

An example of executing playbook is as follows:

[ [email protected] ~] ා ansible playbook -- syntax check / etc / ansible / a.yml <! -- syntax checking -- >
Playbook: / etc / ansible / a.yml <! -- no error reported -- >
[ [email protected] ~] # ansible playbook - C / etc / ansible / a.yml    
... <! -- omit part of the content -- >       : ok=3    changed=1    unreachable=0    failed=0       : ok=2    changed=1    unreachable=0    failed=0
<! -- the returned result indicates that there are no errors and all can be executed successfully. >

[[email protected] ~]# ansible-playbook --list-hosts /etc/ansible/a.yml
<! -- List hosts in a.yml file -- >
[ [email protected] ~] ා ansible playbook -- List tasks / etc / ansible / a.yml <! -- List tasks -- >
[ [email protected] ~] ා ansible playbook -- List tags / etc / ansible / a.yml <! -- List tags -- >
[ [email protected] ~] # ansible playbook / etc / ansible / a.yml
[[email protected] ~]# ssh tail -1 /etc/passwd 
<! -- confirm the execution result -- >
[[email protected] ~]# ssh ls -ld /home/passwd
-Rw-r -- R --. 1 root root root 2342 July 23 16:06 / home / passwd
<! -- in general, execute the "- C" command for pre-test, and then execute the. YML file after there is no problem. >

Usually, ansible-playbook – C / path / to is executed first/ PLAYBOOK.yaml Command to test, and then execute ansible playbook / path / to/ PLAYBOOK.yml Command.

2. Trigger

For tasks that need to be triggered before they can be executed, if you want to trigger other tasks based on the successful execution of the tasks previously defined in tasks, you need to define handlers. For example, after modifying the configuration file of the target host through the ansible module, if the task is executed successfully, a trigger can be triggered, in which the service restart operation of the target host is defined to make the configuration file effective. The handler trigger has the following characteristics:

  • Handlers is one of the conditional mechanisms provided by ansible.
  • Handlers are similar to tasks, but they only trigger execution when they are notified by the task.
  • Handlers are only executed after all tasks have been executed.
  • And even if it is notified many times, it will only execute once.
  • The handlers are executed in the order defined.

Examples of using the handlers trigger are as follows:

[ [email protected] ~] # SSH netstat - anpt | grep 80 <! -- query the port monitored by 100.20 host -- >  
tcp6       0      0 :::80         :::*          LISTEN      94858/httpd  
<! -- you can see that it is listening to port 80. Now it is changed to port 8080 through script and makes it effective. >  
[[email protected] ~]# vim /etc/ansible/httpd.yml  
<! -- edit httpd.yml File, write the following -- >  
- hosts: web1  
  remote_user: root  
        - name: change port  
          command: sed -i 's/Listen\ 80/Listen\ 8080/g' /etc/httpd/conf/httpd.conf  
          Notify: <! -- configure trigger conditions -- >  
                - restart httpd server <! - after the task is completed, call the trigger called "restart httpd server" - >  
  Handlers: <! -- configure triggers -- >  
        -Name: restart httpd server <  
          Service: name = httpd state = restarted <! -- trigger task is to restart httpd Service -- >  
<! -- after writing, save and exit -- >  
[ [email protected]  ~]# ansible-playbook -C /etc/ansible/ httpd.yml <! -- pre test -- >  
[ [email protected]  ~]# ansible-playbook  /etc/ansible/ httpd.yml <! -- execute script -- >  
[ [email protected] ~] # SSH netstat - anpt | grep 8080 <! -- the remote host has run port 8080 -- >  
tcp6       0      0 :::8080        :::*         LISTEN      103594/httpd

3. Role

If the files of various tasks are stored in a certain directory, the directory is the role. Roles are generally stored in the / etc / ansible / roles / directory. The default role directory can be adjusted through the ansible configuration file. There are many subdirectories under the / etc / ansible / roles / directory. Each subdirectory corresponds to a role, and each role also has its own directory structure, as shown in the following figure:

Don't make the operation and maintenance too busy. This article explains the automatic operation and maintenance of ansible in detail

/Etc / ansible / roles / is a collection of roles. There are user-defined subdirectories in this directory:

  • MariaDB: MySQL role;
  • Apache: httpd role;
  • Nginx: nginx role;

The definition of each role is organized in a specific hierarchical directory structure. Take MariaDB (MySQL role) as an example

  • Files: stores the files called by copy or script modules;
  • Templates: the directory where the template module is stored to find the required template files, such as MySQL configuration file template;
  • Tasks: the directory where the task is stored;
  • Handlers: the directory to store the relevant trigger execution;
  • Vars: the directory where the variables are stored;
  • Meta: used to store the metadata of this role;
  • Default: the directory where the default variables are stored. The default variables used by this role are defined in the file;

In the above directory, tasks, handlers, vars, meta, default should contain at least one main.yml You can also have other. YML files in this directory, but you need to main.yml Include other. YML files with the include directive.

After you have the role, you can call the role directly in the yaml file (playbook configuration file). The example is as follows:

- hosts: web  remote_user: root  
- mysql  
<! -- call role name -- >  
- httpd             
<! -- call role name -- >

You can call only one role or multiple roles. After a role is defined, it can be executed by using the ansible playbook pagebook file.

At this point, ansible will go to the role collection directory (/ etc / ansible / roles) to find the MySQL and httpd directories, and then run all the codes under the MySQL and httpd directories in turn.

Here is an example of installing and configuring the MariaDB database

Demand analysis:

  • After the installation, upload the configuration file prepared in advance to the remote host, restart the service, and then create a new testdb database, and allow test users to have all permissions.
  • The managed host configures the yum warehouse and configures it by itself. If the managed end can connect to the Internet, it can directly point the yum warehouse to the Internet.

From: 51CTO blog – junweiqi I…

Newly organized2TBTechnical dry goods: includingArchitect practice course, big data, docker container, system operation and maintenance, database, redis, mogodb, e-book, java basic course, Java practical project, elk stack, machine learning, bat interview intensive lecture videoEtc. You just need to「 Migrant workers’ technology road “WeChat official account dialog box replies to key words:1024All information can be obtained.