Ansible提供了非常丰富的模块,涉及到日常运维工作的方方面面,可以使用ansible-doc查看模块更多帮助

例:ansible-doc -s cron

下面介绍Ansible的常用模块

1、远程命令模块

模块包括command、script、shell,都可以实现远程shell命令运行。

command 是Ansible的默认模块,可以运行远程权限范围内的所有shell命令

ansible webservers -m command -a "free -m"

script 是在远程主机执行主控端存储的shell脚本文件,相当于scp+shell组合

ansible webservers -m script -a "/home/test.sh"

shell 是执行远程主机的shell脚本文件

ansible webservers -m shell -a "/home/test.sh"

 

2、copy模块

实现主控端向目标主机拷贝文件,类似scp

ansible webservers -m copy -a "src=/home/test.sh dest=/tmp/ owner=root group=root mode=0755"

上面例子实现拷贝 /home/test.sh 文件到webservers组下各主机的 /tmp/ 目录下 ,并更新文件属组及权限

也可以单独使用file模块实现权限修改

ansible webservers -m file -a "path=/tmp/test.sh owner=root group=root mode=0755"

 

3、stat模块

获取远程文件状态信息,包括atime、ctime、mtime、md5、uid、gid等等

ansible webservers -m stat -a "path=/tmp/test.sh"

 

4、get_url模块

实现在远程主机下载指定URL到本地(支持sha256sum文件校验)

ansible webservers -m get_url -a "url=http://wwww.baidu.com dest=/tmp/index.html mode=0440 force=yes"

 

5、yum模块

软件包管理操作,常见有yum、apt(pkg和name是要安装的包名)

ansible webservers -m yum -a "pkg=curl state=latest"
ansible webservers -m apt -a "name=curl state=latest"

 

6、cron模块

远程主机crontab配置

day    #日(1-31,*),hour:小时(0-23,*),minute:分钟(0-59,*),month:月(1-12,*),weekday:周(0-7,*)

backup  #对远程主机上的原任务计划内容修改之前做备份

cron_file  #如果指定该选项,则用该文件替换远程主机上的cron.d目录下的用户的任务计划

job  #要执行的任务,依赖于state=present

name  #该任务的描述

special_time  #指定什么时候执行,参数:reboot,yearly,annually,monthly,weekly,daily,hourly

state  #确认该任务计划是创建还是删除

user  #以哪个用户的身份执行

例:每分钟把date命令内容输入到/tmp/test.txt中

ansible webservers -m cron -a "backup=yes minute=*/1 name='test_time' job='date >> /tmp/test.txt'"

查看crontab任务表:ansible webservers -m command -a 'crontab -l'

192.168.190.133 | SUCCESS | rc=0 >>
#Ansible: test_time
*/1 * * * * date >> /tmp/test.txt

192.168.190.131 | SUCCESS | rc=0 >>
#Ansible: test_time
*/1 * * * * date >> /tmp/test.txt

cron删除计划任务,只需指定cron的名字以及state=absent

ansible webservers -m cron -a "name='test_time' state=absent"

 

 7、mount模块

远程主机分区挂载  

fstype    #挂载文件的类型 ,必选
name    #挂载点 ,必选
opts    #传递给mount命令的参数
src    #要挂载的文件 ,必选项
state    #必选项 
    present    #只处理fstab中的配置 
    absent    #删除挂载点 
    mounted    #自动创建挂载点并挂载之 
    umounted    #卸载

创建

ansible webservers -m mount -a "name=/mnt/data src=/dev/sd0 fstype=ext3 opts=ro state=present"

删除

ansible webservers -m mount -a "name=/mnt/data state=absent"

 

8、service模块

系统服务管理

state(started/stopped/restarted/reloaded)

ansible webservers -m service -a "name=nginx state=started"

 

9、user服务模块

远程主机系统用户管理

home    #指定用户的家目录,需要与createhome配合使用
groups    #指定用户的属组
uid    #指定用户的uid
password    #指定用户的密码
name    #指定用户名
createhome    #是否创建家目录 yes|no
system    #是否为系统用户
remove    #当state=absent时,remove=yes则表示连同家目录一起删除,等价于userdel -r
state    #是创建还是删除
shell    #指定用户的shell环境

创建

 

ansible webservers -m user -a "name=zhangsan"

删除

ansible webservers -m user -a "name=zhangsan state=absent remove=yes"

 

group同理