ansible -- Usage and common modules

Keywords: Linux Operation & Maintenance ssh

1. Install ansible package

[root@centos8 ~]yum -y install ansible

2. Modify profile

###Purpose: to cancel the error (yes/no) that occurs every time you connect to the remote host
[root@centos8 ~]#vim /etc/ssh/ssh_config
#Modify the following line
StrictHostKeyChecking no
[root@centos8 ~]#vim /etc/ansible/ansible.cfg 
Uncomment the line
host_key_checking = False

3. Most of the related tools realize the configuration management, application deployment and task execution of remote hosts through ssh protocol

Suggestion: configure the before using this tool ansible The master can contact each managed node based on key authentication  
Example: Implementation Based on key Validated script

[root@centos8 ~]#cat 
#Set the last address of the network segment, between 4-255. The smaller the address, the faster the scan
IP=`ip a s ens160 | awk -F'[ /]+' 'NR==3{print $3}'`
rm -f /root/.ssh/id_rsa
[ -e ./SCANIP.log ] && rm -f SCANIP.log
ping -c 1 -w 1  ${NET}$i &> /dev/null  && echo "${NET}$i" >> SCANIP.log &
ssh-keygen -P "" -f /root/.ssh/id_rsa
rpm -q sshpass || yum -y install sshpass
sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no $IP 
AliveIP=(`cat SCANIP.log`)
for n in ${AliveIP[*]};do
sshpass -p $PASS scp -o StrictHostKeyChecking=no -r /root/.ssh root@${n}:
#Put. ssh/known_hosts is copied to all hosts so that they do not need to enter carriage return when they access each other for the first time
for n in ${AliveIP[*]};do
scp /root/.ssh/known_hosts ${n}:.ssh/

ansible common modules and commands

ansible-doc:This tool is equivalent to man With the help command, you can query the usage of each module
##List all modules
[root@centos8 ~]#ansible-doc -l
##View the usage of the specified module
[root@centos8 ~]#ansible-doc -s  command
- chdir
        Change into this directory before running the command.
        [Default: (null)]
        type: path
        version_added: 0.6
- cmd
        The command to run.
        [Default: (null)]
        type: str
- creates
        A filename or (since 2.0) glob pattern. If it already exists,
        this step *won't* be run.
        [Default: (null)]
        type: path
- free_form
        The command module takes a free form command to run.
        There is no actual parameter named 'free form'.
        [Default: (null)]

ansible common commands


ansible Host name (group name in host name list) -m (modular) -a 
--version #Display version
##-m module #Specify the module. The default is command
##--list-hosts #Displays the host list, which can be abbreviated as -- list
 be careful: ansible -all/Group name list
##-C, --check #Check, not performed (required)
-T, --timeout=TIMEOUT #The timeout for executing the command, which is 10s by default
-k, --ask-pass #Prompt for ssh connection password. The default is Key authentication
##-u, --user=REMOTE_USER #The user who executes remote execution. The default is root
-b, --become #Replace the old sudo switch
##--become-user=USERNAME #Specify the runas user of sudo. The default is root
##-K, --ask-become-pass #Prompt for sudo password
-f FORKS, --forks FORKS #Specifies the number of hosts concurrently executing ansible tasks
 Note: Dimensions#Numbers are common commands

Modify the default module

[root@centos8 ~]#vim /etc/ansible/ansible.cfg 
Modify this row
#module_name = command

Execution process of ansible command

1,Load your own profile

2,Load the corresponding module file

 3,adopt ansible Generate the module or command into the corresponding temporary py File and transfer the file to the corresponding execution user of the remote server
$HOME/.ansible/tmp/ansible-tmp-number/XXX.PY file
4,to ansible File+x Execution Authority  
5,Execute and return results
6,Delete temporary py File, exit

Common color judgment

Green: perform operations that are successful and do not require changes

Yellow: the execution is successful and changes are made to the target host

Red: execution failed

Common modules

1,command: Execute the command on the remote host. This is the default module and can be ignored-m option
 Redirection is not supported(<>)Pipe characters are not supported(|)Wait, you can use it shell The module implements this line of functions
