Ansible Automation Operation and Maintenance Installation and Common Module Detailed Module

Ansible, as an open source operation and maintenance automation tool that has become more and more popular this year, can realize operation and maintenance automation through Ansible, improve the work efficiency of operation and maintenance engineers, and reduce human errors. Ansible can achieve various management tasks through its own integrated very rich modules, with more than a thousand of its own modules. More importantly, it is simple to operate, but provides very rich functions. In the field of operation and maintenance, it can do almost anything.
.
Since its release in 2012, Ansible has quickly become popular around the world. Its characteristics are as follows:

1. Ansible is developed based on Python It is relatively easy for operation and maintenance engineers to develop its secondary development
2, Ansible’s rich built-in modules can almost meet all requirements
3, the management mode is very simple, one command can affect thousands of hosts
4 , Clientless mode, the bottom layer communicates via SSH

We can interact with Ansible in four ways. I only studied two of them here, which is enough for daily work. They are as follows:

1. Ad-Hoc command set: user directly invokes Ansible tool set through Ad-Hoc command set to complete the task.
2. Playbooks: The user pre-programs ansible playbooks, and executes the tasks in order by executing the pre-arranged task set in the playbooks.

1. Ansible working set:
.
Ansible working set includes inventory, Modules, Plugins and API, among which inventory (list) is used To manage the device list, it can be achieved by grouping, and the call to the group directly affects all the hosts in the group; modules are various execution modules, and almost all management tasks are performed through modules; plugins provide various additional functions; API Provide an interface for programmers, based on which can do Ansible secondary development.
.
Ansible can control and change multiple hosts through a single command or configuration file. The following will be written in order from the installation and configuration.

2, playbook configuration file
.
The playbook configuration file uses YAML syntax, which is concise and clear, and has a clear structure. The playbook configuration file is similar to a shell script. It is a YAML format file used to save a task list for specific needs. Although the ansible command introduced above can accomplish various tasks, when configuring some complex tasks, the input one by one becomes very inefficient. A more effective solution is to place all task codes in the playbook configuration file, and execute the file with the ansible-playbook command to achieve automated operation and maintenance. The extension of YAML files is usually .yaml or .yml.
.
Ansible installation and configuration
.
The environment is as follows:
Ansible automated operation and maintenance installation And detailed explanation of common modules
1. Preparations:
1. Local yum Warehouse: https://pan.baidu.com/s/1-ERCVm6QaUA4XQd_X5Kwow Extraction code: exnp version: Ansible 2.3.1.0
2, if the machine is connected to the Internet, it can point to the Internet yum warehouse
3, it is used by default TCP 22 communicates with the client. If there is any change, you need to set the firewall to let it go.
Second, install Ansible:

[[emailprotected] /]# mount / dev/sr0 /media/ # Mount yum warehouse
[[emailprotected] /]# rm -rf /etc/yum.repos.d/* # Delete or remove other configuration files in the yum directory
[[email Protected] /]# vim /etc/yum.repos.d/a.repo
[aaa]
baseurl=file:///media
gpgcheck=0< br />[[email Protected] yum.repos.d]# yum clean all #Clear yum cache
[[email Protected]]# yum -y install ansible #Install Ansible
[[email Protected] yum.repos.d]# ansible --version #You can view this information, indicating that the installation was successful
ansible 2.3.1.0
config file = /etc/ansible/ansible.cfg
.. ... ..............

I used the Internet yum repository to install here, that is, ansible 2.4.2.0.
.
The installation has been completed, but if you want to use Ansible normally, you still need to solve a problem, that is, when controlling multiple hosts, if you need to enter the peer password every time you execute a command or script, It seems very tasteless, so you also need to create an SSH interactive login, as follows:
.
The following operations are performed on the Ansible server:

