模块包括 command
,script
,shell
,都可以实现远程命令运行
command
:为 ansible 的默认模块(-m
选项),可以远程执行命令[root@localhost ~]$ ansible 192.168.159.131 -m command -a "free -m"
192.168.159.131 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 972 162 696 7 113 679
Swap: 2047 0 2047
script
:在远程主机执行主控端存放的shell脚本[root@localhost ~]$ ansible 192.168.159.131 -m script -a "~/test.sh"
192.168.159.131 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.159.131 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.159.131 closed."
],
"stdout": "Hello World\r\n",
"stdout_lines": [
"Hello World"
]
}
shell
:执行远程主机上的可执行文件[root@localhost ~]$ ansible 192.168.159.131 -m shell -a "~/test.sh"
192.168.159.131 | CHANGED | rc=0 >>
Hello World
模块包括 yum
(CentOS),apt
(Ubuntu),实现软件包管理操作。在 ansible 经常会使用 state
变量来表示这个模块的运行模式:
state | 说明 |
---|---|
present | 安装 |
lastest | 不存在则安装,存在则检查更新,保证软件是最新版本的 |
absent | 卸载 |
yum
模块安装 wget
ansible 192.168.159.131 -m yum -a "name=wget state=present"
ansible all -m yum -a "name=* state=latest"
yum
模块安装包组ansible 192.168.159.131 -m yum -a "name'@Development Tools' state=present"
service
:用于管理远程主机的系统服务,服务运行模式(状态)有:
state | 说明 |
---|---|
started | 启动服务,“已开启的状态” |
stopped | 停止服务,“已停止的状态” |
restarted | 重启服务 |
reloaded | 重新加载服务 |
ansible 192.168.159.131 -m service -a "name=httpd state=restarted"
ansible webservers -m service -a "name=httpd state=stopped"
setup
:用于采集系统的信息,一般用于自定义模块中获取信息处理
file
:创建、删除远程主机上的文件目录等
ansible webservers -m file -a "path=/tmp/test state=directory"
ansible webservers -m file -a "path=/tmp/test state=touch"
ansible webservers -m file -a "path=/tmp/test state=link"
ansible webservers -m file -a "path=/tmp/test state=absent"
copy
:实现主控端向目标主机拷贝文件,用 src
表示主控端文件,dest
表示要在目标主机上存放文件的位置
ansible webservers -m copy -a "src=/tmp/test dest=/tmp/ owner=root group=root mode=0755"
iptables
:管理目标主机的防火墙
ansible webservers -m iptables -a "action=append chain=INPUT protocol=tcp destination_port=80 jump=ACCEPT state=present"
lineinfile
:用于替换文件内容,可以基于正则e
ansible webservers -m lineinfile -a "dest=/etc/selinux/config regexp='^SELINUX' line='SELINUX=disable'"
user
:用于远程主机用户的管理
# 先将密码加密
echo 123 | openssl passwd -1 -stdin
$1$xQIniiJR$GKYo4GPd/IbC4rhUPjhpr.
# 使用加密后的密码创建用户
ansible webservers -m user -a "name=alice password=$1$xQIniiJR$GKYo4GPd/IbC4rhUPjhpr."
ansible webservers -m user -a "name=bob state=absent remove=yse"
synchronize
:增量备份(不会用)
ansible webservers -m synchronize -a "src=dest="
# 压缩
ansible webservers -m synchronize -a "compress=yes src=dest="
stat
:获取远程文件的状态信息,包括atime、ctime、mtime、md5、uid、gid 等信息
ansible webservers -m stat -a "path=/etc/sysctl.conf"
get_url
:实现远程主机下载执行URL到本地,支持sha256sum文件校验
ansible webservers -m get_url -a "url=http://xxx.jpg dest=/root/ mode=0755 force=yes"
cron
:远程主机 crontab 配置(计划任务、定时任务)
ansible webservers -m cron -a "name='do something' hour=5,2 job='ls -alh > /dev/null‘“
mount
:管理远程主机分区挂载
ansible webservers -m mount -a "name=/mnt/data src=/dev/sd0 fstype=ext4 opts=ro state=present"