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

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

你在终端输入一条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'python

例如:
[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 >>shell

client01 | SUCCESS | rc=0 >>安全

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

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

[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的区别
看到这里,想必已经让你清晰不少了吧!htm

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

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

相关文章
相关标签/搜索