This is the 7th day of my participation in the August Text Challenge.More challenges in August

preface

Previous Ansible directory

1, Automated operation and maintenance tools -Ansible guide

2. Use of automated operation and maintenance tools -Ansible Playbook

3. Use of automated o&M tools -Ansible Roles

4. B station learning link

1. Introduction to Ansible

1. What is Ansible?

Ansible is a new automated o&M tool developed based on Python. It integrates the advantages of many o&M tools (Puppet, Chef, func, and Fabric) to implement batch system configuration, batch program deployment, and batch command running.

Simply put, Ansible is an architecture that does not have the capability to deploy in batches. The bulk deployment capability is provided by modules! And you don’t need to install anything on the controlled host, because Ansible communicates with remote hosts over SSH

2. Ansible characteristics

  1. The deployment is simple. You only need to deploy the Ansible environment on the master terminal, and no operation is required on the controlled terminal.
  2. By default, the SSH protocol is used to manage devices.
  3. There are a large number of routine operation and maintenance operation modules, which can achieve most of the daily operations;
  4. Simple configuration, powerful function, strong scalability;
  5. Supports APIS and custom modules that can be easily extended through Python;
  6. Customize powerful configuration and state management through Playbooks;
  7. Lightweight, no need to install agent on the client, update, only need to update once on the operator;

3. Ansible architecture

The main module

  • Ansible: Ansible core program
  • HostInventory: HostInventory, which records information about hosts managed by Ansible, including ports, passwords, and IP addresses.
  • Playbooks: Playbooks, YAML format files, multiple tasks defined in one file, defining which modules the host needs to call to complete functions.
  • CoreModules: CoreModules whose main operation is to complete administrative tasks by calling CoreModules.
  • CustomModules: A custom module that performs functions that core modules cannot. It supports multiple languages.
  • ConnectionPlugins: a connection plug-in for Ansible and Host communication

The working process

  1. Users use ansible programs
  2. Ansible viewing the HostInventory
  3. Ansible knows who to control and starts calling modules, scripts, or roles
  4. Connect to the remote host through the connection module, and the deployment task starts

Command Execution Process

  1. Load your own configuration file, default /etc/ansible/ansible. CFG;
  2. Search the corresponding host configuration file to find the host or group to be executed.
  3. Load its own corresponding module file, such as command;
  4. Generate a temporary PY file (python script) for the module or command using Ansible and transfer the file to a remote server.
  5. The. Ansible/TMP /XXX/ xxx.py file corresponding to the user’s home directory is generated.
  6. Give file +x execute permission;
  7. Execute and return results;
  8. Delete temporary py file, sleep 0 exit;

Ansible configuration

1 installation ansible

See my other link to install ansibleblog.csdn.net/qq_45714272 from yum…

2 Directory Structure

The installation directory is as follows: configuration file directory: /etc/ansible/execution file directory: /usr/bin/lib Library dependency directory: /usr/lib/pythonx.x /site-packages/ ansible-help Directory: /usr/share/doc/ansible-x.x.x/Man Directory: /usr/share/man/man1/

3 Ansible configuration file

The ansible configuration file is /etc/ansible/ansible. CFG. Ansible has many parameters.

inventory = /etc/ansible/hosts		This parameter represents the location of the inventory file of the resource list
library = /usr/share/ansible		# point to the directory where the Ansible module is stored. Multiple directories are supported, separated by a colon (:)
forks = 5		# number of concurrent connections, default is 5
sudo_user = root		Set the default user to execute the command
remote_port = 22		The default port number is 22. You are advised to change it to ensure security
host_key_checking = False		# set whether to check SSH host keys. The value is True/False. The configuration instance is not prompted for the first connection after the shutdown
timeout = 60		# set SSH connection timeout in seconds
log_path = /var/log/ansible.log		# specify a file to store ansible logs.
Copy the code

4 Ansible host list

There are several ways to define it:

1, directly specify the host address or host name:192.168.100.10

2Define a group name, add the host, of course can also use wildcard to match! [test]
192.168.100.1:3]0. . ."/etc/ansible/hosts" 57L, 1169C                                                    1.1 
Copy the code

5 color ansible

Ansible execution results are displayed in green (successful execution), yellow (success with state change) and red (failed execution) colors. The colors are associated with the changed state and can be customized in ansible. CFG.

3. Common Ansible commands

1 Ansible command set

/usr/bin/ansibleansibe ad-hoc temporary command execution tool, This command is used to execute temporary commands. /usr/bin/ansible-doc Ansible module help document /usr/bin/ansible-galaxy Download/upload excellent code or the official website of the Roles module /usr/bin/ansible-playbookAnsible-task set orcheographer /usr/bin/ansible-pullansible a tool for remote command execution that pulls configurations instead of pushing configurations. High architecture requirements for O&M) /usr/bin/ansible-vaultansible file encryption tool /usr/bin/ansible-consoleAnsible Command execution tool that allows users to interact with each other on the Linux Consoble interface

/usr/bin/ansible and /usr/bin/ansible-playbook are commonly used.

2 ansible – doc command

[root@ansible ~]# ansible-doc
Usage: ansible-doc [options] [module...]

Options:
  -h, --help            show this-l, --list list available modules# list available modules -m MODULE_PATH, --module-path=MODULE_PATH# Specifies the module pathspecify path(s) to module library (default=None)
  -s, --snippet         Show playbook snippet for specified module(s)# display playbook spec module usage -v, --verbose verbosemode (-vvv forMore, -vvvv to enable# Display ansible-doc version number
  --version             show program's version number and exit
