ansible-doc -l查看ansible当前可使用的模块
查看某一个模块的具体使用方法:
ansible-doc -s module_name
example:
ansible-doc -s user ##查看user模块使用帮助
以下将介绍几个常用模块:
一、user模块
user模块是一个用户管理的模块,使用ansible-doc -s user查看此模块帮助
1.创建用户
创建一个用户名为ansibletest的用户:
ansible all -m user -a "name=ansibletest state=present"

上图信息中的state=present为用户状态,system是否为系统用户
创建系统用户:
ansible all -m user -a "name=ansbileetest state=present system=yes"
2.删除用户
删除用户则使用state=absent:
ansible all -m user -a "name=ansibletest state=absent" ###只是state改变
二、group模块
基本上和user模块差不多,这里不再赘述:
ansible-doc -s group
三、cron模块
1.添加crond定时任务
下面的例子是添加一个时间同步,每十分钟执行一次的crond定时任务:
ansible all -m cron -a 'name="sync time from ntpserver" minute="*/10" job="/sbin/ntpdate cn.pool.ntp.org &>/dev/null state=present"'
# name为注释,job为添加到crontab的任务,minite为分钟选项,state=present可以不写,默认选项
注意ntpd服务必须停止才能使用ntpdate,因为ntpd(debian系为ntp)是ntp服务端守护进程,而ntpdate是客户端,同一台服务器不能同一时间充当服务端和客户端,必须先停止一个,如果ntpd没有停止,使用ntpdate同步时间则会报如下错误:
ntpdate[23668]: the NTP socket is in use, exiting
2.删除crond定时任务
删除则把state=present改成state=absent,并且只需要指定name即可:
ansible all -m cron -a 'name="sync time from ntpserver" state=absent"'
四、copy模块
示例:把fstab复制到/tmp目录下,并且权限为600
ansible all -m copy -a 'src=/etc/fstab dest=/tmp/fstab.tmp mode=600'
五、file模块
创建文件或者目录的模块
state表示文件类型,可以是一般文件(file)、目录文件(directory)、链接文件(link),删除文件则用absent
创建/tmp/testdir目录:
ansible all -m file -a 'path=/tmp/testdir state=directory'
创建链接文件:
ansible all -m file -a 'path=/tmp/fstab.symlink state=link src=/tmp/fstab.tmp'
#src指定原文件,如果原文件不存在,则使用force=yes强制创建,只是链接文件会失效
删除,同样,也只需要指定path即可:
ansible all -m file -a 'path=/tmp/fstab.symlink state=absent force=yes'
#force=yes表示强制删除
六、ping模块
无参数,检测主机是否在线
ansible all -m ping
七、yum模块
基于yum源安装或者卸载程序
yum只能针对有yum命令的主机执行,比如redhat、centos系列,debian系列可使用apt模块
给websrvs组的主机安装nginx:
ansible websrvs -m yum -a 'name=nginx state=latest'
#state=latest指定最新版,默认也是如此
##如果要卸载则state=absent即可
八、service模块
管理服务的模块(停止|启动|开机自启动)
启动nginx服务,并且设置开机自启动:
ansible all -m service -a 'name=nginx state=started enabled=yes'
九、shell模块
指定一个shell程序运行命令
因为commnad模块无法使用管道(使用了也无效),因此使用command模块修改用户密码(echo passwd|passwd --stdin user)是不可行的,这个echo只会在主机本地echo
会被解析成echo 'passwd|passwd --stdin user',因此用到shell模块,把它封装到一个子进程中传递
shell可以不用接选项,直接执行命令即可:
ansible all -m shell -a 'echo 123456|passwd stdin user'
十、script模块
把本地脚本传到远程主机上运行
把本地主机上的test.sh拷贝到远程主机上执行:
ansible all -m script -a '/tmp/test.sh'
十一、setup模块
报告主机信息:IP地址|CPU物理核心数|内存大小|PATH变量|硬盘分区|内核版本|平台架构等等等,并把这些变量保存到ansible变量中
ansible all -m setup

