Detailed Explanation of Common Ansible Modules

Although there are many modules, only about 20 to 30 are commonly used. For specific business needs, only about a dozen modules are frequently used. Reference for common module documentation:

https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html
https://docs.ansible.com/ansible/2.9/modules/list_of_all_modules.html
https://docs.ansible.com/ansible/latest/modules/list_of_all_modules.html
https://docs.ansible.com/ansible/latest/modules/modules_by_category.html

Command Module

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

Note: This command does not support $VARNAME < > | ; & and similar symbols, which may be implemented using the shell module.

Note: This module is not idempotent.

Example:

[root@centos8 ~]# ansible websrvs -m command -a 'chdir=/etc cat centos-release'
172.31.0.48 | CHANGED | rc=0 >>
CentOS Linux release 8.1.1911 (Core) 
172.31.0.38 | CHANGED | rc=0 >>
CentOS Linux release 8.1.1911 (Core)

[root@centos8 ~]# ansible websrvs -m command -a 'chdir=/etc creates=/data/f1.txt cat centos-release'
172.31.0.48 | CHANGED | rc=0 >>
CentOS Linux release 7.7.1908 (Core)
172.31.0.38 | 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'
172.31.0.48 | SUCCESS | rc=0 >>
skipped, since /data/f1.txt does not exist
172.31.0.38 | CHANGED | rc=0 >>
CentOS Linux release 8.1.1911 (Core)

[root@ansible ~]# ansible websrvs -m command -a 'service vsftpd start'
[root@ansible ~]# ansible websrvs -m command -a 'echo centos |passwd --stdin wang'
[root@ansible ~]# ansible websrvs -m command -a 'rm -rf /data/'
[root@ansible ~]# ansible websrvs -m command -a 'echo hello > /data/hello.log'
[root@ansible ~]# ansible websrvs -m command -a "echo $HOSTNAME"

Shell Module

Function: Similar to command, executes commands using the shell, supporting various symbols like: *, $, >

Note: This module is not idempotent.

Example:

[root@centos8 ~]# ansible websrvs -m shell -a 'echo $HOSTNAME'
172.31.0.38 | CHANGED | rc=0 >>
centos8.longxuan.vip
172.31.0.48 | CHANGED | rc=0 >>
centos8.longxuan.vip

[root@centos8 ~]# ansible websrvs -m shell -a 'echo centos | passwd --stdin long'
172.31.0.48 | CHANGED | rc=0 >>
Changing password for user long.
passwd: all authentication tokens updated successfully.
172.31.0.38 | CHANGED | rc=0 >>
Changing password for user long.
passwd: all authentication tokens updated successfully.

[root@centos8 ~]# ansible websrvs -m shell -a 'ls -l /etc/shadow'
172.31.0.48 | CHANGED | rc=0 >>
---------- 1 root root 829 May 25 05:31 /etc/shadow
172.31.0.38 | CHANGED | rc=0 >>
---------- 1 root root 829 May 25 05:31 /etc/shadow

[root@centos8 ~]# ansible websrvs -m shell -a 'echo hello > /home/hello.log'
172.31.0.48 | CHANGED | rc=0 >>

172.31.0.38 | CHANGED | rc=0 >>

[root@centos8 ~]# ansible websrvs -m shell -a 'cat /home/hello.log'
172.31.0.38 | CHANGED | rc=0 >>
hello
172.31.0.48 | CHANGED | rc=0 >>
hello

Note: Invoking bash to execute commands similar to cat /tmp/test.md | awk -F’|’ ‘{print $1,$2}’ > /tmp/example.txt may fail even when using shell. Solution: write to a script, copy it to the remote, execute it, and then pull the required results back to the executing machine.

Example: Use shell module instead of command, set as module.

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

Script Module

Function: Run scripts from the Ansible server on remote hosts (no execution permission required).

Note: This module is not idempotent.

Example:

[root@centos8 ~]# ansible websrvs -m script -a /home/test.sh

Copy Module

Function: Copy files from the Ansible control machine to remote hosts.