Copy the code

Such as:

[root@ansible ansible]# ansible-doc -l |grep nginx
nginx_status_info                                             Retrieve information on nginx stat...
nginx_status_facts                                            Retrieve nginx status facts  

[root@ansible ansible]# ansible-doc -s nginx_status_info
- name: Retrieve information on nginx status.
  nginx_status_info:
      timeout:               # HTTP connection timeout in seconds.
      url:                   # (required) URL of the nginx status.

Copy the code

3 Ansible command format

The command format is as follows: ansible host-pattern -m module name -a ‘parameter’

View information using ansible-h

[root@ansible-k, --ask-pass #ask ansible]# ansible -h -a module parameter, if the default COMMAND module, that is COMMAND parameters, such as "date", "PWD", etcforSSH password. Login password, prompting for SSH password instead of assuming key based authentication --ask-su-pass #askforSu password. Su switch password -k, --ask-sudo-pass #askforSudo password. Prompt password to use sudo, sudo indicates the lift operation --ask-vault-pass #askforVault password. -b SECONDS # background run timeout -c # simulates the run environment and preruns, which can be checked for errors -c CONNECTION # CONNECTION type -f FORKS # number of parallel tasks. Default5--list-hosts # check which host groups are available -m MODULE_NAME # Execute the name of the module, default command module, So if you are executing a single command, you can omit the -m parameter -o # to compress the output and try to print all the results in one line. Generally, for the collection tool, you can use -s # to su the command -r SU_USER # to specify the user to su. -u SUDO_USER # specifies the user to which sudo is assigned. The default value is root. -t TIMEOUT # Specifies the SSH TIMEOUT duration. You can also modify the configuration file to -u REMOTE_USER # remote user, root user by default -v # For details. -VVv, -VVvv for more details is also supportedCopy the code

4 SSH Password-free login

The principle of

The experiment

#1.Generate private key [root]@ansible ~]# ssh-keygen 
#2.Distribute the private key to the host [root]@ansible ~]# ssh-copy-id root@192.168100.10.
[root@ansible ~]# ssh-copy-id root@192.168100.20.
Copy the code

4, Ansible common modules

1 ping module


[root@ansible ~]# ansible 192.168100.10. -m ping 
192.168100.10. | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false."ping": "pong"
}
Copy the code

This means that our host is connected. The following operations can proceed normally.

2 the shell module

Shell modules are commonly used to run commands by calling the shell interpreter on a remote host

[root@ansible ~]# head -10 /etc/ansible/hosts 
[test]
192.168100..1:3]0

[wsr]
192.168100.10. http_port=81
192.168100.20. http_port=82

[wsr:vars]
nodename=mail
domainname=edu
[root@ansible ~]# ansible wsr -m shell -a 'ls -l'
192.168100.10. | CHANGED | rc=0 >>
total 188
drwxr-xr-x. 2 root root      6 Aug 11  2020 a
-rw-------. 1 root root   1260 Jun  3  2020 anaconda-ks.cfg
-rw-r--r--. 1 root root      0 Aug 11  2020 b
-rw-r--r--  1 root root     13 Jun 21 04:09 f4
-rw-r--r--  1 root root   6540 Jun 21 04:22 log.tar.xz
lrwxrwxrwx. 1 root root     17 Jun 20 22:30selinux -> .. /selinux/config drwxr-xr-x.2 root root     25 Jun 20 22:08 sh
-rw-r--r--  1 root root 175412 Jun 22 03:53 vsftpd-3.02.-25.el7.x86_64.rpm
192.168100.20. | CHANGED | rc=0 >>
total 188
drwxr-xr-x. 2 root root      6 Aug 11  2020 a
-rw-------. 1 root root   1260 Jun  3  2020 anaconda-ks.cfg
-rw-r--r--. 1 root root      0 Aug 11  2020 b
-rw-r--r--  1 root root     13 Jun 21 04:09 f4
-rw-r--r--  1 root root   6516 Jun 21 04:22 log.tar.xz
-rw-r--r--  1 root root 175412 Jun 22 03:53 vsftpd-3.02.-25.<font color=#999AAA >Copy the code

3 the command module

This module can execute commands directly on a remote host and return the results to the local host.

The command module accepts the command name, followed by a whitespace delimited list of arguments. The given command will be executed on all selected nodes. It won’t through the shell processing, such as $HOME and operations such as “<” and “>”, “|”, “;” , “&” work (requires the (shell) module to implement these functions).

 

Let’s take a look at some common commands in this module:

  • Chdir # switch to the directory executable # switch shell to execute the command using the absolute path of the command before executing the command
  • Free_form # The Linux command to execute, usually using Ansible’s -a parameter instead.
  • Creates # creates # a file name. If it exists, this command will not execute

To make a judgment

  • If the post does not exist, the command will not be processed
[root@ansible ~]# ansible wsr -m command -a 'chdir=/data ls'
192.168100.20. | CHANGED | rc=0 >>
file1
file2
file3
for1.conf
for2.conf
for3.conf
httpd.conf
192.168100.10. | CHANGED | rc=0 >>
file1
file2
file3
for1.conf
for2.conf
for3.conf
httpd.conf
Copy the code

4 copy module