##command module
[root@centos8 ~]#ansible -a 'echo hello > /data/f1.txt ' | CHANGED | rc=0 >>
hello > /data/f1.txt
##shell module (upgraded command)
[root@centos8 ~]#ansible -m shell -a 'echo hello > /data/f1.txt ' | CHANGED | rc=0 >>
[root@centos8 ~]#ansible -m shell -a 'cat /data/f1.txt ' | CHANGED | rc=0 >>
This module is not idempotent (the result does not change no matter how many times the command is executed)

(1)chdir:Please switch to this path before executing the command
##It is equivalent to executing cat / etc / CentOS release
[root@centos8 ~]#ansible all -a 'chdir=/etc   cat centos-release ' | CHANGED | rc=0 >>
CentOS Linux release 7.2.1511 (Core) | CHANGED | rc=0 >>
CentOS Linux release 8.0.1905 (Core) | CHANGED | rc=0 >>
CentOS Linux release 8.0.1905 (Core) | CHANGED | rc=0 >>
CentOS Linux release 8.0.1905 (Core) 
##If the / data/f1.txt file exists, execute cat / etc / CentOS release
[root@centos8 ~]#ansible -a 'chdir=/etc creates=/data/f1.txt  cat centos-release ' | SUCCESS | rc=0 >>
skipped, since /data/f1.txt exists
##If the / data/f2.txt file does not exist, execute cat / etc / CentOS release
[root@centos8 ~]#ansible -a 'chdir=/etc creates=/data/f2.txt  cat centos-release ' | CHANGED | rc=0 >>
CentOS Linux release 7.2.1511 (Core) 
(3)removes(and creates (similar)
[root@centos8 ~]#ansible -a 'chdir=/etc removes=/data/f3.txt  cat centos-release ' | SUCCESS | rc=0 >>
skipped, since /data/f3.txt does not exist
[root@centos8 ~]#ansible all -a 'chdir=/etc removes=/data/f1.txt  cat centos-release ' | CHANGED | rc=0 >>
CentOS Linux release 7.2.1511 (Core) 

2. shell module (upgraded command): you can execute > < | $and so on
Note: call bash to execute commands like cat /tmp/ | awk -F '|' {print {,}} '& > / TMP / example.txt
Complex commands may fail even when using a shell. The solution: when writing a script, copy it to the remote, execute it, and then send the required results
Pull back the machine that executes the command

3. Script module: run the script on the ansible server on the remote host (no execution permission is required)

[root@centos8 ~]#ansible websrvs -m script -a /data/

4. Copy module: copy files from the master control side of the ansible server to the remote host
Note: src=file if no path is specified, it is the file file in the current directory or the files directory under the current directory

#If the target exists, it will be overwritten by default. It is specified here to back up first
[root@centos8 ~]#
ansible websrvs -m copy -a "src=/root/ dest=/tmp/ owner=wang
mode=600 backup=yes"
#Specify the content and directly generate the target file
[root@centos8 ~]#
ansible websrvs -m copy -a "content='test line1\ntest line2\n'
#Copy the / data directory itself. Note that there is no following / data //
[root@centos8 ~]#touch /data/f{1..4}.log
[root@centos8 ~]# ansible -m copy -a "src=/data/  dest=/tmp"
[root@centos8 tmp]#ls
#Copy the files under / data /, excluding the / data / directory itself. Note that there are/
[root@centos8 ~]#
ansible websrvs -m copy -a "src=/data/ dest=/backup"
[root@centos8 tmp]#ls
f1.log  f2.log  f4.log  vmware-root_796-2991202916
etc   f1.txt  f3.log  source 

5. Get_url module: used to download files from http, https or ftp to the managed machine node
URL: the URL to download the file. It supports HTTP, HTTPS or FTP protocols
dest: download to the target path (absolute path). If the target is a directory, use the name of the file on the server. If the target has a name set
Use the name of the target setting
Owner: Specifies the owner
Group: specify the group
mode: specify permissions
force: If yes, dest is not a directory, the file will be downloaded each time. If the content changes, the file will be replaced. If no, it will only be saved when the target does not exist
The file will not be downloaded until
checksum: calculate the summary of the target file after downloading to ensure its integrity

[root@ansible ~]#ansible websrvs -m get_url -a

6. Fetch module: extract files from the remote host to the master of ansible. On the contrary, copy does not support directories at present

[root@centos8 ~]#
ansible websrvs -m fetch -a 'src=/root/ dest=/data/scripts'
[root@ansible ~]#ansible all -m fetch -a 'src=/etc/redhat-release
[root@centos8 ~]#tree /data/os/
│ └── etc
│ └── redhat-release
│ └── etc
│ └── redhat-release
└── etc
└── redhat-release
6 directories, 3 files

7. File module: set file attributes, create soft links, etc

##Create an empty file
[root@centos8 ~]# ansible -m copy -a "src=/data  dest=/tmp"
[root@centos8 ~]#ansible -a "ls -ld /data/test.txt" | CHANGED | rc=0 >>
-rw-r--r--. 1 root root 0 Dec  3 21:08 /data/test.txt
##Delete file
[root@centos8 ~]#ansible -m file -a "path=/data/test.txt state=absent"
ansible all -m file -a "path=/root/ owner=wang mode=755"
#Create directory
ansible all -m file -a "path=/data/mysql state=directory owner=mysql
#Create soft link
ansible all -m file -a 'src=/data/testfile path|dest|name=/data/testfile-link
#Create directory
ansible all -m file -a 'path=/data/testdir state=directory'
#Modify directory properties recursively, but not to subdirectories
ansible all -m file -a "path=/data/mysql state=directory owner=mysql
#Recursively modify the properties of directories and subdirectories
ansible all -m file -a "path=/data/mysql state=directory owner=mysql group=mysql

8. stat module: check the status of the file system (very important)
Path: the full path of the file / object (required)
Common return value judgment
Exists: determines whether the exists
isuid: whether the ID of the calling user matches the owner ID

root@ansible ~]#ansible -m stat -a 'path=/etc/passwd' | SUCCESS => {
"changed": false,
"stat": {
"atime": 1614601466.7493012,
"attr_flags": "",
"attributes": [],
"block_size": 4096,
"blocks": 8,
"charset": "us-ascii",
"checksum": "8f7a9a996d24de98bf1eab4a047f8e89e9c708cf",
"ctime": 1614334259.4498665,

**9. unarchive module: unpacking and decompressing
Implementation can be used in two ways:

1,take ansible After the compressed package on the host is transferred to the remote host, it is decompressed to a specific directory and set copy=yes,This is the default,Can be omitted
2,Decompress a compressed package on the remote host to the specified path and set copy  
copy: Default to yes,When copy=yes,The copied file is from ansible Copy host to remote host, if set to copy=no,
Will be found on the remote host src source file
remote_src: and copy The functions are the same and mutually exclusive, yes Indicates that it is on the remote host, not on the remote host ansible host, no Indicates that the file is in ansible
 On the host
src: Source path, which can be ansible The path on the host can also be a remote host(Managed end or third-party host)Path on, if
 If it is a path on the remote host, it needs to be set copy=no
dest: Destination path on remote host
mode: Set the permissions of the extracted file**
[root@centos8 ~]#ansible all -m unarchive -a 'src=/data/foo.tgz dest=/var/lib/foo owner=wang
[root@centos8 ~]#ansible all -m unarchive -a 'src=/tmp/ dest=/data copy=no mode=0777'
[root@centos8 ~]#ansible all -m unarchive -a 'src= dest=/data
[root@centos8 ~]#ansible websrvs -m unarchive -a
dest=/data/ owner=root remote_src=yes'
[root@centos8 ~]#ansible websrvs -m unarchive -a 'src=
1.18.0.tar.gz dest=/usr/local/src/ copy=no'

10. archive: package, compress and save in the managed node

[root@centos8 ~]#ansible websrvs -m archive -a 'path=/var/log/ dest=/data/log.tar.bz2 format=bz2
owner=wang mode=0600'

11. Hostname module: manage hostname

[root@centos8 ~]ansible node1 -m hostname -a "name=websrv"
[root@centos8 ~]ansible -m hostname -a ''

12. cron module: scheduling tasks
Support time: * corresponds to minute, hour, day, month and weekday respectively

#Backup database script
[root@centos8 ~]#cat /root/
mysqldump -A -F --single-transaction --master-data=2 -q -uroot |gzip >
/data/mysql_`date +%F_%T`.sql.gz
#Create task
ansible -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql"
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate
&>/dev/null' name=Synctime"
#Disable scheduled tasks
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate
&>/dev/null' name=Synctime disabled=yes"
#Enable scheduled tasks
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate
&>/dev/null' name=Synctime disabled=no"
#Delete task
ansible websrvs -m cron -a "name='backup mysql' state=absent"
ansible websrvs -m cron -a 'state=absent name=Synctime

13. yum and apt module: management package
yum management package, which only supports RHEL, CentOS and fedora, but does not support other versions of Ubuntu
apt module manages the packages of Debian related versions

###Install httpd package
[root@centos8 ~]#ansible websrvs -m yum -a 'name=httpd state=present' 
###Enable epel source for installation
[root@centos8 ~]#ansible websrvs -m yum -a 'name=nginx state=present enablerepo=epel'
###Upgrade packages other than those beginning with kernel and foo
[root@centos8 ~]#ansible websrvs -m yum -a 'name=* state=lastest exclude=kernel*,foo*'
###Delete httpd package
[root@centos8 ~]#ansible websrvs -m yum -a 'name=httpd state=absent'
[root@ansible ~]#ansible websrvs -m yum -a 'name=sl,cowsay'
###Download the installation package from a third party
[root@ansible ~]#ansible websrvs -m yum -a
###Install / remove multiple installation packages at the same time
[root@centos8 ~]#ansible -m apt -a
[root@centos8 ~]#ansible websrvs -m apt -a 'name=rsync,psmisc state=absent'
###View package
[root@ansible ~]#ansible localhost -m yum -a "list=tree"

14. User module: manage users (passwd,user,home, etc.)
Option: comment: Annotation

##Create user
[root@centos8 ~]#ansible all -m user -a 'name=user1 comment="test user" uid=2048 home=/app/user1
[root@centos8 ~]#ansible all -m user -a 'name=nginx comment=nginx uid=88 group=nginx
groups="root,daemon" shell=/sbin/nologin system=yes create_home=no
home=/data/nginx non_unique=yes'
#remove=yes means to delete data such as user and home directory. The default is remove=no
[root@centos8 ~]#ansible all -m user -a 'name=nginx state=absent remove=yes'

15. group module: managing groups

#Create group
[root@centos8 ~]ansible websrvs -m group -a 'name=nginx gid=88 system=yes'
#delete group
[root@centos8 ~]ansible websrvs -m group -a 'name=nginx state=absent

16. Lineinfile module: equivalent to sed, which can modify the file content
If you want to match multiple rows for replacement, you need to use the replace module

[root@centos8 ~]#ansible websrvs -m lineinfile -a "path=/etc/httpd/conf/httpd.conf
regexp='^Listen' line='Listen 80'"
[root@centos8 ~]#ansible all -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX='
[root@centos8 ~]#ansible all -m lineinfile -a 'dest=/etc/fstab state=absent regexp="^#"'

17. Replace module: This module is a bit similar to the sed command. It is mainly based on regular matching and replacement. It is recommended to use

[root@centos8 ~]#ansible all -m replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1'"
[root@centos8 ~]#ansible all -m replace -a "path=/etc/fstab regexp='^#(UUID.*)' replace='\1'"

18. reboot module
19. 3.4.24 debug module: This module can be used to output information and customize the output information content through msg
Note: variables after msg sometimes need to be quoted with ""

[root@centos8 ~]#ansible -m debug | SUCCESS => {
"msg": "Hello world!"
 [root@ansible ansible]#cat debug.yml
 hosts: websrvs
- name: output Hello world
The default is not specified msg,Default output"Hello world!"

Posted by galayman on Fri, 03 Dec 2021 22:26:28 -0800