Detailed explanation of common Ansible modules

Posted by adam87 on Wed, 29 Dec 2021 11:44:34 +0100

Ansible common modules

At the end of 2015, there were more than 270 modules, reaching 540 in 2016, 1378 modules on January 12, 2018, 1852 modules on July 15, 2018, 2080 modules on May 25, 2019 (ansible 2.7.10), and 3387 modules on March 2, 2020

Although there are many modules, the most commonly used modules are only 2 or 30, and only 10 modules are used for specific services

Common module help document reference:

https://docs.ansible.com/ansible/latest/modules/modules_by_category.html
Command module

Function: execute commands on the remote host. This is the default module, and the - m option can be ignored

Note: this command does not support $Varname < >& Etc., implemented with shell module

example:

[root@ansible ~]#ansible websrvs -m command -a 'chdir=/etc cat centos-release'
10.0.0.7 | CHANGED | rc=0 >>
CentOS Linux release 7.7.1908 (Core)
10.0.0.8 | CHANGED | rc=0 >>
CentOS Linux release 8.1.1911 (Core)
[root@ansible ~]#ansible websrvs -m command -a 'chdir=/etc creates=/data/f1.txt cat centos-release'
10.0.0.7 | CHANGED | rc=0 >>
CentOS Linux release 7.7.1908 (Core)
10.0.0.8 | SUCCESS | rc=0 >>
skipped, since /data/f1.txt exists
[root@ansible ~]#ansible websrvs -m command -a 'chdir=/etc removes=/data/f1.txt cat centos-release'
10.0.0.7 | SUCCESS | rc=0 >>
skipped, since /data/f1.txt does not exist
10.0.0.8 | CHANGED | rc=0 >>
CentOS Linux release 8.1.1911 (Core)

ansible websrvs -m command -a 'service vsftpd start' 
ansible websrvs -m command -a 'echo magedu |passwd --stdin wang'   
ansible websrvs -m command -a 'rm -rf /data/'
ansible websrvs -m command -a 'echo hello > /data/hello.log'
ansible websrvs -m command -a "echo $HOSTNAME"
Shell module

Function: similar to command, execute commands with shell

example:

[root@ansible ~]#ansible websrvs -m shell -a "echo HOSTNAME"
10.0.0.7 | CHANGED | rc=0 >>
ansible
10.0.0.8 | CHANGED | rc=0 >>
ansible
[root@ansible ~]#ansible websrvs -m shell -a 'echoHOSTNAME'
10.0.0.7 | CHANGED | rc=0 >>
centos7.wangxiaochun.com
10.0.0.8 | CHANGED | rc=0 >>
centos8.localdomain

[root@ansible ~]#ansible websrvs -m shell -a 'echo centos | passwd --stdin wang'
10.0.0.7 | CHANGED | rc=0 >>
Changing password for user wang.
passwd: all authentication tokens updated successfully.
10.0.0.8 | CHANGED | rc=0 >>
Changing password for user wang.
passwd: all authentication tokens updated successfully.
[root@ansible ~]#ansible websrvs -m shell -a 'ls -l /etc/shadow'
10.0.0.7 | CHANGED | rc=0 >>
---------- 1 root root 889 Mar  2 14:34 /etc/shadow
10.0.0.8 | CHANGED | rc=0 >>
---------- 1 root root 944 Mar  2 14:34 /etc/shadow
[root@ansible ~]#ansible websrvs -m shell -a 'echo hello > /data/hello.log'
10.0.0.7 | CHANGED | rc=0 >>

10.0.0.8 | CHANGED | rc=0 >>

[root@ansible ~]#ansible websrvs -m shell -a 'cat  /data/hello.log'
10.0.0.7 | CHANGED | rc=0 >>
hello
10.0.0.8 | CHANGED | rc=0 >>
hello

Note: the call execution command is similar to cat / TMP / test md | awk -F‘|’ ‘{print 1,1,1,2}’ &> /tmp/example. Txt these complex commands may fail even using a shell. The solution: when writing a script, copy it to the remote, execute it, and then pull the required results back to the machine executing the command

Example: replace command with shell module and set it as module

[root@ansible ~]#vim /etc/ansible/ansible.cfg
#Modify the following line
module_name = shell
Script module

Function: run scripts on ansible server on remote host

example:

ansible websrvs  -m script -a /data/test.sh
Copy module

Function: copy files from the master of the ansible server to the remote host

#If the target exists, it will be overwritten by default. It is specified here to back up first
ansible websrvs -m copy -a "src=/root/test1.sh dest=/tmp/test2.sh    owner=wang  mode=600 backup=yes" 
#Specify the content and directly generate the target file    
ansible websrvs -m copy -a "content='test line1\ntest line2' dest=/tmp/test.txt"
#Copy the files under / etc /, excluding the / etc / directory itself
ansible websrvs -m copy -a "src=/etc/ dest=/backup"
Fetch module

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

example:

ansible websrvs -m fetch -a 'src=/root/test.sh dest=/data/scripts' 

example:

[root@ansible ~]#ansible   all -m  fetch -a 'src=/etc/redhat-release dest=/data/os'
[root@ansible ~]#tree /data/os/
/data/os/
├── 10.0.0.6
│   └── etc
│       └── redhat-release
├── 10.0.0.7
│   └── etc
│       └── redhat-release
└── 10.0.0.8
    └── etc
        └── redhat-release

6 directories, 3 files
File module

Function: set file properties

example:

#Create an empty file
ansible all -m  file  -a 'path=/data/test.txt state=touch'
ansible all -m  file  -a 'path=/data/test.txt state=absent'
ansible all -m file -a "path=/root/test.sh owner=wang mode=755"
#Create directory
ansible all -m file -a "path=/data/mysql state=directory owner=mysql group=mysql"
#Create soft link
ansible all -m file -a 'src=/data/testfile  dest=/data/testfile-link state=link'
unarchive module