Note: If src=file is not specified, it defaults to the current directory or the files directory under the current directory.

# If the target exists, it defaults to overwrite, specify backup first here
[root@centos8 ~]# ansible websrvs -m copy -a "src=/root/test1.sh dest=/tmp/test2.sh owner=wang mode=600 backup=yes"
# Specify content to directly generate the target file
[root@centos8 ~]# ansible websrvs -m copy -a "content='test line1\ntest line2\n' dest=/tmp/test.txt"
# Copy the /etc directory itself, note that there is no trailing slash after /etc/
[root@centos8 ~]# ansible websrvs -m copy -a "src=/etc dest=/backup"
# Copy files under /etc/, not including the /etc/ directory itself, note that there is a trailing slash after /etc/
[root@centos8 ~]# ansible websrvs -m copy -a "src=/etc/ dest=/backup"

Get_url Module

Function: Used to download files from http, https, or ftp to managed nodes.

Common parameters are as follows:

url: URL of the file to download, supports HTTP, HTTPS, or FTP protocols
dest: Absolute path to download to. If the target is a directory, it uses the name of the file on the server. If a name is set for the target, it uses the specified name.
owner: Specify owner
group: Specify group
mode: Specify permissions
force: If yes, dest is not a directory, it will download the file every time. If no, it will only download the file if the target does not exist.
checksum: Calculate the checksum of the target file after downloading to ensure its integrity
Example: checksum="sha256:D98291AC[...]B6DC7B97",
checksum="sha256:http://example.com/path/sha256sum.txt"
url_username: Username for HTTP basic authentication. This parameter may be omitted for sites that allow empty passwords.
url_password: Password for HTTP basic authentication. If the `url_username` parameter is not specified, the `url_password` parameter will not be used.
validate_certs: If "no", SSL certificates will not be validated. Suitable for self-signed certificates used on private sites
timeout: Timeout for URL requests, in seconds

Example:

[root@centos8 ~]# ansible websrvs -m get_url -a 'url=http://nginx.org/download/nginx-1.18.0.tar.gz dest=/usr/local/src/nginx.tar.gz checksum="md5:b2d33d24d89b8b1f87ff5d251aa27eb8"'

Fetch Module

Function: Extract files from remote hosts to the Ansible control machine, opposite of copy, currently does not support directories.

Example:

[root@centos8 ~]# ansible websrvs -m fetch -a 'src=/root/test.sh dest=/data/scripts'

Example:

[root@centos8 ~]# ansible all -m fetch -a 'src=/etc/redhat-release dest=/data/os'

[root@centos8 ~]# tree /data/os/
/data/os/
├── 172.31.0.6
│   └── etc
│       └── redhat-release
├── 172.31.0.7
│   └── etc
│       └── redhat-release
└── 172.31.0.8
    └── etc
        └── redhat-release
6 directories, 3 files

File Module

Function: Set file attributes, create symbolic links, etc.

Example:

# Create an empty file
[root@centos8 ~]# ansible websrvs -m file -a 'path=/tmp/test.txt state=touch'
172.31.0.38 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/tmp/test.txt",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "root",
    "size": 0,
    "state": "file",
    "uid": 0
}
172.31.0.48 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/tmp/test.txt",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "root",
    "size": 0,
    "state": "file",
    "uid": 0
}

# Delete an empty file
[root@centos8 ~]# ansible websrvs -m file -a 'path=/tmp/test.txt state=absent'
172.31.0.48 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "path": "/tmp/test.txt",
    "state": "absent"
}
172.31.0.38 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "path": "/tmp/test.txt",
    "state": "absent"
}

# Change ownership
[root@centos8 ~]# ansible websrvs -m file -a 'path=/root/test.sh owner=long mode=755'

# Create a directory
[root@centos8 ~]# ansible all -m file -a "path=/data/mysql state=directory owner=mysql group=mysql"

# Create a symbolic link
[root@centos8 ~]# ansible all -m file -a 'src=/data/testfile path|dest|name=/data/testfile-link state=link'