[[emailprotected] ~]# ssh-keygen- t rsa #Generate a key pair on the Ansible server, and press Enter by default after execution.
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh /id_rsa): #default press enter
Enter passphrase (empty for no passphrase): #default press enter
Enter same passphrase again: #default press enter
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is: #default press enter
SHA256: zhd2++KvByxFPE4ZKmDdmTHp6cjsuIEz5M26QrkBfes [email protected]
The key's randomart image is: #default press enter
+---[RSA 2048]----+
| o.. o*.o |
|. .. =o* |
|. ...=. |
|... .oo |
|. o.. oSooo . |
| +o.+ o+.ooo. |
| . += +oo .... |
| o E+.... ... |
| .o... .o=o |
+----[ SHA256]-----+
#So far, the key pair has been generated, hidden and stored in the home directory of the current user.
[[email Protected] ~]# ls -a | grep ssh #View
.ssh
[[email Protected] ~]# cd .ssh
[[email Protected] .ssh]# ls #View the files in the .ssh directory, there are public and private keys
id_rsa id_rsa.pub known_hosts
[[email Protected] ~]# ssh-copy-id [email Protected] #Copy the public key to the host 192.168.1.20
[emailprotected]'s password: #Enter the root user password of the host 1.20
[[emailprotected] ~]# ssh-copy-id [emailprotected] #Copy the public key to the host 192.168.1.30
[email protected]'s password: #Enter the root user password of the host 1.30
#In the actual production environment, the root identity will not be used. Change the copy public The user specified in the key can be used.
[[email Protected] ~]# ssh 192.168.1.20 #Test whether you can log in without a password
Last login: Tue Jul 23 08:11:39 2019 from 192.168.1.88
[[email protected] ~]# exit #Exit the shell environment of 192.168.1.2
[[email protected] ~]# ssh 192.168.1.30 #Test whether it is possible to log in without password
Last login: Tue Jul 23 08:43 :16 2019 from 192.168.1.88
[[email Protected] 2 ~]# exit #Exit the shell environment of 192.168.1.3

3. Ansible configuration:
inventory is the configuration file for Ansible to manage host information, which is equivalent to the system’s hosts file function. It is stored in /etc/ansible/hosts by default. In the hosts file, devices are organized by groups. Ansible defines hosts and groups through inventory. Instead of using the default /etc/ansible/hosts, you can specify inventory through ansible -i new inventory path. I will directly use the default path here.
.
1. Add the hosts that need to be managed in groups:
.
Before management, you must first write the hosts file, because Ansible adds the hosts file by grouping the device list To realize the management of equipment. In the hosts file, [] contains the group name, and the device list supports domain names and IP addresses. By default, the device is managed by accessing port 22 (SSH). If the target host uses a non-default SSH port, you can also Use a colon and port number after the name to indicate the unit, separate units by line, and also support wildcards.
.

[[email Protected] ~]# vim /etc/ansible/hosts #Edit the manifest file and write the following at the end of the file
........ ............. #Omit part of the content
[web] #Define a group named web, the following is the host in the web group
192.168.1.20
192.168.1.30
[test01] #Define a group named test01, the following are hosts in the test01 group
www.test.com:222 #If the target host uses a non-default SSH port, You can specify the port number after the domain name
www[2:5].test.com #[2:5] means all numbers between 2 and 5, such as www2.test.com, www3.test. All hosts of com .......
192.168.1.4:66 #You can also specify a non-default port number after the IP address.
#After writing the host to be managed, save and exit. . Note that the file contains an implicit group "all", which means all hosts.

.
After the configuration is complete, you can perform remote operations on the group defined by hosts, or you can operate on one or more hosts specified in the group, as follows:

 [[email protected] ~]# ansible web -m command -a "systemctl status httpd" --limit "192.168.1.20"
#View the status of the httpd service on the 192.168.1.20 host in the web group
192.168.1.20 | FAILED | rc=3 >>
● httpd.service-The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd. preset: disabled)
Active: inactive (dead)
Docs: man:httpd(8)
man:apachectl(8)non-zero return code
#It can also be like this:
[[email protected] ~]# ansible 192.168.1.20 -m command -a "systemctl status httpd"
192.168.1.20 | FAILED | rc=3 >>
● httpd.service-The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd. preset: disabled)
Active: inactive (dead)
Docs: man:httpd(8)
man:apachectl( 8)non-zero return code
[[email protected] ~]# ansible 192.168.1.* -m command -a "systemctl status httpd"
#Query all hosts on the 192.168.1.0 network segment httpd service status
192.168.1.20 | F AILED | rc=3 >>
.................
192.168.1.30 | FAILED | rc=3 >>
... ..............

Four. Ansible command:

[[email protected] ~]#ansible # After inputting ansible, press the tab key twice to view all related commands of ansible
ansible ansible-doc ansible-playbook-2
ansible-2 ansible-doc-2 ansible-playbook-2.7
ansible-2.7 ansible-doc-2.7 ansible-pull
..........................

