Principle of ansible, installation, various modules in detail

What is ansible?

Ansible is a new automated operation and maintenance tool. It is developed based on Python and combines the advantages of many operation and maintenance tools (puppet, cfengine, chef, func, fabric). It realizes the functions of batch system configuration, batch program deployment, batch running commands and so on.Ansible is module-based and does not have the capacity to deploy in bulk.What really has a bulk deployment is the modules that ansible runs, and ansible only provides a framework.Mainly include:
(1) connection plugins: responsible and monitored for communication;
(2) host inventory: The host for the specified operation is the host for which monitoring is defined in the configuration file;
(3) various module core modules, command modules, custom modules;
(4) With the help of plug-ins, log mail and other functions can be completed;
(5) playbook: When a script performs multiple tasks, it is not necessary for a node to run multiple tasks at once.

ansible feature

1. The deployment is simple, only the Ansible environment needs to be deployed on the master side, and the controlled side does not need to do anything.

2. Use SSH protocol to manage devices by default;
3. There are a large number of routine operation modules, which can achieve the vast majority of daily operations;
4. Simple configuration, powerful function and scalability;
5. Support API and custom modules, which can be easily extended through Python;
6. Customize powerful configuration and state management through Playbooks;
7. Lightweight, there is no need to install agent on the client. When updating, only one update is needed on the operator.
8. Idempotency, a task's line of 1 or n times has the same effect, not due to repeated execution

Ansible architecture and how it works

Ansible: Ansible Core Program.
HostInventory: Records host information managed by Ansible, including port, password, ip, etc.
Playbooks: Playbooks YAML format file, where multiple tasks are defined in one file, defining which modules the host needs to call to complete the function.
CoreModules: Core module, the main operation is to complete the management task by calling the core module.
CustomModules: Custom modules that support multiple languages by completing functions that core modules cannot do.
ConnectionPlugins: Connection Plugins, used for Ansible and Host communication

ansible task execution mode

Ansible systems can be divided into two types by the way the control host operates on the managed nodes, adhoc and playbook:

ad-hoc mode (point-to-point mode)
Use a single module to support batch execution of a single command.The ad-hoc command is a command that can be entered quickly and does not need to be saved.Is equivalent to a shell in bash.
playbook mode (script mode)
Is Ansible's primary management and key to its powerful functionality.playbook accomplishes one type of functionality through multiple task collections, such as installation and deployment of Web services, batch backup of database servers, and so on.playbook can be simply understood as a configuration file that combines multiple ad-hoc operations.

ansible execution process

Simple understanding is that when Ansible runs, it first reads the configuration in ansible.cfg, obtains a list of management hosts in Inventory according to the rules, executes the configured tasks in these hosts in parallel, and finally waits for the results to be returned.

ansible command execution process

1. Load your own configuration file, default/etc/ansible/ansible.cfg;
2. Find the corresponding host configuration file, find the host or group to execute;
3. Load your own module file, such as command;
4. Generate a temporary python file (py thon script) from a module or command through ansible and transfer the file to a remote server;
5.ansible/tmp/XXX/XXX.PY file corresponding to the home directory of the executing user;
6. Give file+x execute permission;
7. Execute and return the results;
8. Delete temporary py file, sleep 0 exits;

Three commonly used automated layout tools in the market

Ansible: ssh-based protocol does not require proxy, suitable for small and medium-sized applications
Saltstack: Agent agent software is required (more efficient execution)
Puppet:ruby, powerful and complex to configure for very large environments

ansible environment deployment

Main end:
Controlled end 01:
Controlled end 02:

#Firewall shutdown for all three hosts
 [root@localhost ~]# systemctl stop firewalld.service 
 [root@localhost ~]# setenforce 0

#Master Install ansible
yum install -y epel-release  //Install epel source
yum install ansible -y

ansible --version          //View ansible version
ansible 2.9.3
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Aug  4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]

yum install tree -y
tree /etc/ansible/      //Tree structure display folder
├── ansible.cfg    #ansible configuration file
├── hosts         #ansible's main repository for storing information about remote hosts that need to be managed
└── roles     #

cd /etc/ansible
vim hosts       //Configure host list