# Create a directory
[root@centos8 ~]# ansible websrvs -m file -a 'path=/tmp/testdir state=directory'

# Recursively modify attributes of the directory and subdirectories
[root@centos8 ~]# ansible websrvs -m file -a 'path=/data/mysql state=directory owner=mysql group=mysql recurse=yes'

# Recursively modify directory attributes, but not down to subdirectories
[root@centos8 ~]# ansible websrvs -m file -a 'path=/data/mysql state=directory owner=mysql group=mysql'

Stat Module

Function: Check the status of files or file systems.

Note: For Windows targets, please use the win_stat module.

Options:

path: Full path of the file/object (required)

Common return values include:

exists: Check if it exists
isuid: Whether the calling user's ID matches the owner ID

Example:

[root@centos8 ~]# ansible 127.0.0.1 -m stat -a 'path=/etc/passwd'
127.0.0.1 | SUCCESS => {
    "changed": false,
    "stat": {
        "atime": 1621882861.7590294,
        "attr_flags": "",
        "attributes": [],
        "block_size": 4096,
        "blocks": 8,
        "charset": "us-ascii",
        "checksum": "056025cd699efaa095eb3ae845130765034fa44c",
        "ctime": 1621455327.1228225,
        "dev": 2050,
        "device_type": 0,
        "executable": false,
        "exists": true,
        "gid": 0,
        "gr_name": "root",
        "inode": 33990246,
        "isblk": false,
        "ischr": false,
        "isdir": false,
        "isfifo": false,
        "isgid": false,
        "islnk": false,
        "isreg": true,
        "issock": false,
        "isuid": false,
        "mimetype": "text/plain",
        "mode": "0644",
        "mtime": 1621455327.1228225,
        "nlink": 1,
        "path": "/etc/passwd",
        "pw_name": "root",
        "readable": true,
        "rgrp": true,
        "roth": true,
        "rusr": true,
        "size": 1088,
        "uid": 0,
        "version": "767136742",
        "wgrp": false,
        "woth": false,
        "writeable": true,
        "wusr": true,
        "xgrp": false,
        "xoth": false,
        "xusr": false
    }
}

Example:

- name: install | Check if file is already configured.
  stat: path={{ nginx_file_path }}
  connection: local
  register: nginx_file_result
- name: install | Download nginx file
  get_url: url={{ nginx_file_url }} dest={{ software_files_path }}
validate_certs=no
  connection: local
  when: not nginx_file_result.stat.exists

Example:

[root@centos8 ~]# vim stat.yml
---
- hosts: websrvs
  
  tasks:
    - name: check file
      stat: path=/data/mysql
      register: st
    - name: debug
      debug:
        msg: "/data/mysql is not exist"
      when: not st.stat.exists

Example: Execute

[root@centos8 ~]# ansible-playbook stat.yml 

PLAY [websrvs] *********************************************************************************

TASK [Gathering Facts] *************************************************************************
ok: [172.31.0.48]
ok: [172.31.0.38]

TASK [check file] ******************************************************************************
ok: [172.31.0.38]
ok: [172.31.0.48]

TASK [debug] ***********************************************************************************
skipping: [172.31.0.38]
skipping: [172.31.0.48]

PLAY RECAP *************************************************************************************
172.31.0.38                : ok=2    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
172.31.0.48                : ok=2    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0

Unarchive Module

Function: Unpack and decompress.

There are two common usages:

1. Transfer a compressed package from the Ansible host to the remote host and decompress it to a specific directory, set copy=yes, which is the default value and can be omitted. 2. Decompress a compressed package from the remote host to a specified path, set copy=no.

Common parameters:

copy: Defaults to yes. When copy=yes, the file is copied from the Ansible host to the remote host. If set to copy=no, it will look for the src source file on the remote host.
remote_src: Functions similarly to copy and is mutually exclusive. yes indicates it is on the remote host, no indicates the file is on the Ansible host.
src: Source path, can be a path on the Ansible host or a path on the remote host (managed endpoint or third-party host). If it is a path on the remote host, copy=no needs to be set.
dest: Target path on the remote host
mode: Set permissions for the decompressed files