This module is used to copy files to remote hosts, while supporting file generation and modification permissions for a given content, etc. The options are as follows:

  • Src# is copied to a local file on the remote host. It can be an absolute path or a relative path. If the path is a directory, it is copied recursively, similar to “rsync”
  • Content# replaces “SRC” and can directly specify the value of the file
  • Dest# Specifies the absolute path to the remote host to which the source file will be copied
  • Backup# When the contents of the file are changed, the source file is backed up before overwriting. The backup file contains time information
  • Directory_mode # Recursively sets directory permissions, default to system default
  • Force# If the target host contains the file but the content is different, set this parameter to yes. If this parameter is set to no, the file is replicated only when the target location of the target host does not exist. The default value is “yes”
  • Others# all options in the file module can be used here

SRC, dest, backup, and mode are commonly used

copy

[root@ansible ~]# touch 2021710
[root@ansible ~]# ansible wsr -m copy -a 'src=2021710 dest=/data/2021710'
192.168100.10. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709"."dest": "/data/2021710"."gid": 0."group": "root"."md5sum": "d41d8cd98f00b204e9800998ecf8427e"."mode": "0644"."owner": "root"."size": 0."src": "/ root /. Ansible/TMP/ansible - 038951 / TMP - 1625931089.28-8051-80193366 source"."state": "file"."uid": 0
}
192.168100.20. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709"."dest": "/data/2021710"."gid": 0."group": "root"."md5sum": "d41d8cd98f00b204e9800998ecf8427e"."mode": "0644"."owner": "root"."size": 0."src": "/ root /. Ansible/TMP/ansible - 716175 / TMP - 1625931089.28-8052-82580429 source"."state": "file"."uid": 0
}
Copy the code

Permissions and backups

[root@ansible ~]# ansible wsr -m copy -a 'content="i am bad boy\n" backup=yes dest=/data/2021710 mode=666'
192.168100.10. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/ data / 2021710.11493.2021-07-10 @ 11:32:39 ~"."changed": true."checksum": "444281122cde3d31fa394ffe2d29d9a1fa2411f3"."dest": "/data/2021710"."gid": 0."group": "root"."md5sum": "e2ea0ae0489f588fd0e7adcdc361ff70"."mode": "0666"."owner": "root"."size": 13."src": "/ root /. Ansible/TMP/ansible - 502466 / TMP - 1625931158.27-8105-89064400 source"."state": "file"."uid": 0
}
192.168100.20. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/ data / 2021710.11427.2021-07-10 @ 11:32:39 ~"."changed": true."checksum": "444281122cde3d31fa394ffe2d29d9a1fa2411f3"."dest": "/data/2021710"."gid": 0."group": "root"."md5sum": "e2ea0ae0489f588fd0e7adcdc361ff70"."mode": "0666"."owner": "root"."size": 13."src": "/ root /. Ansible/TMP/ansible - 5505942 / TMP - 1625931158.28-8106-20136363 source"."state": "file"."uid": 0
}

Copy the code

detection

A large list of names is the name of the backup, and you can also see that the permission is 666

[root@ansible ~]# ansible wsr -m shell -a 'ls -l /data'
192.168100.10. | CHANGED | rc=0 >>
total 32
-rw-rw-rw- 1 root   root    13 Jul 10 11:32 2021710
-rw-r--r-- 1 root   root     0 Jul 10 11:31 2021710.114932021.-07-10@11:32:39~
-rw-rw-rw- 1 root   root    21 Jul 10 11:20 a.sh
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file1
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file2
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file3
-rw-r--r-- 1 root   root    63 Jul  4 11:51 for1.conf
-rw-r--r-- 1 root   root   267 Jul  4 12:06 for2.conf
-rw-r--r-- 1 root   root   171 Jul  5 04:05 for3.conf
-rw-r--r-- 1 apache root 11753 Jul 10 03:21 httpd.conf
192.168100.20. | CHANGED | rc=0 >>
total 32
-rw-rw-rw- 1 root   root    13 Jul 10 11:32 2021710
-rw-r--r-- 1 root   root     0 Jul 10 11:31 2021710.114272021.-07-10@11:32:39~
-rw-rw-rw- 1 root   root    21 Jul 10 11:20 a.sh
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file1
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file2
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file3
-rw-r--r-- 1 root   root    63 Jul  4 11:51 for1.conf
-rw-r--r-- 1 root   root   267 Jul  4 12:06 for2.conf
-rw-r--r-- 1 root   root   171 Jul  5 04:05 for3.conf
-rw-r--r-- 1 apache root 11753 Jul 10 03:21 httpd.conf
Copy the code

5 yum modules

The options are as follows:

  • Name =# The name of the package installed
  • State =#present– > Install, latest– > Install, latest– > Uninstall software.
  • The rest that are not commonly used will not be listed

The installation

State The default value is present