#Push Public Key
ssh-keygen -t rsa
[root@localhost ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/idrsa):  #Enter
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):  #Input password
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/idrsa.
Your public key has been saved in /root/.ssh/
The key fingerprint is:
SHA256:QnRuJjR10Jy6HuyQxQz3ccWML8iHCdQ1HZx5ba57Ak0 root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
|      +o==.ooBo+.|
|     o.+o. o.B +|
|      o=+=  . + |
|     . +=  o E .|
|      .+S. . + . |
|      o.+   . o  |
|       + .   . . |
|        o     o .|
|               o |

#Push Public Key to Other Host
ssh-copy-id root@
ssh-copy-id root@    //Configure key pair validation

#View the time of two hosts on the controlled side
[root@localhost ~]# ansible -m command -a 'date'
Enter passphrase for key '/root/.ssh/idrsa': | CHANGED | rc=0 >>
Sun Feb  9 09:02:44 CST 2020

[root@localhost ~]# ansible mysql -m command -a 'date'
Enter passphrase for key '/root/.ssh/idrsa': | CHANGED | rc=0 >>
Sun Feb  9 09:03:11 CST 2020

#Delivery Free
[root@localhost ~]# ssh-agent bash #ssh proxy
[root@localhost ~]# ssh-add #Add Password

[root@localhost ~]# ansible webserver -m command -a 'date' | CHANGED | rc=0 >>
Sun Feb  9 09:05:08 CST 2020

----------ansible Command Line Module-------------

-------command module-------

Command format: ansible [Host] [-m Modular] [-a args]
ansible-doc -l     //List all installed modules Note: Quit by q
ansible-doc -s yum   //-s Lists yum module description information and action
#ansible default module, all: on behalf of all hosts (as long as they are online), -a+''specifies parameters
[root@localhost ~]# ansible all -a 'date' | CHANGED | rc=0 >>
Sun Feb  9 09:16:22 CST 2020 | CHANGED | rc=0 >>
Sun Feb  9 09:16:22 CST 2020

ansible -m command -a 'date'  //Specify ip execution date
ansible webserver -m command -a 'date'       //Specify Category Execution date
ansible mysql -m command -a 'date'       
ansible all -m command -a 'date'        //All hosts host execute date command
ansible all -a 'ls /'      If not added-m Module runs by default command Modular

-----cron module-----