Example:

[root@centos8 ~]# ansible websrvs -m unarchive -a 'src=/data/foo.tgz dest=/var/lib/foo owner=long group=bin'

# Decompress local package cp to the target host and authorize
[root@centos8 ~]# ansible websrvs -m unarchive -a 'src=/tmp/foo.zip dest=/data copy=no mode=0777'

# Use network to download zip package and copy to target host
[root@centos8 ~]# ansible websrvs -m unarchive -a 'src=https//example.com/example.zip dest=/data copy=no'

[root@centos8 ~]# ansible websrvs -m unarchive -a 'src=https://releases.ansible.com/ansible/ansible-2.1.6.0-0.1.rc1.tar.gz dest=/data/ owner=root remote_src=yes'

[root@centos8 ~]# ansible websrvs -m unarchive -a 'src=http://nginx.org/download/nginx-1.18.0.tar.gz dest=/usr/local/src/ copy=no'

Archive Module

Function: Package and compress to save on managed nodes.

Example:

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

Hostname Module

Function: Manage hostnames.

Example:

[root@centos8 ~]# ansible node1 -m hostname -a 'name=websrvs'

[root@ansible ~]# ansible 172.31.0.17 -m hostname -a 'name=node17.longxuan.vip'
172.31.0.17 | CHANGED => {
    "ansible_facts": {
        "ansible_domain": "longxuan.vip",
        "ansible_fqdn": "node17.longxuan.vip",
        "ansible_hostname": "node17",
        "ansible_nodename": "node17.longxuan.vip",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "name": "node17.longxuan.vip"
}

Cron Module

Function: Schedule tasks.

Supports time: minute, hour, day, month, weekday.

Example:

# Backup database script
[root@centos8 ~]# cat /root/mysql_backup.sh
#!/bin/bash
mysqldump -A -F --single-transaction --master-data=2 -q -uroot |gzip > /data/mysql_`date +%F_%T`.sql.gz

# Create task
[root@centos8 ~]# ansible 172.31.0.8 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/root/mysql_backup.sh'

[root@centos8 ~]# ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate ntp.aliyun.com &amp;&gt;/dev/null' name=Synctime"
 
# Disable scheduled task
[root@centos8 ~]# ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &amp;&gt;/dev/null' name=Synctime disabled=yes"

# Enable scheduled task
[root@centos8 ~]# ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &amp;&gt;/dev/null' name=Synctime disabled=no"

# Delete task
[root@centos8 ~]# ansible websrvs -m cron -a "name='backup mysql' state=absent"
[root@centos8 ~]# ansible websrvs -m cron -a 'state=absent name=Synctime'

Yum and Apt Modules

Function:

yum manages packages, only supports RHEL, CentOS, Fedora, does not support Ubuntu and other versions.

apt module manages packages related to Debian versions.

Example:

# Install
[root@centos8 ~]# ansible websrvs -m yum -a 'name=httpd state=present'

# Remove
[root@centos8 ~]# ansible websrvs -m yum -a 'name=httpd state=absent'

# Enable epel repo for installation
[root@centos8 ~]# ansible websrvs -m yum -a 'name=nginx state=present enablerepo=epel' 

# Upgrade all packages except kernel and those starting with foo
[root@centos8 ~]# ansible websrvs -m yum -a 'name=* state=lastest exclude=kernel*,foo*' 


[root@centos8 /opt]# sl
-bash: sl: command not found
# Install
[root@centos8 ~]# ansible websrvs -m yum -a 'name=sl,cowsay'

Example:

[root@ansible ~]# ansible websrvs -m yum -a "name=https://mirror.tuna.tsinghua.edu.cn/zabbix/zabbix/5.2/rhel/7/x86_64/zabbixagent-5.2.5-1.el7.x86_64.rpm"

Example:

[root@centos8 ~]# ansible 10.0.0.100 -m apt -a 'name=bb,sl,cowsay,cmatrix,oneko,hollywood,boxes,libaa-bin,x11-apps'

# Ubuntu apt remove software
[root@centos8 ~]# ansible websrvs -m apt -a 'name=rsync,psmisc state=absent'

Example: View package

[17:22:37 root@centos8 ~]# ansible localhost -m yum -a 'list=tree'
localhost | SUCCESS => {
    "ansible_facts": {
        "pkg_mgr": "dnf"
    },
    "changed": false,
    "msg": "",
    "results": [
        {
            "arch": "x86_64",
            "epoch": "0",
            "name": "tree",
            "nevra": "0:tree-1.7.0-15.el8.x86_64",
            "release": "15.el8",
            "repo": "@System",
            "version": "1.7.0",
            "yumstate": "installed"
        },
        {
            "arch": "x86_64",
            "epoch": "0",
            "name": "tree",
            "nevra": "0:tree-1.7.0-15.el8.x86_64",
            "release": "15.el8",
            "repo": "BaseOS",
            "version": "1.7.0",
            "yumstate": "available"
        }
    ]
}

yum_repository Module

- name: Add multiple repositories into the same file (1/2)
  yum_repository:
    name: epel
    description: EPEL YUM repo
    file: external_repos
    baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
    gpgcheck: no
    
- name: Add multiple repositories into the same file (2/2)
  yum_repository:
    name: rpmforge
    description: RPMforge YUM repo
    file: external_repos
    baseurl: http://apt.sw.be/redhat/el7/en/$basearch/rpmforge
    mirrorlist: http://mirrorlist.repoforge.org/el7/mirrors-rpmforge
    enabled: no
    
- name: Remove repository from a specific repo file
  yum_repository:
    name: epel
    file: external_repos
    state: absent

Example: Create and delete a repository

[root@ansible ~]# cat yum_repo.yml
- hosts: websrvs
  tasks:
    - name: Add multiple repositories into the same file
      yum_repository:
        name: test
        description: EPEL YUM repo
        file: external_repos
        baseurl:
        https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
        gpgcheck: no

[root@ansible ~]# ansible-playbook yum_repo.yml

[root@web1 ~]# cat /etc/yum.repos.d/external_repos.repo
[test]
baseurl = https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
gpgcheck = 0
name = EPEL YUM repo
[root@ansible ~]#cat remove_yum_repo.yml
- hosts: websrvs
  tasks:
    - name: remove repo
      yum_repository:
        name: test
        file: external_repos
        state: absent
        
[root@ansible ~]# ansible-playbook remove_yum_repo.yml

Service Module

Function: Manage services.

Example:

# Start and set to start on boot
[root@centos8 ~]# ansible websrvs -m service -a 'name=httpd  state=started enabled=yes'

# Stop httpd service
[root@centos8 ~]# ansible websrvs -m service -a 'name=httpd state=stopped'

# Restart httpd service
[root@centos8 ~]# ansible websrvs -m service -a 'name=httpd state=reloaded'

# Use sed command in shell module to change port number
[root@centos8 ~]# ansible websrvs -m shell -a "sed -ri 's/^(Listen )80/\18080/' /etc/httpd/conf/httpd.conf"

# Restart httpd service to apply the above port change
[17:42:39 root@centos8 ~]# ansible websrvs -m service -a 'name=httpd state=restarted'

User Module

Function: Manage users.

Example:

# Create user
[root@centos8 ~]# ansible websrvs -m user -a 'name=user1 comment="test user" uid=2021 home=/app/user1 group=root'

[root@centos8 ~]# ansible websrvs -m user -a 'name=www comment=www uid=80 group=nginx groups="root,daemon" shell=/sbin/nologin system=yes create_home=no home=/data/nginx non_unique=yes'

# remove=yes indicates to delete the user and home directory data, default remove=no
[root@centos8 ~]# ansible websrvs -m user -a 'name=nginx state=absent remove=yes'

# Generate encrypted password for 123456
[root@centos8 ~]# ansible localhost -m debug -a "msg={{ '123456' |password_hash('sha512','salt')}}"
localhost | SUCCESS => {
    "msg": "$6$salt$MktMKPZJ6t59GfxcJU20DwcwQzfMvOlHFVZiOVD71w.igcOo1R7vBYR65JquIQ/7siC7VRpmteKvZmfSkNc69."
}

# Create user using the above password
[root@centos8 ~]# ansible websrvs -m user -a 'name=test password="$6$salt$MktMKPZJ6t59GfxcJU20DwcwQzfMvOlHFVZiOVD71w.igcOo1R7vBYR65JquIQ/7siC7VRpmteKvZmfSkNc69."'

# Create user test and generate a 4096bit private key
[root@centos8 ~]# ansible websrvs -m user -a 'name=test generate_ssh_key=yes ssh_key_bits=4096 ssh_key_file=.ssh/id_rsa'

Group Module

Function: Manage groups.

Example:

# Create group
[root@centos8 ~]# ansible websrvs -m group -a 'name=nginx gid=80 system=yes'
172.31.0.48 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 80,
    "name": "nginx",
    "state": "present",
    "system": true
}
172.31.0.38 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 80,
    "name": "nginx",
    "state": "present",
    "system": true
}

