其他分享
首页 > 其他分享> > Ansible之常见模块

Ansible之常见模块

作者:互联网

虽然模块众多,但最常用的模块也就2,30个而已,针对特定业务只用10几个模块
常用模块帮助文档参考:

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 模块

功能:在远程主机执行命令,此为默认模块,可忽略 -m 选项

注意:此命令不支持 $VARNAME < > | ; &

等,可能用shell模块实现

注意:此模块不具有幂等性

范例:

[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 模块

功能:和command相似,用shell执行命令,支持各种符号,比如:*,$, >

注意:此模块不具有幂等性

范例:

[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

注意:调用bash执行命令 类似 cat /tmp/test.md | awk -F’|’ ‘{print $1,$2}’ &> /tmp/example.txt 这些复杂命令,即使使用shell也可能会失败,解决办法:写到脚本时,copy到远程,执行,再把需要的结果拉回执行命令的机器

范例:将shell模块代替command,设为模块

[root@centos8 ~]# vim /etc/ansible/ansible.cfg
# 修改下面一行
module_name = shell

Script 模块

功能:在远程主机上运行ansible服务器上的脚本(无需执行权限)

注意:此模块不具有幂等性

范例:

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

Copy 模块

功能:从ansible服务器主控端复制文件到远程主机

注意: src=file 如果是没指明路径,则为当前目录或当前目录下的files目录下的file文件

#如目标存在,默认覆盖,此处指定先备份
[root@centos8 ~]# ansible websrvs -m copy -a "src=/root/test1.sh dest=/tmp/test2.sh owner=wang
mode=600 backup=yes"
#指定内容,直接生成目标文件
[root@centos8 ~]# ansible websrvs -m copy -a "content='test line1\ntest line2\n'
dest=/tmp/test.txt"
#复制/etc目录自身,注意/etc/后面没有/
[root@centos8 ~]# ansible websrvs -m copy -a "src=/etc dest=/backup"
#复制/etc/下的文件,不包括/etc/目录自身,注意/etc/后面有/
[root@centos8 ~]# ansible websrvs -m copy -a "src=/etc/ dest=/backup"

Get_url 模块

功能: 用于将文件从http、https或ftp下载到被管理机节点上

常用参数如下:

url: 下载文件的URL,支持HTTP,HTTPS或FTP协议
dest: 下载到目标路径(绝对路径),如果目标是一个目录,就用服务器上面文件的名称,如果目标设置了名
称就用目标设置的名称
owner:指定属主
group:指定属组
mode:指定权限
force: 如果yes,dest不是目录,将每次下载文件,如果内容改变,替换文件。如果否,则只有在目标不存
在时才会下载该文件
checksum: 对目标文件在下载后计算摘要,以确保其完整性
示例: checksum="sha256:D98291AC[...]B6DC7B97",
checksum="sha256:http://example.com/path/sha256sum.txt"
url_username: 用于HTTP基本认证的用户名。 对于允许空密码的站点,此参数可以不使用
`url_password'
url_password: 用于HTTP基本认证的密码。 如果未指定`url_username'参数,则不会使用
`url_password'参数
validate_certs:如果“no”,SSL证书将不会被验证。 适用于自签名证书在私有网站上使用
timeout: URL请求的超时时间,秒为单位

范例:

[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 模块

功能:从远程主机提取文件至ansible的主控端,copy相反,目前不支持目录

范例:

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

范例:

[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 模块

功能:设置文件属性,创建软链接等

范例:

# 创建空文件
[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
}

# 删除空文件
[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"
}

# 授权改所属
[root@centos8 ~]# ansible websrvs -m file -a 'path=/root/test.sh owner=long mode=755'

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

#创建软链接
[root@centos8 ~]# ansible all -m file -a 'src=/data/testfile path|dest|name=/data/testfile-link
state=link'

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

# 递归修改目录及子目录的属性
[root@centos8 ~]# ansible websrvs -m file -a 'path=/data/mysql state=directory owner=mysql group=mysql recurse=yes'

# 递归修改目录属性,但不递归至子目录
[root@centos8 ~]# ansible websrvs -m file -a 'path=/data/mysql state=directory owner=mysql group=mysql'

stat 模块

功能:检查文件或文件系统的状态

注意:对于Windows目标,请改用win_stat模块

选项:

path:文件/对象的完整路径(必须)

常用的返回值判断:

exists: 判断是否存在
isuid: 调用用户的ID与所有者ID是否匹配

范例:

[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
    }
}

案例:

- 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

范例:

[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

范例:执行

[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 模块

功能:解包解压缩

实现有两种用法:

1、将ansible主机上的压缩包传到远程主机后解压缩至特定目录,设置copy=yes,此为默认值,可省略
2、将远程主机上的某个压缩包解压缩到指定路径下,设置copy=no

常见参数:

copy:默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果设置为copy=no,
会在远程主机上寻找src源文件
remote_src:和copy功能一样且互斥,yes表示在远程主机,不在ansible主机,no表示文件在ansible
主机上
src:源路径,可以是ansible主机上的路径,也可以是远程主机(被管理端或者第三方主机)上的路径,如果
是远程主机上的路径,则需要设置copy=no
dest:远程主机上的目标路径
mode:设置解压缩后的文件权限

范例:

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

# 解压本地包cp到目标主机并授权
[root@centos8 ~]# ansible websrvs -m unarchive -a 'src=/tmp/foo.zip dest=/data copy=no mode=0777'

# 使用网络下载zip包拷贝到目标主机
[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 模块

功能:打包压缩保存在被管理节点

范例:

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

Hostname 模块

功能:管理主机名

范例:

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

[root@centos8 ~]# 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 模块

功能:计划任务

支持时间:minute,hour,day,month,weekday

范例:

# 备份数据库脚本
[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

# 创建任务
[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 &>/dev/null' name=Synctime"
 
# 禁用计划任务
[root@centos8 ~]# ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/dev/null' name=Synctime disabled=yes"

# 启用计划任务
[root@centos8 ~]# ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/dev/null' name=Synctime disabled=no"

# 删除任务
[root@centos8 ~]# ansible websrvs -m cron -a "name='backup mysql' state=absent"
[root@centos8 ~]# ansible websrvs -m cron -a 'state=absent name=Synctime'

Yum 和 Apt 模块

功能:

yum 管理软件包,只支持RHEL,CentOS,fedora,不支持Ubuntu其它版本

apt 模块管理 Debian 相关版本的软件包

范例

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

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

# 启用epel源进行安装
[root@centos8 ~]# ansible websrvs -m yum -a 'name=nginx state=present enablerepo=epel' 

#升级除kernel和foo开头以外的所有包
[root@centos8 ~]# ansible websrvs -m yum -a 'name=* state=lastest exclude=kernel*,foo*' 


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

范例:

[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"

范例:

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

# ubuntu apt删除软件
[root@centos8 ~]# ansible websrvs -m apt -a 'name=rsync,psmisc state=absent'

范例:查看包

[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 模块

- 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

范例: 创建和删除仓库

[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 模块

功能:管理服务

范例:

# 启动并设置开机自启
[root@centos8 ~]# ansible websrvs -m service -a 'name=httpd  state=started enabled=yes'

# 停止httpd服务
[root@centos8 ~]# ansible websrvs -m service -a 'name=httpd state=stopped'

# 重启httpd服务
[root@centos8 ~]# ansible websrvs -m service -a 'name=httpd state=reloaded'

# 使用shell模块里的sed命令改端口号
[root@centos8 ~]# ansible websrvs -m shell -a "sed -ri 's/^(Listen )80/\18080/' /etc/httpd/conf/httpd.conf"

# 重启httpd服务使上面的端口号重新更改
[17:42:39 root@centos8 ~]# ansible websrvs -m service -a 'name=httpd state=restarted'

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表示删除用户及家目录等数据,默认remove=no
[root@centos8 ~]# ansible websrvs -m user -a 'name=nginx state=absent remove=yes'

# 生成123456加密的密码
[root@centos8 ~]# ansible localhost -m debug -a "msg={{ '123456' |password_hash('sha512','salt')}}"
localhost | SUCCESS => {
    "msg": "$6$salt$MktMKPZJ6t59GfxcJU20DwcwQzfMvOlHFVZiOVD71w.igcOo1R7vBYR65JquIQ/7siC7VRpmteKvZmfSkNc69."
}

# 使用上面创建的密码创建用户
[root@centos8 ~]# ansible websrvs -m user -a 'name=test password="$6$salt$MktMKPZJ6t59GfxcJU20DwcwQzfMvOlHFVZiOVD71w.igcOo1R7vBYR65JquIQ/7siC7VRpmteKvZmfSkNc69."'

# 创建用户test,并生成4096bit的私钥
[root@centos8 ~]# ansible websrvs -m user -a 'name=test generate_ssh_key=yes ssh_key_bits=4096 ssh_key_file=.ssh/id_rsa'

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
}

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

Lineinfile 模块

ansible在使用sed进行替换时,经常会遇到需要转义的问题,而且ansible在遇到特殊符号进行替换时,
存在问题,无法正常进行替换。其实在ansible自身提供了两个模块:lineinfile模块和replace模块,可以方便的进行替换

一般在ansible当中去修改某个文件的单行进行替换的时候需要使用lineinfile模块

regexp参数 :使用正则表达式匹配对应的行,当替换文本时,如果有多行文本都能被匹配,则只有最后面被匹配到的那行文本才会被替换,当删除文本时,如果有多行文本都能被匹配,这么这些行都会被删除。

如果想进行多行匹配进行替换需要使用replace模块

功能:相当于sed,可以修改文件内容

范例:

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

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

# 删除/etc/fstab文件以#号开头的行 
[root@centos8 ~]# ansible websrvs -m lineinfile -a "dest=/etc/fstab state=absent regexp='^#'"

Replace 模块

该模块有点类似于sed命令,主要也是基于正则进行匹配和替换,建议使用

范例:

# 以UUID开头的行加注释
[root@centos8 ~]# ansible websrvs -m replace -a 'path=/etc/fstab regexp="^(UUID.*)" replace="#\1"'

# 以UUID开头的行去掉注释
[root@centos8 ~]# ansible websrvs -m replace -a "path=/etc/fstab regexp='^#(UUID.*)' replace='\1'"

SELinux 模块

该模块管理 SELInux 策略
范例:

[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 模块

功能:重启目标机器

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

mount 挂载和卸

功能: 挂载和卸载文件系统
范例:

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

#临时取消挂载
[root@centos8 ~]# mount websrvs -m mount -a 'path=/home fstype=xfs opts=noatime state=unmounted'

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

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

Setup 模块

功能: setup 模块来收集主机的系统信息,这些 facts 信息可以直接以变量的形式使用,但是如果主机较多,会影响执行速度

可以使用gather_facts: no 来禁止 Ansible 收集 facts 信息

范例:

[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_processor*"
[root@centos8 ~]# ansible all -m setup -a 'filter=ansible_env'

范例:查询所有目标主机的发行版本信息

[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
}

范例:取某台目标主机的所有IP地址

[root@centos8 ~]# ansible 172.31.0.48 -m setup -a 'filter=ansible_all_ipv4_addresses'
172.31.0.48 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "172.31.0.48",
            "192.168.0.104"
        ],
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}

范例:取某台目标主机的默认IP

[root@centos8 ~]# ansible 172.31.0.17 -m setup -a 'filter=ansible_default_ipv4'
172.31.0.17 | SUCCESS => {
    "ansible_facts": {
        "ansible_default_ipv4": {
            "address": "172.31.0.17",
            "alias": "eth0",
            "broadcast": "172.31.255.255",
            "gateway": "172.31.0.254",
            "interface": "eth0",
            "macaddress": "00:0c:29:51:72:d9",
            "mtu": 1500,
            "netmask": "255.255.0.0",
            "network": "172.31.0.0",
            "type": "ether"
        },
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}

debug 模块

此模块可以用于输出信息,并且通过 msg 定制输出的信息内容
注意: msg后面的变量有时需要加 " " 引起来

范例: debug 模块默认输出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:
      
# 默认没有指定msg,默认输出"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

范例: 利用debug 模块输出变量

[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

范例: 显示字符串特定字符

[root@centos8 ~]# cat debug.yml
- hosts: all
  gather_facts: no
  vars:
    a: "12345"
  tasks:
  - debug:
      msg: "{{a[2]}}"
      
# 定义了一个字符串变量a,如果想要获取a字符串的第3个字符,则可以使用”a[2]”获取,索引从0开始,执行
上例playbook,debug的输出信息如下:

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

标签:name,websrvs,常见,ansible,Ansible,模块,172.31,root,centos8
来源: https://blog.csdn.net/qq_38419276/article/details/117266101