Ansible匹配目标和常用模块
匹配目标目标匹配格式如下:
ansible <pattrern_goes_here>-m <module_name>-a <arguments>
<pattern_goes_here>参数使用方法
常用模块的使用
1、远程模块命令(command、script、shell)
模块包括command、script、shell都可以实现shell命令运行。command作为Ansible的默认模块,可以运行远程范围所有的shell命令;script功能是远程主机执行主控端存储的shell脚本文件,相当于scp+shell的组合,shell功能是执行远程主机的shell脚本文件
# ansible webservers -m command -a 'hostname'
# ansible webservers -m script -a '/data/shell/test.sh' /data/shell/test.sh 脚本在主控端
# ansible webservers -m shell -a '/data/shell/test.sh' /data/shell/test.sh 脚本在被管端
2、copy模块
实现主控端向目标拷贝文件,类似与scp的功能
实现拷贝/home/test.txt文件至webservers组目标主机/tmp目录下,并更新文件属主及权限
# ansible webservers -m copy -a 'src=/home/test.txt dest=/tmp/ owner=root group=root mode=0644'
3、stat模块
获取远程文件状态信息,包括atme、ctime、md5、uid、gid等信息
# ansible webservers -m stat -a 'path=/tmp/test.txt'
4、get_url模块
实现远程主机下载指定URL到本地,支持sha256sum文件校验
# ansible webservers -m get_url -a 'url=http://www.baidu.com dest=/tmp/index.html'
5、yum模块
# ansible webservers -m yum -a 'name=httpd state=latest'
6、cron模块
# ansible webservers -m cron -a'name="ntpdate by heboan" minute=*/3 hour=* day=* month=* weekday=* job="/usr/sbin/ntpdate s1a.time.edu.cn"'
效果:
# crontab -l
#Ansible: ntpdate by heboan
*/3 * * * * /usr/sbin/ntpdate s1a.time.edu.cn
7、mount模块
远程主机分区挂载
# ansible -m mount -a "/mnt/data src=/dev/sd0 fstype=ext3 opts=ro state=present"
8、service模块
远程主机系统服务管理
# ansible webservers -m service -a "name=nginx state=stopped"
# ansible webservers -m service -a "name=nginx state=started"
# ansible webservers -m service -a "name=nginx state=restarted"
# ansible webservers -m service -a "name=nginx state=reloaded"
9、sysctl包管理模块
# ansible webservers -m sysctl -a "name=net.ipv4.ip_forward value=1 sysctl_set=yes"
10、user模块
添加用户:tomcat
# ansible webservers -m user -a 'name=tomcat uid=1010 group=tomcat password=123456'
删除用户:tomcat
# ansible webservers -m user -a 'name=tomcat state=absent remove=yes'
11、ping模块
# ansible webservers -m ping
playbooks模块调用格式如下,以 command模块为例子
- name: reboot the servers command: /sbin/reboot -t now
页:
[1]