# Delete group
[root@centos8 ~]# ansible websrvs -m group -a 'name=nginx state=absent'

Lineinfile Module

In Ansible, when using sed for replacements, there are often issues with escaping, and Ansible has problems with special symbols during replacements. In fact, Ansible provides two modules: lineinfile and replace, which can facilitate replacements.

Generally, when modifying a single line of a file in Ansible, the lineinfile module is used.

regexp parameter: Matches the corresponding line using a regular expression. When replacing text, if multiple lines of text can be matched, only the last matched line will be replaced. When deleting text, if multiple lines can be matched, those lines will all be deleted.

If you want to perform multi-line matching for replacement, you need to use the replace module.

Function: Equivalent to sed, can modify file content.

Example:

# Change httpd port number
[root@centos8 ~]# ansible websrvs -m lineinfile -a "path=/etc/httpd/conf/httpd.conf regexp='^Listen' line='Linsten 80'"

# Change Selinux to disabled
[root@centos8 ~]# ansible websrvs -m lineinfile -a "path=/etc/selinux/config regexp='SELINUX=' line='SELINUX=disabled'"

# Delete lines starting with # in /etc/fstab
[root@centos8 ~]# ansible websrvs -m lineinfile -a "dest=/etc/fstab state=absent regexp='^#'"