< strong>Command 1, ansible:
.
Ansible is one of the most frequently used commands in the production environment, mainly used in the following scenarios:
.

  • Temporary maintenance, irregular, temporary tasks that need to be done, also called non-solidified requirements.
  • Temporary one-time operation.
  • Calling the secondary development interface.

    The available options of Ansible are as follows:

    • -v: Output detailed execution process information, and all information about the execution process can be obtained.
    • -i PATH: Specify inventory information, the default is /etc/ansible/hosts.
    • -f: The number of concurrent threads, the default is 5 threads.
    • –private-key=PRIVATE_KEY_FILE: Specify the key file.
    • -m: Specify the module used for execution.
    • -M: Specify the storage path of the module, the default is /usr/share/ansible, or you can set the default path through ANSIBLE_LIBRARY.
    • -a: Specify module parameters.
    • -u: Specify which user the remote host runs the command as.
    • -l: Limit the running host, which is equivalent to “–limit”.
    • –list-hosts: List a list of eligible hosts without executing any commands.

Usage example 1 (you need to define the web group in the /etc/ansible/hosts file in advance):

 [[email Protected] ~]# ansible all -f 5 -m ping 
192.168.1.30 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.1.20 | SUCCESS => {
"changed": false,
"ping": "pong"< br />}

Usage example 2:

[[email protected] ~]# ansible web --list #List all hosts in the web group 
hosts (2):
192.168.1.20
192.168.1.30
#The above means that the web contains two hosts, 1.20 and 1.30 respectively

Usage example 3:

[[email protected] ~]# ansible web -m command -a "df -hT" #Display the disk usage of the host in the web group
192.168.1.20 | SUCCESS | rc=0 >>
File system type capacity Used Usable Used% Mount Point
/dev/mapper/centos-root xfs 50G 5.8G 45G 12% /
devtmpfs devtmpfs 895M 0 895M 0% /dev
.... ........................ #The omitted part

192.168.1.30 | SUCCESS | rc=0 >>
File system type capacity has been used, available and used% mount point
/dev/mapper/cl-root xfs 17G 5.5G 12G 33% /
devtmpfs devtmpfs 897M 0 897M 0% /dev
tmpfs tmpfs 912M 84K 912M 1% /dev/shm
............................ #The omitted part

Ansible’s return result is very friendly, generally three types are used The colors represent the execution results: red, green, and orange yellow (that color is harmonized). Among them, red means there is an abnormality in the execution process; orange and yellow means that the target has a status change after the command is executed; green means the execution is successful and the target host is not modified.
Command 2, ansible-doc:

Ansible-doc is used to query the description of the ansible module documentation, similar to the man command, with detailed usage for each module Description and application case introduction.

[[email protected] ~]# ansible-doc -l | wc -l #List the supported modules
1378 #There are 1378 supported modules
[[emailprotected ] ~]# ansible-doc ping #Query the description information of the ping module
> PING (/usr/lib/python2.7/site-packages/ansible/modules/system/ping.py)
< br /> 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
................#Omit part of the content

Command 3. Ansible-playbook:
.
Ansible-playbook is the most commonly used command in daily applications, similar to the sh or source commands in Linux, used to perform a series of tasks. Its working mechanism is: to achieve centralized processing tasks by reading the pre-written playbook file. 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 (the playbook.yml file needs to be written in advance, and it is best to specify the absolute path of the playbook.yml):

[[email Protected] ~]# ansible-playbook playbook.yml

Command 4. ansible-console:
.
ansible-console is ansible An interactive tool for us, similar to cmd in Windows and shell in Linux. You can use the various built-in commands of ansible on the virtual terminal of ansible-console like a shell. This provides a good experience for users who are accustomed to shell interaction. All operations are similar to the shell, and it supports tab key completion. . The specific operation is as follows:

[[email Protected] ~]# ansible-console #Connect to interactive tools
Vault password: #ansible 2.4.2.0 will prompt to enter a password, just enter it and press back The car is fine, no null value is allowed
Welcome to the ansible console.
Type help or? To list commands.

[emailprotected] (2)[f:5] $ cd web #Switch to web group
[emailprotected] (2)[f:5]$ list #List the hosts in the group
192.168.1.20
192.168.1.30
[email protected] (2)[f:5]$ ifconfig ens33 #Query the network card information of each host
[emailprotected] (2)[f:5]$ exit #Exit the ansible-console environment