[root@ansible ~]# ansible wsr -m yum -a 'name=vim'
192.168100.20. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."changes": {
        "installed": [
            "vim"]},"msg": "Repository base is listed more than once in the configuration\nRepository updates is listed more than once in the configuration\nRepository extras is listed more than once in the configuration\nRepository centosplus is listed more than once in the configuration\nRepository epel is listed more than once in the configuration\nRepository epel-debuginfo  is listed more than once in the configuration\nRepository epel-source is listed more than once in the configuration\n"."rc": 0."results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package vim-enhanced. X86_64 2:7.4.629-8.el7_9 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n Vim-enhanced X86_64 2:7.4.629-8.el7_9 updates 1.1m \n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal Download Size: 1.1m \nInstalled size: 2.2m \nDownloading Packages :\nRunning Transaction Check \nRunning Transaction test\nTransaction test Succeeded \nRunning Transaction \n Installing: 2: VIM-enhanced 7.4.629-8.el7_9.x86_64 1/1 \n Verifying: 2: VIm-enhanced 7.4.629-8.el7_9.x86_64 1/1 \n\nInstalled:\n vim-enhanced. X86_64 2:7.4.629-8.el7_9 \n\nComplete! \n"]}192.168100.10. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."changes": {
        "installed": [
            "vim"]},"msg": "Repository base is listed more than once in the configuration\nRepository updates is listed more than once in the configuration\nRepository extras is listed more than once in the configuration\nRepository centosplus is listed more than once in the configuration\nRepository epel is listed more than once in the configuration\nRepository epel-debuginfo  is listed more than once in the configuration\nRepository epel-source is listed more than once in the configuration\n"."rc": 0."results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package vim-enhanced. X86_64 2:7.4.629-8.el7_9 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n Vim-enhanced X86_64 2:7.4.629-8.el7_9 updates 1.1m \n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal Download Size: 1.1m \nInstalled size: 2.2m \nDownloading Packages :\nRunning Transaction Check \nRunning Transaction test\nTransaction test Succeeded \nRunning Transaction \n Installing: 2: VIM-enhanced 7.4.629-8.el7_9.x86_64 1/1 \n Verifying: 2: VIm-enhanced 7.4.629-8.el7_9.x86_64 1/1 \n\nInstalled:\n vim-enhanced. X86_64 2:7.4.629-8.el7_9 \n\nComplete! \n"]}Copy the code

uninstall

Change the state to Absent

/ root @ ansible ~ # ansible yum the WSR - m - a 'name = vim state = absent' 192.168.100.20 | CHANGED = > {" ansible_facts ": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "changes": { "removed": [ "vim" ] }, "msg": "Repository base is listed more than once in the configuration\nRepository updates is listed more than once in the configuration\nRepository extras is listed more than once in the configuration\nRepository centosplus is listed more than once in the configuration\nRepository epel is listed more than once in the configuration\nRepository epel-debuginfo  is listed more than once in the configuration\nRepository epel-source is listed more than once in the configuration\n",  "rc": 0, "results": [ "Loaded plugins: Fastestmirror \ nconsiderations Dependencies\n--> Running Transaction Check \n--> Package vim-enhanced. X86_64 2:7.4.629-8.el7_9  will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nRemoving:\n Vim-enhanced X86_64 2:7.4.629-8.el7_9@ updates 2.2m \n\nTransaction Summary\n================================================================================\nRemove 1 Package\n\nInstalled  size: 2.2m \nDownloading Packages :\nRunning Transaction Check \nRunning Transaction test\nTransaction test Succeeded \nRunning Transaction \n Erasing: 2: VIm-enhanced 7.4.629-8.el7_9.x86_64 1/1 \n Verifying: 1 :vim-enhanced 7.4.629-8.el7_9.x86_64 1/1 \n\nRemoved:\n vim-enhanced.x86_64 2:7.4.629-8.el7_9 \n\nComplete!\n"]} 192.168.100.10 | CHANGED = > {" ansible_facts ": {" discovered_interpreter_python" : "/ usr/bin/python"}, "CHANGED" : true, "changes": { "removed": [ "vim" ] }, "msg": "Repository base is listed more than once in the configuration\nRepository updates is listed more than once in the configuration\nRepository extras is listed more than once in the configuration\nRepository centosplus is listed more than once in the configuration\nRepository epel is listed more than once in the configuration\nRepository epel-debuginfo  is listed more than once in the configuration\nRepository epel-source is listed more than once in the configuration\n",  "rc": 0, "results": [ "Loaded plugins: Fastestmirror \ nconsiderations Dependencies\n--> Running Transaction Check \n--> Package vim-enhanced. X86_64 2:7.4.629-8.el7_9  will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nRemoving:\n Vim-enhanced X86_64 2:7.4.629-8.el7_9@ updates 2.2m \n\nTransaction Summary\n================================================================================\nRemove 1 Package\n\nInstalled  size: 2.2m \nDownloading Packages :\nRunning Transaction Check \nRunning Transaction test\nTransaction test Succeeded \nRunning Transaction \n Erasing: 2: VIm-enhanced 7.4.629-8.el7_9.x86_64 1/1 \n Verifying: 1 :vim-enhanced 7.4.629-8.el7_9.x86_64 1/1 \n\nRemoved:\n vim-enhanced.x86_64 2:7.4.629-8.el7_9 \n\nComplete!\n"]}Copy the code

6 the file module

This module is mainly used to set the properties of files, such as creating files, creating link files, deleting files and so on. Here are some common commands:

Force# needs to force soft links to be created in two cases, one is when the source file does not exist but will be created later; Is another target soft links exist, need to cancel before soft chain first, and then create a new soft chain, there are two options: yes | no group# definition file/directory belong to the group. Owner# define the owner of a file/directory. Path: define file/directory path recurse# set file attributes recursively, directory only, SRC: Directory: if the directory does not exist, create a directory file: if the directory does not exist, create a directory file: Link: a soft link is created. Hard: a hard link is created. Touch: A new file is created if the file does not existCopy the code

Creating a folder