Replace Module

This module is somewhat similar to the sed command, primarily based on regular expressions for matching and replacing, it is recommended to use.

Example:

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

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

SELinux Module

This module manages SELinux policies. Example:

[root@ansible ~]# ansible 172.31.0.8 -m selinux -a 'state=disabled'
[WARNING]: SELinux state temporarily changed from 'enforcing' to 'permissive'.
State change will take effect next reboot.
172.31.0.8 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": true,
"configfile": "/etc/selinux/config",
"msg": "Config SELinux state changed from 'enforcing' to 'disabled'",
"policy": "targeted",
"reboot_required": true,
"state": "disabled"
}

[root@centos8 ~]# grep -v '#' /etc/selinux/config
SELINUX=disabled
SELINUXTYPE=targeted
[root@centos8 ~]# getenforce
Permissive

Reboot Module

Function: Restart target machines.

[root@ansible ~]# ansible websrvs -m reboot

Mount Module

Function: Mount and unmount file systems. Example:

# Temporary mount
[root@centos8 ~]# mount websrvs -m mount -a 'src="UUID=b3e48f45-f933-4c8e-a700-22a159ec9077" path=/home fstype=xfs opts=noatime state=present'

# Temporarily unmount
[root@centos8 ~]# mount websrvs -m mount -a 'path=/home fstype=xfs opts=noatime state=unmounted'

# Permanent mount
[root@centos8 ~]# ansible websrvs -m mount -a 'src=10.0.0.8:/data/wordpress path=/var/www/html/wpcontent/ uploads opts="_netdev" state=mounted'