V. Introduction to the modules that come with Ansible:

1. Command module:

The command module executes commands on the remote host. It does not support shell features such as pipes and redirection. The rest is similar to the shell. Common parameters are as follows:

  • chdir: It is required before running the command on the remote host The directory entered in advance.
  • creates: Create a file when the command runs. If the file already exists, the creation task will not be executed.
  • removes: Remove a file while the command is running. If the file does not exist, the removal task will not be executed.
  • executeble: Specify the shell program that runs the command.
[[emailprotected] ~]# ansible all -m command -a "chdir=/home ls ./"
#Run on all hosts" ls ./" command, switch to the /home directory before running.

2. Shell module (equivalent to a universal module, can execute most commands):
.
The shell module executes commands on the remote host, which is equivalent to calling the remote The host’s shell process, and then open a subshell under the shell to run commands. The difference from the command module is that it supports shell features, such as pipe characters, redirection, and so on.
.

[[email Protected] ~]# ansible web -m shell -a'echo "hello world" >> /tmp/hello.txt'
#in the web group Write a txt file on the host
192.168.1.20 | SUCCESS | rc=0 >>

192.168.1.30 | SUCCESS | rc=0 >>

[[ email protected] ~]# ansible web -m shell -a 'cat /tmp/hello.txt' #View the written file
192.168.1.30 | SUCCESS | rc=0 >>
hello world

192.168.1.20 | SUCCESS | rc=0 >>
hello world

3, copy module:

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

  • src: Point out the source file path, you can use relative path and absolute path. Support directly specifying the directory, if the source is a directory, the target should also be a directory.
  • dest: Point out the location of the target directory of the copied file, use an absolute path, and support directly specifying the directory. If the source is a directory, the target must also be a directory. If the target already exists, the original content will be overwritten.
  • mode: Indicate the permission of the target file when copying, optional.
  • owner: Point out the owner of the target file when copying, optional.
  • group: Indicate the group of the target file when copying, optional.
  • content: Point out the content copied to the target host. It cannot be used with src, which is equivalent to copying the data specified by content to the target file.
[[email protected] ~]# ansible web -m copy -a "src=/etc/hosts dest=/tmp/ mode=777 owner=nobody group= root"
#Copy the /etc/hosts file of this machine to the host in the web group, and specify the authority as 777, the owner as nobody, and the belonging group as root.

4. Hostname module:

The hostname module is used to manage host names. Common parameters are as follows:

name: Specify the host name.

[[email protected] ~]# ansible 192.168.1.20 -m hostname -a "name=web1"
#Change the hostname of host 192.168.1.20 to web1< br />192.168.1.20 | SUCCESS => {
ansible_facts: {
ansible_domain:,
ansible_fqdn: web1,
ansible_hostname web1
ansible_nodename: web1
},
changed: true
name: web1
}
[[email protected] ~]# hostname #View on the 192.168.1.20 host
web1
[[email protected] ~]# cat /etc/hostname #View on the 192.168.1.20 host
web1
#After changing the host name, you need to restart to make the new host name take effect.

5, yum module:

The yum module is based on the yum mechanism. For remote host management packages, the common parameters are as follows:

  • name: The name of the program package, you can carry the version number. If the version is not specified, the latest version will be installed by default.
  • state=present | latest | absent: specify the operation performed on the package, present means installing the package, latest means installing the latest version of the package, and absent means uninstalling the package.
  • disablerepo: When installing with yum, temporarily disable the ID of a certain repository.
  • enablerepo: When installing with yum, temporarily enable the ID of a certain repository.
  • conf_file: The configuration file when yum is running, instead of using the default configuration file.
  • diable_gpg_check=yes | no: Whether to enable the integrity check function.
[[email protected] ~]# ansible web -m yum -a "name=httpd state=present" 

6. Service module:

Service module is a module used to manage services on remote hosts, common The parameters are as follows:

  • name: The name of the managed service.
  • state=started | stopped | restarted | reloaded: Actions include starting, shutting down, restarting and reloading the configuration file.
  • enabled=yes | no: Indicates whether to set the service to start automatically after booting.
  • runlevel: If enabled is set to start automatically at boot, it must be defined to automatically start under those run targets, such as 2/3/4/5.