Function: unpacking and decompression

Implementation can be used in two ways:
1. After the compressed package on the ansible host is transferred to the remote host, unzip it to a specific directory, and set copy=yes
2. Decompress a compressed package on the remote host to the specified path, and set copy=no

Common parameters:

  • Copy: the default value is yes. When copy=yes, the copied file is copied from the ansible host to the remote host. If copy=no, the src source file will be found on the remote host
  • remote_src: it has the same function as copy and is mutually exclusive. yes means that it is on the remote host, not on the ansible host, and no means that the file is on the ansible host
  • src: source path, which can be the path on the ansible host or the path on the remote host. If it is the path on the remote host, you need to set copy=no
  • dest: destination path on remote host
  • mode: set the file permissions after decompression

example:

ansible all -m unarchive -a 'src=/data/foo.tgz dest=/var/lib/foo'
ansible all -m unarchive -a 'src=/tmp/foo.zip dest=/data copy=no mode=0777'
ansible all -m unarchive -a 'src=https://example.com/example.zip dest=/data copy=no'
Archive module

Function: package compression

example:

ansible websrvs -m archive  -a 'path=/var/log/ dest=/data/log.tar.bz2 format=bz2  owner=wang mode=0600'
3.4.9 Hostname module

Function: manage host names

example:

ansible node1 -m hostname -a "name=websrv" 
ansible 192.168.100.18 -m hostname -a 'name=node18.magedu.com'
Cron module

Function: schedule tasks
Support time: minute, hour, day, month, weekday

example:

#Backup database script
[root@centos8 ~]#cat mysql_backup.sh 
mysqldump -A -F --single-transaction --master-data=2 -q -uroot |gzip > /data/mysql_date +%F_%T.sql.gz
#Create task
ansible 10.0.0.8 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/root/mysql_backup.sh'
ansible websrvs   -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/dev/null' name=Synctime"
#Disable scheduled tasks
ansible websrvs   -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/dev/null' name=Synctime disabled=yes"
#Enable scheduled tasks
ansible websrvs   -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/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'
Yum module

Function: management package, only RHEL, CentOS and fedora are supported, and other versions of Ubuntu are not supported

example:

ansible websrvs -m yum -a 'name=httpd state=present'  #install
ansible websrvs -m yum -a 'name=httpd state=absent'  #delete
Service module

Function: Management Service

example:

ansible all -m service -a 'name=httpd state=started enabled=yes'
ansible all -m service -a 'name=httpd state=stopped'
ansible all -m service -a 'name=httpd state=reloaded'
ansible all -m shell -a "sed -i 's/^Listen 80/Listen 8080/' /etc/httpd/conf/httpd.conf"
ansible all -m service -a 'name=httpd state=restarted' 
User module

Function: manage users

example:

#Create user
ansible all -m user -a 'name=user1 comment="test user" uid=2048 home=/app/user1 group=root'

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'

#Delete user, home directory and other data
ansible all -m user -a 'name=nginx state=absent remove=yes'
Group module

Function: Management Group

example:

#Create group
ansible websrvs -m group  -a 'name=nginx gid=88 system=yes'
#delete group
ansible websrvs -m group  -a 'name=nginx state=absent'
Lineinfile module

When using sed for replacement, ansible often encounters the problem of escape, and ansible has problems when encountering special symbols for replacement, so it cannot replace normally. In fact, ansible itself provides two modules: lineinfile module and replace module, which can be easily replaced

Function: equivalent to sed, you can modify the file content

example:

ansible all -m   lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=enforcing'"
ansible all -m lineinfile  -a 'dest=/etc/fstab state=absent regexp="^#"'
Replace module

This module is a bit similar to the sed command. It is mainly based on regular matching and replacement

example:

ansible all -m replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1'"  
ansible all -m replace -a "path=/etc/fstab regexp='^#(.*)' replace='\1'"
Setup module

Function: the setup module collects the system information of the host. These facts information can be used directly in the form of variables. However, if there are many hosts, it will affect the execution speed. You can use gather_facts: no to prevent Ansible from collecting facts information

example:

ansible all -m setup
ansible all -m setup -a "filter=ansible_nodename"
ansible all -m setup -a "filter=ansible_hostname"
ansible all -m setup -a "filter=ansible_domain"
ansible all -m setup -a "filter=ansible_memtotal_mb"
ansible all -m setup -a "filter=ansible_memory_mb"
ansible all -m setup -a "filter=ansible_memfree_mb"
ansible all -m setup -a "filter=ansible_os_family"
ansible all -m setup -a "filter=ansible_distribution_major_version"
ansible all -m setup -a "filter=ansible_distribution_version"
ansible all -m setup -a "filter=ansible_processor_vcpus"
ansible all -m setup -a "filter=ansible_all_ipv4_addresses"
ansible all -m setup -a "filter=ansible_architecture"
ansible all -m  setup  -a "filter=ansible_processor*"

example:

[root@ansible ~]#ansible all  -m  setup -a 'filter=ansible_python_version'
10.0.0.7 | SUCCESS => {
    "ansible_facts": {
        "ansible_python_version": "2.7.5",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
10.0.0.6 | SUCCESS => {
    "ansible_facts": {
        "ansible_python_version": "2.6.6",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
10.0.0.8 | SUCCESS => {
    "ansible_facts": {
        "ansible_python_version": "3.6.8",
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}
[root@ansible ~]#

Link to this article: http://www.yunweipai.com/34676.html

Topics: Linux