# Permanent unmount
[root@centos8 ~]# ansible websrvs -m mount -a 'src=10.0.0.8:/data/wordpress path=/var/www/html/wpcontent/ uploads state=absent'

Setup Module

Function: The setup module is used to collect system information of hosts, and this facts information can be used directly as variables. However, if there are many hosts, it may affect execution speed.

You can use gather_facts: no to prevent Ansible from collecting facts information.

Example:

[root@centos8 ~]# ansible all -m setup
[root@centos8 ~]# ansible all -m setup -a 'filter=ansible_nodename'
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_hostname"
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_domain"
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_memtotal_mb"
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_memory_mb"
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_memfree_mb"
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_os_family"
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_distribution_major_version"
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_distribution_version"
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_processor_vcpus"
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_all_ipv4_addresses"
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_architecture"
[root@centos8 ~]# ansible all -m setup -a "filter=ansible_uptime_seconds"
[root@centos8 ~]# ansible all -m setup -a 'filter=ansible_env'

Example: Query the distribution version information of all target hosts.

[root@centos8 ~]# ansible all -m setup -a 'filter=ansible_os_family'
172.31.0.17 | SUCCESS => {
    "ansible_facts": {
        "ansible_os_family": "RedHat",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
172.31.0.38 | SUCCESS => {
    "ansible_facts": {
        "ansible_os_family": "RedHat",
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}
172.31.0.48 | SUCCESS => {
    "ansible_facts": {
        "ansible_os_family": "RedHat",
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}
172.31.0.28 | SUCCESS => {
    "ansible_facts": {
        "ansible_os_family": "RedHat",
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}
172.31.0.29 | SUCCESS => {
    "ansible_facts": {
        "ansible_os_family": "Debian",
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false
}

Debug Module

This module can be used to output information, and the output content can be customized through msg. Note: Sometimes the variable after msg needs to be enclosed in ” “

Example: The debug module defaults to output Hello world.

[root@ansible ~]# ansible 172.31.0.18 -m debug
172.31.0.18 | SUCCESS => {
    "msg": "Hello world!"
}
[root@ansible ansible]#cat debug.yml
---
- hosts: websrvs
  tasks:
    - name: output Hello world
      debug:
      
# Defaults to no specified msg, outputs "Hello world!"
[root@ansible ansible]# ansible-playbook debug.yml
PLAY [websrvs]
********************************************************************************
***************************************
TASK [Gathering Facts]
********************************************************************************
*******************************
ok: [172.31.0.7]
ok: [172.31.0.8]
TASK [output variables]
********************************************************************************
******************************
ok: [172.31.0.7] => {
"msg": "Hello world!"
}
ok: [172.31.0.8] => {
"msg": "Hello world!"
}
PLAY RECAP
********************************************************************************
*******************************************
172.31.0.7 : ok=2 changed=0 unreachable=0 failed=0
skipped=0 rescued=0 ignored=0
172.31.0.8 : ok=2 changed=0 unreachable=0 failed=0
skipped=0 rescued=0 ignored=0

Example: Use the debug module to output variables.

[root@centos8 ~]# cat debug.yaml
---
- hosts: websrvs
  tasks:
    - name: output variables
      debug:
        msg: Host "{{ ansible_nodename }}" Ip "{{ ansible_default_ipv4.address }}"

[root@centos8 ~]# ansible-playbook debug.yaml

Example: Show specific character of a string.

[root@centos8 ~]# cat debug.yml
- hosts: all
  gather_facts: no
  vars:
    a: "12345"
  tasks:
  - debug:
      msg: "{{a[2]}}"
      
# Defined a string variable a, if you want to get the 3rd character of a, you can use "a[2]" to retrieve it. The index starts from 0, execute the above playbook, the output of debug will be as follows:

TASK [debug] *************************
ok: [test71] => {
    "msg": "3"
}

Link: https://www.cnblogs.com/xuanlv-0413/p/14811241.html

(Copyright belongs to the original author, please delete if infringed)

Leave a Comment