Two states ( state): present Represents an addition (which can be omitted), absent Represents removal.
ansible-doc -s cron      //View cron module information
#Once per minute, job: operation, echo output heihei,name:name
ansible webserver -m cron -a 'minute="/1" job="/bin/echo heihei" name="test cron job"' | CHANGED => {
    "ansiblefacts": {
        "discoveredinterpreterpython": "/usr/bin/python"
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test cron job"
#View periodic planned tasks
[root@localhost ~]# ansible webserver -a 'crontab -l' | CHANGED | rc=0 >>
#Ansible: test cron job
/1     /usr/bin/echo heihei

ansible webserver -a 'crontab -l'
ansible webserver -m cron -a 'name="test cron job" state=absent'    //Remove the scheduled task, name=None if it is not named

-----user module-----

user Module is requested by useradd, userdel, usermod Three directives
ansible-doc -s user
ansible all -m user -a 'name="test01"'    //Create user test01 | CHANGED => {
    "ansiblefacts": {
        "discoveredinterpreterpython": "/usr/bin/python"
    "changed": true, 
    "comment": "", 
    "createhome": true, 
    "group": 1001, 
    "home": "/home/test01", 
    "name": "test01", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
} | CHANGED => {
    "ansiblefacts": {
        "discoveredinterpreterpython": "/usr/bin/python"
    "changed": true, 
    "comment": "", 
    "createhome": true, 
    "group": 1001, 
    "home": "/home/test01", 
    "name": "test01", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001

ansible mysql -m command -a 'tail /etc/passwd'
ansible webserver -m user -a 'name="test01" state=absent'    //Delete user test01

-----group module-----

group Module requests groupadd, groupdel, groupmod Three instructions.
ansible-doc -s group
ansible mysql -m group -a 'name=mysql gid=306 system=yes'

ansible mysql -a 'tail /etc/group'
[root@localhost ~]# ansible mysql -a 'tail /etc/group' | CHANGED | rc=0 >>

ansible mysql -m user -a 'name=test02 uid=306 system=yes group=mysql'
ansible mysql -a 'tail /etc/passwd'

ansible mysql -a 'id test02' | CHANGED | rc=0 >>
uid=306(test02) gid=306(mysql) groups=306(mysql)

-------copy module-----------

ansible-doc -s copy
#src original, dest target, owner:Specify file permissions
ansible mysql -m copy -a 'src=/etc/fstab dest=/opt/fstab.back owner=root mode=640'
ansible mysql -a 'ls -l /opt' | CHANGED | rc=0 >>
total 4
-rw-r-----. 1 root root 541 Feb  9 09:44 fstab.back
drwxr-xr-x. 2 root root   6 Mar 26  2015 rh

ansible mysql -a 'cat /opt/fstab.back'

#contest: Specify content to generate a new file
ansible mysql -m copy -a 'content="hello heihei!"
dest=/opt/fstab.back'  //Write hello heihei! To/opt/fstab.back
ansible mysql -a 'cat /opt/fstab.back' | CHANGED | rc=0 >>
hello heihei!


ansible-doc -s file
ansible mysql -m user -a 'name=mysql system=yes'
ansible mysql -m group -a 'name=mysql system=yes'
#Path:Specify file path
ansible mysql -m file -a 'owner=mysql group=mysql mode=644 path=/opt/fstab.back'        //Modify file ownership group permissions, etc.
ansible mysql -m file -a 'path=/opt/ src=/opt/fstab.back state=link'      //Link file to set/opt/ to/opt/fstab.back
ansible mysql -m file -a "path=/opt/fstab.back state=absent"               //Delete a file
ansible mysql -m file -a "path=/opt/test state=touch"             Create a file

-----ping Modular-------
ansible all -m ping | SUCCESS => {
    "ansiblefacts": {
        "discoveredinterpreterpython": "/usr/bin/python"
    "changed": false, 
    "ping": "pong"
} | SUCCESS => {
    "ansiblefacts": {
        "discoveredinterpreterpython": "/usr/bin/python"
    "changed": false, 
    "ping": "pong"


ansible-doc -s service
[root@ab ~]# yum install -y httpd
[root@aa ~]# Ansible webserver - a'systemctl status httpd'//View web server httpd status
 ansible webserver -m service -a 'enabled=true name=httpd state=started'  #Close with stop | CHANGED => {
    "ansiblefacts": {
        "discoveredinterpreterpython": "/usr/bin/python"
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 

      //service httpd start
[root@ab ~]# systemctl status httpd //Check to see if it is turned on

------shell Modular-----
ansible-doc -s shell
[root@localhost ~]# ansible webserver -m shell -a 'echo abc123|passwd --stdin chen' | CHANGED | rc=0 >>
Changing password for user chen.
passwd: all authentication tokens updated successfully.
       //Create user Password for user using no interactive mode

---------script module---------

#Create a script locally so that all other controlled end hosts can execute the script together
ansible-doc -s script
echo "hello ansible from script"> /opt/script.txt

chmod +x
ansible mysql -m script -a ''

[root@localhost ~]# ansible mysql -a 'cat /opt/script.txt' | CHANGED | rc=0 >>
hello ansible from script

-----yum module-----

ansible-doc -s yum
ansible mysql -m yum -a 'name=httpd'           //yum install httpd | CHANGED => {
    "ansiblefacts": {
        "discoveredinterpreterpython": "/usr/bin/python"
    "changed": true, 
    "changes": {
        "installed": [
    "msg": "", 
    "rc": 0, 
    "results": [

[root@ac ~]# rpm -q httpd

ansible mysql -m yum -a 'name=httpd state=absent'     //Uninstall zsh
[root@ac ~]# rpm -q httpd

-----setup module-------

ansible-doc -s setup
ansible mysql -m setup           //Get facts information for mysql group host

Tags: ansible MySQL ssh Python

Posted on Sun, 09 Feb 2020 09:49:02 -0800 by like_php