在Ansible中,执行带管道的命令需要使用
shell
模块,因为
command
模块不支持管道和重定向符号。以下是一些关键点和示例:
shell模块
:在远程主机上执行shell命令,支持管道和重定向符号。
可以使用
chdir
参数在执行命令之前切换到指定目录。
creates
参数可以在指定文件存在时不执行命令。
removes
参数可以在指定文件不存在时不执行命令。
executable
参数可以指定使用其他类型的shell执行命令。
command模块
:在远程主机执行命令,但不支持管道和重定向符号。
示例
:
使用
shell
模块执行带管道的命令:
ansible all -m shell -a ‘chdir=/opt echo “123456”|passwd –stdin test’
使用
command
模块执行命令(不支持管道):
ansible all -m command -a ‘chdir=/opt ls’
注意事项
:
使用
shell
模块时,命令会经过远程主机上的
/bin/sh
程序处理。
如果需要执行的命令中含有重定向、管道符等操作时,使用
command
模块这些符号会失效。
其他模块
:
script
模块:在远程主机上执行ansible主机上的脚本。
使用Ansible执行带管道的命令时,应优先考虑使用
shell
模块,以确保命令能够正确执行。