[root@ansible ~]# ansible wsr -m file -a 'path=/data/2339 state=directory'
192.168.100.20 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0."group": "root"."mode": "0755"."owner": "root"."path": "/data/2339"."size": 6."state": "directory"."uid": 0
}
192.168.100.10 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0."group": "root"."mode": "0755"."owner": "root"."path": "/data/2339"."size": 6."state": "directory"."uid": 0
}
Copy the code

Creating a link file

[root@ansible ~]# ansible wsr -m file -a 'path=/data/2340 src=2339 state=link'
192.168100.10. | CHANGED= > {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."dest": "/data/2340"."gid": 0."group": "root"."mode": "0777"."owner": "root"."size": 4."src": "2339"."state": "link"."uid": 0
}
192.168100.20. | CHANGED= > {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."dest": "/data/2340"."gid": 0."group": "root"."mode": "0777"."owner": "root"."size": 4."src": "2339"."state": "link"."uid": 0} test [root@ansible ~]# ansible WSR -a'ls -l /data'
192.168100.20. | CHANGED | rc=0 >>
total 32
-rw-rw-rw- 1 root   root    13 Jul 10 11:32 2021710
-rw-r--r-- 1 root   root     0 Jul 10 11:31 2021710.114272021.-07-10@11:32:39~
drwxr-xr-x 2 root   root     6 Jul 10 11:40 2339
lrwxrwxrwx 1 root   root     4 Jul 10 11:42 2340 -> 2339
-rw-rw-rw- 1 root   root    21 Jul 10 11:20 a.sh
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file1
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file2
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file3
-rw-r--r-- 1 root   root    63 Jul  4 11:51 for1.conf
-rw-r--r-- 1 root   root   267 Jul  4 12:06 for2.conf
-rw-r--r-- 1 root   root   171 Jul  5 04:05 for3.conf
-rw-r--r-- 1 apache root 11753 Jul 10 03:21 httpd.conf
192.168100.10. | CHANGED | rc=0 >>
total 32
-rw-rw-rw- 1 root   root    13 Jul 10 11:32 2021710
-rw-r--r-- 1 root   root     0 Jul 10 11:31 2021710.114932021.-07-10@11:32:39~
drwxr-xr-x 2 root   root     6 Jul 10 11:40 2339
lrwxrwxrwx 1 root   root     4 Jul 10 11:42 2340 -> 2339
-rw-rw-rw- 1 root   root    21 Jul 10 11:20 a.sh
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file1
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file2
-rw-r--r-- 1 root   root     0 Jul  3 23:14 file3
-rw-r--r-- 1 root   root    63 Jul  4 11:51 for1.conf
-rw-r--r-- 1 root   root   267 Jul  4 12:06 for2.conf
-rw-r--r-- 1 root   root   171 Jul  5 04:05 for3.conf
-rw-r--r-- 1 apache root 11753 Jul 10 03:21 httpd.conf
Copy the code

Delete the file

[root@ansible ~]# ansible WSR -m file -a ‘path=/data/2339 state=absent’

7 the cron module

This module is suitable for managing CRON scheduled tasks. It uses the same syntax as in our crontab file

  • Day = # Work that should run on day (1-31, *, */2,)
  • Hour = # hour (0-23, *, */2,)
  • Minute = # (0-59, *, */2,)
  • Month = # month (1-12, *, /2,)
  • Weekday = # weekday (0-6 for Sunday-saturday,,)
  • What command does job= # indicate to run
  • Name = # Description of a scheduled task
  • Reboot # The task is run on reboot. This is not recommended. Instead, use special_time
  • Hourly parameters: reboot, annually, monthly, weekly, daily, hourly
  • Present indicates that the scheduled task is added, which is also the default setting. Absent indicates that the scheduled task is deleted
  • User # Which user to execute as
[root@ansible ~]# ansible wsr -m cron -a 'name="echo words" minute=*/5 job="echo hello world"'
192.168100.10. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."envs": []."jobs": [
        "warningcron"."None"."echo words"]}192.168100.20. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."envs": []."jobs": [
        "warningcron"."None"."echo words"]} Test results [root@ansible ~]# ansible wsr -a 'crontab -l'
192.168100.10. | CHANGED | rc=0 >>
#Ansible: warningcron
#* * * * 1.3.5 /usr/bin/wall FBI warning
#Ansible: None
#* * * * * /usr/bin/wall FBI warning
#Ansible: echo words
*/5 * * * * echo hello world
192.168100.20. | CHANGED | rc=0 >>
#Ansible: warningcron
#* * * * 1.3.5 /usr/bin/wall FBI warning
#Ansible: None
#* * * * * /usr/bin/wall FBI warning
#Ansible: echo words
*/5 * * * * echo hello world
Copy the code

Mission Completely!!

8 the user module

This module is mainly used to manage accounts

  • Comment# Description of the user
  • Createhome# whether to create a home directory
  • Force# behaves the same as userdel — force when state=absent is used.
  • Group# Specifies the base group
  • Groups# specifies additional groups. If (groups=) is specified, all groups are removed
  • Home# specifies the user’s home directory
  • Move_home # If set to home=, attempts to move the user home directory to the specified directory
  • Name# Specifies the user name
  • Non_unique # This option allows changing non-unique user ID values
  • Password# Specifies the user password
  • Remove # Behaves the same as userdel — remove when state=absent is used
  • Shell# specifies the default shell
  • State# sets the account status. Absent indicates that the account is deleted
  • System# When creating a user, set the user to be a system user. This setting does not change existing users
  • Id # Specifies the uid of the user

Add a user and specify a UID

