一、命令模块
1、Command模块
[root@kafka-node01 ansible]# ansible web01 -m command -a "free -m"
192.168.1.21 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 7721 891 5906 23 923 6560
Swap: 8043 0 8043
# 不支持特殊字符
[root@kafka-node01 ansible]# ansible web01 -m command -a "ifconfig enp3s0 | awk 'NR==2 {print \$2}'"
192.168.1.21 | FAILED | rc=1 >>
|: 未知的主机
ifconfig: `--help' gives usage information.non-zero return code
2、Shell模块
[root@kafka-node01 ansible]# ansible web01 -m shell -a "free -h"
192.168.1.21 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 7.5Gi 892Mi 5.8Gi 23Mi 924Mi 6.4Gi
Swap: 7.9Gi 0B 7.9Gi
# 支持特殊字符
[root@kafka-node01 ansible]# ansible web01 -m shell -a "ifconfig enp3s0 | awk 'NR==2 {print \$2}'"
192.168.1.21 | CHANGED | rc=0 >>
00:0c:29:b4:f3:e2
2、scripts模块
# 远程执行脚本
[root@kafka-node01 ansible]# ansible web01 -m script -a "mkdir.sh"
192.168.1.21 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.1.21 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.1.21 closed."
],
"stdout": "",
"stdout_lines": []
}
二、软件管理模块
1、 yum模块
[root@m01 ~]# ansible-doc yum
EXAMPLES: # 搜EXAMP可以看到示例
- name: install the latest version of Apache
yum:
name: httpd
state: latest # 如果是lastest就不用指定包的版本,默认就安装到最新
name可以是
要安装的软件包名可以带版本httpd-2.4.6
一个本地rpm包路径
一个rpm包的url地址
state:
latest #确保是安装过的,并且是最新版本,无论有无都会更新至最新版
absent #确保没有安装,即卸载
present #确保是安装过的,有则不更新,无则安装最新
# 直接yum 安装服务httpd 相当于在远程主机执行yum install httpd -y
[root@kafka-node01 ~]# ansible 192.168.1.21 -m yum -a "name=httpd state=present" -vv
#安装本地的rpm包(包一定先传到远程机器上,注意是传到远程主机上)
wget https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-release-4.0-2.el7.noarch.rpm,然后传到远程主机的/tmp目录下
[root@kafka-node01 ~]# ansible 192.168.71.13 -m yum -a 'name=/tmp/zabbix-release-4.0-2.el7.noarch.rpm state=present disable_gpg_check=yes' # 末尾加上disable_gpg_check=yes,否则会报错Failed to validate GPG
相当于在远程机器上执行:yum localinstall -y /tmp/zabbix-release-4.0-2.el7.noarch.rpm
#安装云上的服务
[root@kafka-node01 ~]# ansible web_group -m yum -a 'name=https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-release-4.0-2.el7.noarch.rpm state=present disable_gpg_check=yes' # 如果报错,请将https换成http协议
相当于在远程机器上执行:yum install -y url地址
#卸载服务包
[root@kafka-node01 ~]# ansible web_group -m yum -a 'name=zabbix* state=absent' # 相当于yum remove zabbix* -y
2、yum_repository模块
3、package通用包管理
跨平台包操作(自动识别 yum/apt/dnf 等)
[root@kafka-node01 ~]# ansible 192.168.1.25 -m package -a "name=httpd state=latest"
4、apt模块(debian/Ubuntu)
特殊功能:
- 更新缓存:
<font style="color:rgb(251, 71, 135);">update_cache: yes</font>
- 固定版本:
<font style="color:rgb(251, 71, 135);">force: yes</font>
- name: Install nginx with specific version
apt:
name: nginx=1.18.0-0ubuntu1
state: present
三、文件管理模块
1、copy模块
本地文件,上传到远程主机
[root@m01 ~]# ansible-doc copy
EXAMPLES:
- name: Copy file with owner and permissions
copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: '0644'
backup: yes
content: '# This file was moved to /etc/other.conf'
follow: yes
src #文件的源地址
dest #目标地址或文件
owner #文da件属主
group #文件属组
mode #文件的权限
backup #替换的文件是否备份
content #直接将内容写入文件
follow #处理软连接
# 推送文件到远程主机
[root@kafka-node01 ~]# ansible web01 -m copy -a "src=my.cnf dest=/root"
# 推送文件到远程主机并授权
[root@kafka-node01 ~]# ansible web01 -m copy -a "src=my.cnf dest=/root mode=600"
# 推送文件到远程主机,并授权属主属组
[root@kafka-node01 ~]# ansible web01 -m copy -a "src=my.cnf dest=/root owner=dujie group=dujie"
#推送文件并备份: 目标主机若存在该文本并且内容与源传过来的不一致,则将目标主机的该文件备份
[root@kafka-node01 ~]# ansible web01 -m copy -a "src=my.cnf dest=/root owner=dujie group=dujie backup=yes"
[root@kafka-node02 ~]# ll /root/my.cnf*
-rw------- 1 dujie dujie 3698 5月 31 20:46 /root/my.cnf
-rw------- 1 dujie dujie 3724 5月 31 20:46 /root/my.cnf.15237.2025-05-31@20:46:51~
# 直接将内容写入文件
[root@kafka-node01 ~]# ansible web01 -m copy -a "content=11111 dest=/root/niubi.txt"
2、file模块
在目标主机上进行文件操作
1.1 语法:
[root@m01 ~]# ansible-doc file
EXAMPLES:
- name: Change file ownership, group and permissions
file:
src: /file/to/link/to
path: /etc/foo.conf
owner: foo
group: foo
mode: '0644'
state: link
recurse: yes
path #创建的文件或目录的地址
owner #文件或目录的属主
group #文件或目录的属组
mode #文件或目录的权限
state
link #创建软链接
src #源文件
dest #软链接的名字
touch #创建文件
directory #创建目录
absent #删除,目录,文件,软链接
recurse #递归授权
1.2 示例
目录操作
# 在目标主机创建目录
[root@kafka-node01 ~]# ansible web01 -m file -a "path=/code state=directory"
#相当于在远程机器上执行:mkdir /code && chown www.www /code
[root@kafka-node01 ~]# ansible web01 -m file -a "path=/code state=directory owner=www group=www"
#递归创建目录,不需要加任何参数
[root@kafka-node01 ~]# ansible web01 -m file -a 'path=/code/wordpress/wp-content/pic state=directory'
#递归授权目录,需要加recurse=yes
[root@kafka-node01 ~]# ansible web01 -m file -a 'path=/code/ state=directory owner=www group=www recurse=yes'
文件操作
#创建文件
[root@kafka-node01 ~]# ansible web01 -m file -a 'path=/tmp/1.txt state=touch'
#创建文件并授权
[root@kafka-node01 ~]# ansible web01 -m file -a 'path=/tmp/1.txt state=touch owner=nginx group=nginx'
创建软连接(源文件/目录必须存在)
[root@m01 ~]# ansible web01 -m file -a 'src=/tmp/aaa dest=/tmp/bbb state=link'
[root@m01 ~]# ansible web01 -m file -a 'src=/tmp/1.txt dest=/tmp/1.ln state=link'
3、get_url模块
语法:
[root@m01 ~]# ansible-doc get_url
EXAMPLES:
- name: Download foo.conf
get_url:
url: http://example.com/path/file.conf
dest: /etc/foo.conf
mode: '0440'
checksum: sha256:b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c
url #文件下载地址
dest #文件存放路径
mode #文件下载后授权
checksum #验证文件
sha256 #加密方式
示例:
#下载网站上的文件
[root@m01 ~]# ansible web01 -m get_url -a 'url=http://10.0.0.7/1.txt dest=/tmp'
#下载时验证文件
[root@m01 ~]# ansible web01 -m get_url -a 'url=https://www.test.com/static/img/xingganheguan.gif dest=/tmp checksum=md5:8732bc18d78503fe4879fee530115a4e' # md5值与文件对不上,会报错
四、Ansible服务管理模块
4.1 service
[root@m01 ~]# ansible-doc service
EXAMPLES:
- name: Start service httpd, if not started
service:
name: httpd
state: started
name: nginx #服务名字
state:
started #启动服务
stopped #停止服务
restarted #重启服务
reloaded #重载服务
enabled: yes #开机自启
4.2 systemd
语法
[root@m01 ~]# ansible-doc systemd
EXAMPLES:
- name: Make sure a service is running
systemd:
state: started
name: httpd
name: nginx #服务名字
state:
started #启动服务
stopped #停止服务
restarted #重启服务
reloaded #重载服务
enabled: yes #开机自启
示例
#关闭服务
[root@m01 ~]# ansible web01 -m systemd -a 'name=nginx state=stopped'
#启动服务
[root@m01 ~]# ansible web01 -m systemd -a 'name=nginx state=started'
五、用户管理模块
1、group模块
语法
[root@m01 ~]# ansible-doc group
EXAMPLES:
- name: Ensure group "somegroup" exists
group:
name: somegroup #组名字
state:
present #创建组
absent #删除组
gid: 666 #指定组id
示例
#创建用户组,查看cat /etc/group |grep www
[root@m01 ~]# ansible web01 -m group -a 'name=www gid=666 state=present'
#删除用户组
[root@m01 ~]# ansible web01 -m group -a 'name=www gid=666 state=absent'
2、user模块
语法
[root@m01 ~]# ansible-doc user
EXAMPLES:
- name: Add the user 'johnd' with a specific uid and a primary group of 'admin'
user:
name: johnd
comment: John Doe
uid: 1040
group: admin
shell: /bin/bash
state: absent
remove: yes
create_home: false
name #用户名字
comment #用户备注
uid #用户id
group #用户所在的组名字
shell
/bin/bash #用户可以登录
/sbin/nologin #用户不需要登录
state
absent #删除用户
present #创建用户
remove #移除家目录
create_home #是否创建家目录
true #创建家目录
false #不创建家目录
示例
#创建用户,指定组(组必须存在否则报错),不需要登录,有家目录,
[root@m01 ~]# ansible web01 -m user -a 'name=www uid=666 group=www shell=/sbin/nologin create_home=true'
#删除用户并移除家目录
[root@m01 ~]# ansible web01 -m user -a 'name=www state=absent remove=yes'
#注意:
1.当组的名字与用户名字相同时,删除用户组也会被删除
2.当组的名字与用户名字相同时,而组下面还有其他用户,则删除用户时不会删除同名组
六、其他模块
1、cron定时任务模块
语法
[root@m01 ~]# ansible-doc cron
EXAMPLES:
- name: Ensure a job that runs at 2 and 5 exists. Creates an entry like "0 5,2 * * ls -alh > /dev/null"
cron:
name: "check dirs"
minute: "0"
hour: "5,2"
day: "*"
month: "*"
weekday: "*"
job: "ls -alh > /dev/null"
state: absent
disabled: yes
name #定时任务的备注
minute #分钟
hour #小时
day #日
month #月
weekday #周
job #指定的定时任务内容
state
present #新建定时任务
absent #删除定时任务
disabled
yes #注释定时任务
no #取消注释
示例
#添加定时任务,每五分钟执行一次时间同步(只配置分钟,其他不配置默认是 * )
[root@m01 ~]# ansible web01 -m cron -a 'name="测试ansible配置定时任务" minute=*/5 job="ntpdate time1.aliyun.com"'
#查看配置
[root@web01 html]# crontab -l
#Ansible: 测试ansible配置定时任务
*/5 * * * * ntpdate time1.aliyun.com
#注释定时任务
[root@m01 ~]# ansible web01 -m cron -a 'name="测试ansible配置定时任务" minute=*/5 job="ntpdate time1.aliyun.com" disabled=yes'
#删除定时任务
[root@m01 ~]# ansible web01 -m cron -a 'name="测试ansible配置定时任务" minute=*/5 job="ntpdate time1.aliyun.com" state=absent'
#注意:
1.定时任务添加,是通过名字来区分是否一样的,如果不加name参数,则会添加重复的定时任务
2.定时任务注释是通过 name 参数来注释的,所以一定要加 name 参数
3.定时任务删除是通过 name 参数来删除的,所以一定要加 name 参数
2、mount挂载模块
2.1 安装nfs
1.安装nfs
[root@m01 ~]# ansible nfs_server -m yum -a 'name=nfs-utils state=present'
2.配置nfs
[root@m01 ~]# ansible nfs_server -m copy -a 'content="/data 192.168.71.0/24(rw,sync,all_squash)" dest=/etc/exports'
3.创建目录
[root@m01 ~]# ansible nfs_server -m file -a 'path=/data state=directory owner=nfsnobody group=nfsnobody'
4.启动服务
[root@m01 ~]# ansible nfs_server -m systemd -a 'name=nfs-server state=started'
2.1.2 挂载模块语法和参数
[root@m01 ~]# ansible-doc mount
EXAMPLES:
- name: Mount DVD read-only
mount:
path: /mnt/dvd
src: /dev/sr0
fstype: iso9660
opts: ro,noauto
state: present
path #本机准备挂载的目录
src #远端挂载点
fstype #指定挂载类型
opts #挂载参数(/etc/fstab中的内容)
state
present #配置开机挂载,将配置写入自动挂载文件,并没有直接挂载
unmounted #取消挂载,但是没有删除自动挂载配置
#常用配置
mounted #配置开机挂载,并且直接挂载上
absent #取消挂载,并且删除自动挂载配置
实例
注意:
1、针对ansible挂载nfs报错:The module mount was redirected to ansible.posix.mount, which could not be loaded
[root@lb ~]# ansible-doc -l|grep mount
[root@lb ~]# ansible-galaxy collection install ansible.posix
[root@lb ~]# ansible-doc -l|grep mount
ansible.posix.mount Control active and configured mount …
2、要挂载nfs,目标节点也必须安装有nfs才可以支持nfs文件系统ansible web01 -m yum -a ‘name=nfs-utils state=present’
#配置开机挂载,将配置写入自动挂载文件,并没有直接挂载,可以去目标主机查看/etc/fstab
[root@m01 ~]# ansible web01 -m mount -a 'path=/data src=192.168.71.16:/data fstype=nfs opts=defaults state=present'
#配置开机挂载,并且直接挂载上
[root@m01 ~]# ansible web01 -m mount -a 'path=/data src=192.168.71.16:/data fstype=nfs opts=defaults state=mounted'
#取消挂载,但是没有删除自动挂载配置
[root@m01 ~]# ansible web01 -m mount -a 'path=/data src=192.168.71.16:/data fstype=nfs opts=defaults state=unmounted'
#取消挂载,并且删除自动挂载配置,可以去目标主机查看/etc/fstab
[root@m01 ~]# ansible web01 -m mount -a 'path=/data src=192.168.71.16:/data fstype=nfs opts=defaults state=absent'
3、selinux模块
- name: Disable SELinux
selinux:
state: disabled
#关闭selinux
[root@m01 ~]# ansible web02 -m selinux -a 'state=disabled'
web02 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"configfile": "/etc/selinux/config",
"msg": "",
"policy": "targeted",
"reboot_required": false,
"state": "disabled"
}
4 、firewalld模块
[root@m01 ~]# ansible-doc firewalld
EXAMPLES:
- firewalld:
service: https #指定服务
permanent: #是否永久生效
yes #永久生效
no #临时生效
state:
enabled #允许通过
port:
8081/tcp #指定端口
zone: dmz #指定区域
rich_rule: rule service name="ftp" audit limit value="1/m" accept #配置富规则
source: 192.0.2.0/24 #指定网段
interface: eth2 #帮定网卡
masquerade: yes #开启IP伪装
示例
#允许访问http服务,永久生效
[root@m01 ~]# ansible web01 -m firewalld -a 'service=http permanent=yes state=enabled'
[root@m01 ~]# ansible web01 -m firewalld -a 'service=http state=enabled'
#允许访问80端口,临时生效
[root@m01 ~]# ansible web01 -m firewalld -a 'port=80/tcp state=enabled'
#配置允许10.0.0.0网段访问22端口
[root@m01 ~]# ansible web01 -m firewalld -a 'rich_rule="rule family=ipv4 source address=10.0.0.0/24 port port=22 protocol=tcp accept" state=enabled'
#配置网段白名单
[root@m01 ~]# ansible web01 -m firewalld -a 'source=10.0.0.0/24 zone=trusted state=enabled permanent=yes'
[root@m01 ~]# ansible web01 -m firewalld -a 'source=10.0.0.0/24 zone=trusted state=enabled permanent=no'
5、unarchive解压模块
[root@m01 ~]# ansible-doc unarchive
EXAMPLES:
- name: Extract foo.tgz into /var/lib/foo
unarchive:
src: foo.tgz
dest: /var/lib/foo
remote_src: no #默认是no
src #包的路径
dest #解压后的目标路径
remote_src
yes #包在受控端服务器上
no #包在控制端服务器上
示例
#解压包到受控端,包在控制端上
[root@m01 ~]# ansible web01 -m unarchive -a 'src=/root/php.tar.gz dest=/tmp'
:
#在受控端解压包,包在受控端
[root@m01 ~]# ansible web01 -m unarchive -a 'src=/tmp/php.tar.gz dest=/tmp remote_src=yes'
6、archive压缩模块
[root@m01 ~]# ansible-doc archive
EXAMPLES:
- name: Compress directory /path/to/foo/ into /path/to/foo.tgz
archive:
path: /path/to/foo #要打包的内容
dest: /path/to/foo.tgz #打好的包与存放位置
format:gz #打包的类型 bz2, gz, tar, xz, zip
#打包实例
[root@m01 ~]# ansible web01 -m archive -a 'path=/tmp dest=/opt/php.tar.gz'
#报错
192.168.71.14 | FAILED! => {
"msg": "The module archive was redirected to community.general.archive, which could not be loaded."
}
报错,需要安装(Ansible 2.10版本开始,一些核心模块被移动到了对应的Ansible Collection中去,所以你需要确保对应的 Ansible Collection 已经安装在你的系统中)
ansible-galaxy collection install community.general
安装后重新执行即可
7、set模块
Ansible 的 setup
模块是一个内置模块,用于收集远程主机的详细系统信息。
setup
模块收集的系统信息被称为 “facts”(事实)。这些信息包括但不限于以下内容:
- 操作系统类型、版本和内核信息
- 主机名和网络信息
- 磁盘和内存使用情况
- 用户和组信息
- 硬件架构和处理器信息
- 环境变量
- 时间和时区信息
这个模块通常在 Ansible playbooks 开始时自动运行,但也可以显式地调用它来获取和使用远程主机的变量信息。
在 Ansible 中,setup
模块和 playbook剧本中的每个play的gather_facts
配置选项是密切相关的
1、setup
模块是实际执行收集系统信息(facts)任务的模块。它收集的信息包括操作系统类型、版本、网络接口、硬件信息等。
2、gather_facts
是一个 play 级别的选项,控制是否在 play 开始时自动调用 setup
模块。默认情况下,gather_facts
为 true
,即 Ansible 会自动调用 setup
模块。这也是为何你执行ansible批量任务时,每个play的开头都会执行一次Gathering Facts的原因
[root@m01 /workspace]# ansible-playbook web_group.yaml
PLAY [web_group] **************************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************************
ok: [web02]
ok: [web01]
TASK [Gather OS version] ******************************************************************************************************************************
changed: [web02]
changed: [web01]
。。。。。。
正因每个play开始执行前会默认先执行Gathering Facts,所以我们才可以在剧本中直接引用这些facts
[root@m01 /workspace]# cat test.yaml # ansible_fqdn与主机名一样
- hosts: nfs_server
tasks:
- name: Copy files to remote locations
copy:
dest: "/tmp/test.txt"
content: "{{ ansible_fqdn }} {{ ansible_memory_mb.swap.total }}"
3、如果你将 gather_facts
设置为 false(主机规模大的情况设置为false可以提速)
,你可以通过手动调用 setup
模块来收集所需的系统信息。
- name: Skip gathering facts example
hosts: all
gather_facts: false # 设置为false
tasks:
- name: Print a message
debug:
msg: "Facts gathering is disabled."
下面就来演示下手动执行setup模块的效果
#1.获取web01主机所有信息
[root@m01 ~]# ansible web01 -m setup
#2.获取主机IP
[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_default_ipv4'
#3.获取主机名
[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_fqdn'
web01 | SUCCESS => {
"ansible_facts": {
"ansible_fqdn": "www.baidu.com",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
#4.获取内存信息
[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_memory_mb'
web01 | SUCCESS => {
"ansible_facts": {
"ansible_memory_mb": {
"nocache": {
"free": 720,
"used": 252
},
"real": {
"free": 276,
"total": 972,
"used": 696
},
"swap": {
"cached": 0,
"free": 1023,
"total": 1023,
"used": 0
}
},
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
#5.常用参数
ansible_all_ipv4_addresses:仅显示ipv4的信息。
ansible_devices:仅显示磁盘设备信息。
ansible_distribution:显示是什么系统,例:centos,suse等。
ansible_distribution_major_version:显示是系统主版本。
ansible_distribution_version:仅显示系统版本。
ansible_machine:显示系统类型,例:32位,还是64位。
ansible_eth0:仅显示eth0的信息。
ansible_hostname:仅显示主机名(不准确)
ansible_fqdn:仅显示主机名。
ansible_kernel:仅显示内核版本。
ansible_lvm:显示lvm相关信息。
ansible_memtotal_mb:显示系统总内存。
ansible_memfree_mb:显示可用系统内存。
ansible_memory_mb:详细显示内存情况。
ansible_swaptotal_mb:显示总的swap内存。
ansible_swapfree_mb:显示swap内存的可用内存。
ansible_mounts:显示系统磁盘挂载情况。
ansible_processor:显示cpu个数(具体显示每个cpu的型号)。
ansible_processor_vcpus:显示cpu个数(只显示总的个数)。