ansible远程命令,ansible


ansible远程命令

ansible testhost -m command -a ‘w’
这样就可以批量执行命令了。这里的testhost 为主机组名,-m后边是模块名字,-a后面是命令。当然我们也可以直接写一个ip,针对某一台机器来执行命令。
ansible 127.0.0.1 -m command -a ‘hostname’
错误: “msg”: “Aborting, target uses selinux but python bindings (libselinux-python) aren’t installed!”
解决: yum install -y libselinux-python

还有一个模块就是shell同样也可以实现 ,他可以用来执行脚本
ansible testhost -m shell -a ‘w’

ansible 管理文件和目录

需要用到copy模块,跟本机执行copy命令基本上一样,再次执行会覆盖
拷贝目录:
ansible 192.168.1.203 -m copy -a “src=/etc/ansible dest=/tmp/ansibletest owner=root group=root mode=0755”

注意:源目录会放到目标目录下面去,如果目标指定的目录不存在,它会自动创建。如果拷贝的是文件,dest指定的名字和源如果不同,并且它不是已经存在的目录,相当于拷贝过去后又重命名。但相反,如果desc是目标机器上已经存在的目录,则会直接把文件拷贝到该目录下面。
拷贝文件:
ansible 192.168.1.203 -m copy -a “src=/etc/passwd dest=/tmp/1.txt owner=root group=root mode=0755”

这里的/tmp/1.txt和源机器上的/etc/passwd是一致的。

ansible 远程执行脚本

需要用到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 mode=0755”
最后是批量执行该shell脚本
ansible testhost -m shell -a “/tmp/test.sh”
执行完毕可以查看对应生成的/tmp/ansible_test.txt文件,判断脚本执行成功
shell模块,还支持远程执行命令并且带管道
ansible testhost -m shell -a “cat /etc/passwd|wc -l “

ansible管理任务计划

需要用到cron模块
ansible testhost -m cron -a “name=’test cron’ job=’/bin/touch /tmp/123.txt’ hour=1 weekday=6”

在geenk01上我们可以crontab -l查看
#下面的注释不能删除,不然ansible要执行删除操作的时候就找不到了
#Ansible: test cron
* 1 * * 6 /bin/touch /tmp/123.txt

若要删除该cron 只需要加一个字段 state=absent
ansible testhost -m cron -a “name=’test cron’ state=absent”

其他的时间表示:分钟 minute 小时 hour 日期 day 月份 month

ansible安装包和管理服务

需要使用到yum 模块
安装httpd:
ansible testhost -m yum -a “name=httpd”
在name后面还可以加上state=installed/removed
卸载httpd:
ansible testhost -m yum -a “name=httpd state=removed”

启动并设置为开机启动:(需要用到模块service)
ansible testhost -m service -a “name=httpd state=started enabled=yes”
这里的name是centos系统里的服务名,可以通过chkconfig –list查到。
停止服务并讲开机启动关闭
ansible testhost -m service -a “name=httpd state=stopped enabled=no”

Ansible文档的使用

ansible-doc -l 列出所有的模块
ansible-doc cron 查看指定模块的文档

相关内容

    暂无相关文章