[root@ansible ~]# ansible wsr -m user -a 'name=zs uid=66666'
192.168100.10. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."comment": ""."create_home": true."group": 1005."home": "/home/zs"."name": "zs"."shell": "/bin/bash"."state": "present"."system": false."uid": 66666
}
192.168100.20. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."comment": ""."create_home": true."group": 1005."home": "/home/zs"."name": "zs"."shell": "/bin/bash"."state": "present"."system": false."uid": 66666
}
Copy the code
[root@ansible ~]# ansible wsr -m shell -a 'getent passwd|grep zs'
192.168100.10. | CHANGED | rc=0 >>
zs:x:66666:1005::/home/zs:/bin/bash
192.168100.20. | CHANGED | rc=0 >>
zs:x:66666:1005::/home/zs:/bin/bash
Copy the code

Delete user

Specify the status to absent

[root@ansible ~]# ansible wsr -m user -a 'name=zs uid=66666 state=absent'
192.168100.10. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."force": false."name": "zs"."remove": false."state": "absent"
}
192.168100.20. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."force": false."name": "zs"."remove": false."state": "absent"
}
Copy the code
[root@ansible ~]# ansible wsr -m shell -a 'getent passwd|grep zs'
192.168100.10. | FAILED | rc=1 >>
non-zero return code
192.168100.20. | FAILED | rc=1 >>
non-zero return code
Copy the code

9 group module

This module is used to add or remove groups. Common options are as follows:

  • Gid =# Sets the GROUP GID number
  • Name =# Specifies the name of the group
  • State =# Specifies the status of the group. By default, the group is created
  • System =# Set the value to yes, indicating that the system group is created

Create a group and specify a GID

[root@ansible ~]# ansible wsr -m group -a 'name=ls gid=888888'
192.168100.20. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."gid": 888888."name": "ls"."state": "present"."system": false
}
192.168100.10. | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."gid": 888888."name": "ls"."state": "present"."system": false
}
Copy the code
[root@ansible ~]# ansible wsr -m shell -a 'cat /etc/group |grep 888888'
192.168100.10. | CHANGED | rc=0 >>
ls:x:888888:
192.168100.20. | CHANGED | rc=0 >>
ls:x:888888:
Copy the code

Delete the group

Specify state to ABSENT to delete the file

[root@ansible ~]# ansible wsr -m group -a 'name=ls state=absent'
192.168100.20. | CHANGED= > {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."name": "ls"."state": "absent"
}
192.168100.10. | CHANGED= > {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."name": "ls"."state": "absent"
}
Copy the code

10 script module

This module is used to run local scripts on the managed machine.

[root@ansible tmp]# cat df.sh 
#!/bin/bash

	date >> /tmp/disk_total.log
	df -lh >> /tmp/disk_total.log 

Copy the code
[root@ansible tmp]# ansible wsr -m script -a '/tmp/df.sh'
192.168100.10. | CHANGED= > {
    "changed": true."rc": 0."stderr": "Shared connection to 192.168.100.10 closed.\r\n"."stderr_lines": [
        "Shared connection to 192.168.100.10 closed"]."stdout": ""."stdout_lines": []}192.168100.20. | CHANGED= > {
    "changed": true."rc": 0."stderr": "Shared connection to 192.168.100.20 closed.\r\n"."stderr_lines": [
        "Shared connection to 192.168.100.20 closed"]."stdout": ""."stdout_lines": []}Copy the code

test

[root@ansible tmp]# ansible wsr -a 'cat /tmp/disk_total.log'
192.168100.10. | CHANGED | rc=0 >>
Sat Jul 10 21:24:51 EDT 2021
Filesystem               Size  Used Avail Use% Mounted on
devtmpfs                 475M     0  475M   0% /dev
tmpfs                    487M     0  487M   0% /dev/shm
tmpfs                    487M  7.6M  479M   2% /run
tmpfs                    487M     0  487M   0% /sys/fs/cgroup
/dev/mapper/centos-root  8.0G  1.5G  6.6G  18% /
/dev/sr0                 4.4G  4.4G     0 100% /mnt/centos
/dev/sda1               1014M  136M  879M  14% /boot
tmpfs                     98M     0   98M   0% /run/user/0
192.168100.20. | CHANGED | rc=0 >>
Sat Jul 10 21:24:51 EDT 2021
Filesystem               Size  Used Avail Use% Mounted on
devtmpfs                 475M     0  475M   0% /dev
tmpfs                    487M     0  487M   0% /dev/shm
tmpfs                    487M  7.6M  479M   2% /run
tmpfs                    487M     0  487M   0% /sys/fs/cgroup
/dev/mapper/centos-root  8.0G  1.5G  6.6G  18% /
/dev/sr0                 4.4G  4.4G     0 100% /mnt/centos
/dev/sda1               1014M  136M  879M  14% /boot
tmpfs                     98M     0   98M   0% /run/user/0
Copy the code

11 the setup module

Collect host information such as number of Vcpus, size of memory, etc….. by calling the FACTS component (facts are variables, built-in variables)

You can use filter to view the specified information and return a lot of corresponding host information. In the following operations, you can perform different operations according to different information. For example, Redhat series use YUM to install software and Debian series use APT to install software.

