ansible 中shell 模块和command 模块的区别

Ansible中有一个很重要的功能就是可以执行ad-hoc命令,可能有些人不懂ad-hoc这个词的意思,它表示即时的意思,或者说随意的意思。
与之相对的是ansible playbook功能,playbook适用于批量部署环境,一般不用经常改动。而ad-hoc命令适用于业务变更等操作场景,比如批量部署一个配置文件,重启某个服务,安装一些包等。
ad-hoc命令中有两个模块:command, shell。很多人不知道他们的区别是什么,其实很简单。

你在终端输入一条ad-hoc命令后,ansible会生成一个可执行python脚本文件,然后把它拷贝到远程机器上执行,这个脚本中包含了命令行的所有信息。
如果你用的是command或shell模块,那么脚本中调用的是subprocess.Popen(args,kwargs)函数,command和shell的区别就在于command模块使用shell=True,而shell模块使用shell=False,就是一个调用了shell,一个没有。
官方文档中是不建议使用shell=True的,因为这可能导致shell injection安全问题,但是有些情况下用shell模块就很方便,比如我要批量删除一些文件,
ansible -i inventory all -m command -a "rm -f /etc/yum.repos.d/CentOS
.repo" -U root -s -f 50 -kK
你如果执行以上命令的话,是不会删除掉那些文件的,为什么?
因为你的命令行中包含了通配符号,通配符必须要有在shell环境中才能被识别出,不然,它只能删除CentOS.repo这一个文件。
所以你需要执行以下命令才能成功
ansible -i inventory all -m shell -a "rm -f /etc/yum.repos.d/CentOS.repo" -U root -s -f 50 -kK
而这两个命令所生成的可执行脚本的区别就一行
< MODULE_ARGS = 'rm -f /etc/yum.repos.d/CentOS
.repo'

MODULE_ARGS = 'rm -f /etc/yum.repos.d/CentOS* #USE_SHELL'

例如:
[root@master tmp]# ansible slave -m command -a "rm -f /tmp/test*" -U root -s -f 50 -kK
SSH password:
SUDO password[defaults to SSH password]:
client02 | SUCCESS | rc=0 >>

client01 | SUCCESS | rc=0 >>

[root@client01 tmp]# ls
test0001 test.sh txt01 yum.log

[root@client02 tmp]# ls
test0001 test.sh txt01 yum.log

[root@master tmp]# ansible slave -m shell -a "rm -f /tmp/test*" -U root -s -f 50 -kK
SSH password:
SUDO password[defaults to SSH password]:
client01 | SUCCESS | rc=0 >>

client02 | SUCCESS | rc=0 >>
[root@client01 tmp]# ls
txt01 yum.log
[root@client02 tmp]# ls
txt01 yum.log

以上就是shell 和command的区别
看到这里,想必已经让你清晰很多了吧!

http://www.cnblogs.com/hemhem/archive/2011/03/14/2087482.html

http://www.ruby-lang.org/en/downloads/

转载于:https://blog.51cto.com/wujianwei/2082906

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值