[[emailprotected] ~]# ansible web -m service -a "name=httpd state=started enabled=yes"
#Start httpd service, And set to boot from the start.

7. User module:

The user module is used to manage user accounts on remote hosts. Common parameters are as follows:

< ul>

  • name: required parameter, account name.
  • state=present | absent: create or delete an account, present means create, absent means delete.
  • system=yes | no: Whether it is a system account.
  • uid: User UID.
  • group: The user’s basic group.
  • groups: Additional groups for the user.
  • shell: The shell used by default.
  • home: The user’s home directory.
  • move_home=yes | no: If the set home directory already exists, whether to move the existing home directory.
  • password: The user’s password.
  • comment: user’s comment information.
  • remove=yes | no: When state=absent, whether to delete the user’s home directory.
  • [[emailprotected] ~]# ansible web -m user -a'name=user1 system=yes uid=501 group=root groups=sshd shell=/sbin /nologin home=/home/user1 password=user1 comment="test user"'
    #Create a user named user1
    [[emailprotected] ~]# ansible web -m user -a " name=user1 remove=yes state=absent"
    #Delete the user1 user just created

    8, group module:

    The group module is used to manage groups and is used to create or delete groups. Common parameters are as follows:

    • gid: the gid of the specified group
    • name: the name of the specified group
    • state=present | absent: create or delete
    • system=yes | no: whether it is a system group
    [roo[emailprotected ] ~]# ansible web -m group -a'name=test gid=300 state=present system=yes'
    #Create a system group with a gid of 300 and a group name of test.
    [[email Protected] ~]# ansible web -m group -a ‘name=test gid=300 state=absent system=yes‘
    #Delete the group just created.

    9. Mount module:

    The mount module is used to mount the file system. Common parameters are as follows:

      < li>src: the device or file system to be mounted
    • name: specify the mount point
    • fstype: specify the file system type
    • ots=w | r | o: Set the file read and write type, which can be used in combination.
    • state=present | absent | mounted | unmounted: present means that only the configuration in the fstab file is modified, the mount point is not automatically created, and it is not mounted; absent means that the mount point is deleted and the fstab file is modified; mounted: automatically create a mount point and mount it, add an automatic mount (fstab); unmounted: only unmount, do not delete the mount point, and do not modify the fstab file.
    [[emailprotected]~]# ansible web -m mount -a'name=/warrent src=/dev/cdrom fstype=iso9660 state=mounted'
    #Mount the iso image to the /warrent directory, and set it to automatically mount at boot.
    [[email Protected] ~]# ansible web -m mount -a ‘name=/warrent state=absent‘
    #Unmount the ISO image, delete the mount point, and delete the automatic mount at boot.
    [[email Protected]~]# ansible web -m mount -a "path=/mnt/data src=/dev/sdb1 fstype=xfs ots=wr state=mounted"
    #Note: mount The original name parameter has been replaced by path, but the name parameter can still be used.

    10, cron module:

    The cron module is used to manage scheduled tasks. Common parameters are as follows:

    • name: Specify the description of the scheduled task, required
    • job: The task to be executed
    • user: The user who runs the scheduled task
    • Execution time:
    • minute: 0-59, default is *
    • hour: 0-23, default is *
    • day: 1-31, default is *
    • < li>month: 1-12, the default is *

    • weekday: 1-7, the default is *
    • state=present | absent: present means adding scheduled tasks; absent means deleting plans Task.
    [[email protected] ~]# ansible web -m cron -a'name=test user=root minute=*/2 job="echo test >> / tmp/warrent.txt" state=present'
    #Add a scheduled task to test it
    [[emailprotected] ~]# ansible web -m shell -a "crontab -l" #View the created task Plan
    192.168.1.20 | SUCCESS | rc=0 >>
    #Ansible: test
    */2 * * * * echo test >> /tmp/warrent.txt
    < br />192.168.1.30 | SUCCESS | rc=0 >>
    #Ansible: test
    */2 * * * * echo test >> /tmp/warrent.txt

    11. Script module:

    Function: execute the script of the main control terminal on the remote host, which is equivalent to the combination of scp+shell.

    The usage is as follows:

    [[email Protected] ~]#ansible web -m script -a "/home/test.sh"

    For the use of playbook configuration files, please refer to: https://blog.51cto.com/14227204/2442514

    WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
    SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 206 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

    Leave a Comment

    Your email address will not be published.