[root@ansible tmp]# ansible wsr -m setup -a 'filter=*cpu*'
192.168100.20. | SUCCESS= > {
    "ansible_facts": {
        "ansible_processor_vcpus": 2."discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
192.168100.10. | SUCCESS= > {
    "ansible_facts": {
        "ansible_processor_vcpus": 2."discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
Copy the code

12 service module

This module is used to manage the service program. The main options are as follows:

  • Arguments # The command line provides additional arguments
  • Enabled # Set boot on the machine.
  • Name = # Service name
  • Runlevel # Specifies the boot level.
  • Sleep # Whether to wait while restarting the service. For example, after the service is shut down, wait 2 seconds to start again. (Defined in the script.)
  • When the service started, the service stopped. When the service started, the service stopped.
  • Running –> restarting services, reloaded– > overloaded configurations
[root@ansible tmp]# ansible wsr -m service -a 'name=httpd state=restarted enabled=true'
192.168100.20. | CHANGED= > {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."enabled": true."name": "httpd"."state": "started"."status": {
        "ActiveEnterTimestampMonotonic": "0"."ActiveExitTimestampMonotonic": "0"."ActiveState": "inactive"."After": "basic.target remote-fs.target system.slice systemd-journald.socket network.target tmp.mount nss-lookup.target -.mount"."AllowIsolate": "no"."AmbientCapabilities": "0"."AssertResult": "no"."AssertTimestampMonotonic": "0"."Before": "shutdown.target"."BlockIOAccounting": "no"."BlockIOWeight": "18446744073709551615"."CPUAccounting": "no"."CPUQuotaPerSecUSec": "infinity"."CPUSchedulingPolicy": "0"."CPUSchedulingPriority": "0"."CPUSchedulingResetOnFork": "no"."CPUShares": "18446744073709551615"."CanIsolate": "no"."CanReload": "yes"."CanStart": "yes"."CanStop": "yes"."CapabilityBoundingSet": "18446744073709551615"."ConditionResult": "no"."ConditionTimestampMonotonic": "0"."Conflicts": "shutdown.target"."ControlPID": "0"."DefaultDependencies": "yes"."Delegate": "no"."Description": "The Apache HTTP Server"."DevicePolicy": "auto"."Documentation": "man:httpd(8) man:apachectl(8)"."EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)"."ExecMainCode": "0"."ExecMainExitTimestampMonotonic": "0"."ExecMainPID": "0"."ExecMainStartTimestampMonotonic": "0"."ExecMainStatus": "0"."ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }"."ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }"."ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }"."FailureAction": "none"."FileDescriptorStoreMax": "0"."FragmentPath": "/usr/lib/systemd/system/httpd.service"."GuessMainPID": "yes"."IOScheduling": "0"."Id": "httpd.service"."IgnoreOnIsolate": "no"."IgnoreOnSnapshot": "no"."IgnoreSIGPIPE": "yes"."InactiveEnterTimestampMonotonic": "0"."InactiveExitTimestampMonotonic": "0"."JobTimeoutAction": "none"."JobTimeoutUSec": "0"."KillMode": "control-group"."KillSignal": "18"."LimitAS": "18446744073709551615"."LimitCORE": "18446744073709551615"."LimitCPU": "18446744073709551615"."LimitDATA": "18446744073709551615"."LimitFSIZE": "18446744073709551615"."LimitLOCKS": "18446744073709551615"."LimitMEMLOCK": "65536"."LimitMSGQUEUE": "819200"."LimitNICE": "0"."LimitNOFILE": "4096"."LimitNPROC": "3795"."LimitRSS": "18446744073709551615"."LimitRTPRIO": "0"."LimitRTTIME": "18446744073709551615"."LimitSIGPENDING": "3795"."LimitSTACK": "18446744073709551615"."LoadState": "loaded"."MainPID": "0"."MemoryAccounting": "no"."MemoryCurrent": "18446744073709551615"."MemoryLimit": "18446744073709551615"."MountFlags": "0"."Names": "httpd.service"."NeedDaemonReload": "no"."Nice": "0"."NoNewPrivileges": "no"."NonBlocking": "no"."NotifyAccess": "main"."OOMScoreAdjust": "0"."OnFailureJobMode": "replace"."PermissionsStartOnly": "no"."PrivateDevices": "no"."PrivateNetwork": "no"."PrivateTmp": "yes"."ProtectHome": "no"."ProtectSystem": "no"."RefuseManualStart": "no"."RefuseManualStop": "no"."RemainAfterExit": "no"."Requires": "-.mount basic.target"."RequiresMountsFor": "/var/tmp"."Restart": "no"."RestartUSec": "100ms"."Result": "success"."RootDirectoryStartOnly": "no"."RuntimeDirectoryMode": "0755"."SameProcessGroup": "no"."SecureBits": "0"."SendSIGHUP": "no"."SendSIGKILL": "yes"."Slice": "system.slice"."StandardError": "inherit"."StandardInput": "null"."StandardOutput": "journal"."StartLimitAction": "none"."StartLimitBurst": "5"."StartLimitInterval": "10000000"."StartupBlockIOWeight": "18446744073709551615"."StartupCPUShares": "18446744073709551615"."StatusErrno": "0"."StopWhenUnneeded": "no"."SubState": "dead"."SyslogLevelPrefix": "yes"."SyslogPriority": "30"."SystemCallErrorNumber": "0"."TTYReset": "no"."TTYVHangup": "no"."TTYVTDisallocate": "no"."TasksAccounting": "no"."TasksCurrent": "18446744073709551615"."TasksMax": "18446744073709551615"."TimeoutStartUSec": "1min 30s"."TimeoutStopUSec": "1min 30s"."TimerSlackNSec": "50000"."Transient": "no"."Type": "notify"."UMask": "0022"."UnitFilePreset": "disabled"."UnitFileState": "disabled"."Wants": "system.slice"."WatchdogTimestampMonotonic": "0"."WatchdogUSec": "0"}}192.168100.10. | CHANGED= > {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true."enabled": true."name": "httpd"."state": "started"."status": {
        "ActiveEnterTimestampMonotonic": "0"."ActiveExitTimestampMonotonic": "0"."ActiveState": "inactive"."After": "remote-fs.target nss-lookup.target tmp.mount basic.target -.mount systemd-journald.socket system.slice network.target"."AllowIsolate": "no"."AmbientCapabilities": "0"."AssertResult": "no"."AssertTimestampMonotonic": "0"."Before": "shutdown.target"."BlockIOAccounting": "no"."BlockIOWeight": "18446744073709551615"."CPUAccounting": "no"."CPUQuotaPerSecUSec": "infinity"."CPUSchedulingPolicy": "0"."CPUSchedulingPriority": "0"."CPUSchedulingResetOnFork": "no"."CPUShares": "18446744073709551615"."CanIsolate": "no"."CanReload": "yes"."CanStart": "yes"."CanStop": "yes"."CapabilityBoundingSet": "18446744073709551615"."ConditionResult": "no"."ConditionTimestampMonotonic": "0"."Conflicts": "shutdown.target"."ControlPID": "0"."DefaultDependencies": "yes"."Delegate": "no"."Description": "The Apache HTTP Server"."DevicePolicy": "auto"."Documentation": "man:httpd(8) man:apachectl(8)"."EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)"."ExecMainCode": "0"."ExecMainExitTimestampMonotonic": "0"."ExecMainPID": "0"."ExecMainStartTimestampMonotonic": "0"."ExecMainStatus": "0"."ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }"."ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }"."ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }"."FailureAction": "none"."FileDescriptorStoreMax": "0"."FragmentPath": "/usr/lib/systemd/system/httpd.service"."GuessMainPID": "yes"."IOScheduling": "0"."Id": "httpd.service"."IgnoreOnIsolate": "no"."IgnoreOnSnapshot": "no"."IgnoreSIGPIPE": "yes"."InactiveEnterTimestampMonotonic": "0"."InactiveExitTimestampMonotonic": "0"."JobTimeoutAction": "none"."JobTimeoutUSec": "0"."KillMode": "control-group"."KillSignal": "18"."LimitAS": "18446744073709551615"."LimitCORE": "18446744073709551615"."LimitCPU": "18446744073709551615"."LimitDATA": "18446744073709551615"."LimitFSIZE": "18446744073709551615"."LimitLOCKS": "18446744073709551615"."LimitMEMLOCK": "65536"."LimitMSGQUEUE": "819200"."LimitNICE": "0"."LimitNOFILE": "4096"."LimitNPROC": "3795"."LimitRSS": "18446744073709551615"."LimitRTPRIO": "0"."LimitRTTIME": "18446744073709551615"."LimitSIGPENDING": "3795"."LimitSTACK": "18446744073709551615"."LoadState": "loaded"."MainPID": "0"."MemoryAccounting": "no"."MemoryCurrent": "18446744073709551615"."MemoryLimit": "18446744073709551615"."MountFlags": "0"."Names": "httpd.service"."NeedDaemonReload": "no"."Nice": "0"."NoNewPrivileges": "no"."NonBlocking": "no"."NotifyAccess": "main"."OOMScoreAdjust": "0"."OnFailureJobMode": "replace"."PermissionsStartOnly": "no"."PrivateDevices": "no"."PrivateNetwork": "no"."PrivateTmp": "yes"."ProtectHome": "no"."ProtectSystem": "no"."RefuseManualStart": "no"."RefuseManualStop": "no"."RemainAfterExit": "no"."Requires": "basic.target -.mount"."RequiresMountsFor": "/var/tmp"."Restart": "no"."RestartUSec": "100ms"."Result": "success"."RootDirectoryStartOnly": "no"."RuntimeDirectoryMode": "0755"."SameProcessGroup": "no"."SecureBits": "0"."SendSIGHUP": "no"."SendSIGKILL": "yes"."Slice": "system.slice"."StandardError": "inherit"."StandardInput": "null"."StandardOutput": "journal"."StartLimitAction": "none"."StartLimitBurst": "5"."StartLimitInterval": "10000000"."StartupBlockIOWeight": "18446744073709551615"."StartupCPUShares": "18446744073709551615"."StatusErrno": "0"."StopWhenUnneeded": "no"."SubState": "dead"."SyslogLevelPrefix": "yes"."SyslogPriority": "30"."SystemCallErrorNumber": "0"."TTYReset": "no"."TTYVHangup": "no"."TTYVTDisallocate": "no"."TasksAccounting": "no"."TasksCurrent": "18446744073709551615"."TasksMax": "18446744073709551615"."TimeoutStartUSec": "1min 30s"."TimeoutStopUSec": "1min 30s"."TimerSlackNSec": "50000"."Transient": "no"."Type": "notify"."UMask": "0022"."UnitFilePreset": "disabled"."UnitFileState": "disabled"."Wants": "system.slice"."WatchdogTimestampMonotonic": "0"."WatchdogUSec": "0"}}Copy the code

reference

My.oschina.net/u/3413282/b… www.cnblogs.com/keerya/p/79…