ansible 配置
vi /etc/ansible/hosts //增加
[testhost]
127.0.0.1
172.7.15.111
说明: testhost为主机组名字,自定义的。 下面两个ip为组内的机器ip。
远程执行命令
ansible testhost -m command -a 'w'
这样就可以批量执行命令了。这里的testhost 为主机组名,当然我们也可以直接写一个ip,针对某一台机器来执行命令。 //也可以用shell,shell支持管道符'|'
错误: "msg": "Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!"
解决: yum install -y libselinux-python
拷贝文件或者目录
ansible web10.aming.com -m copy -a "src=/etc/ansible dest=/tmp/ansibletest owner=root group=root mode=0755"
注意:源目录会放到目标目录下面去,如果目标指定的目录不存在,它会自动创建。如果拷贝的是文件,dest指定的名字和源如果不同,并且它不是已经存在的目录,相当于拷贝过去后又重命名。但相反,如果desc是目标机器上已经存在的目录,则会直接把文件拷贝到该目录下面。
ansible testhost -m copy -a "src=/etc/passwd dest=/tmp/1.txt"
这里的/tmp/123和源机器上的/etc/passwd是一致的,但如果目标机器上已经有/tmp/123目录,则会再/tmp/123目录下面建立passwd文件
远程执行一个shell脚本
首先创建一个shell脚本
vim /tmp/test.sh //加入内容
#!/bin/bash
echo `date` > /tmp/ansible_test.txt
然后把该脚本分发到各个机器上
ansible testhost -m copy -a "src=/tmp/test.sh dest=/tmp/test.sh mod=0755"
最后是批量执行该shell脚本
ansible testhost -m shell -a "/tmp/test.sh"
shell模块,还支持远程执行命令并且带管道
ansible testhost -m shell -a "cat /etc/passwd|wc -l "
cron任务计划
ansible testhost -m cron -a "name='test cron' job='/bin/touch /tmp/1212.txt' weekday=6"
若要删除该cron 只需要加一个字段 state=absent
ansible testhost -m cron -a "name='test cron' job='/bin/touch /tmp/1212.txt' weekday=6 state=absent"
yum和service
ansible testhost -m yum -a "name=httpd"
ansible testhost -m service -a "name=httpd state=started enabled=yes"
文档使用:
ansible-doc -l 列出所有的模块
ansible-doc cron 查看指定模块的文档
转载于:https://blog.51cto.com/xiongrc/1788219