ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 执行命令模块 [shell][1] 和 command 这两个模块都用来执行命令,shell的范围更大,支持脚本和管道,因此推荐使用shell。 >[info] -m 指定模块 module > -a 指定参数 args 当参数为没有空格隔开的内容时,可以不使用引号(单引号/双引号都可以);否则要使用引号。 ### 选项 ``` chdir change dir creates a filename, when it already exists, this step will not be run. removes a filename, when it does not exist, this step will not be run. warn no yes ``` ### 返回结果 ![](https://box.kancloud.cn/d47ca564dff3cabd930636b630c4be33_606x261.png) ### 命令行使用格式 ``` ansible anserver -m command -a 'hostname' ansible anserver -m shell -a 'hostname' ``` ### 脚本的远程执行 先使用copy模块复制脚本到远程客户端,再使用shell模块执行 ``` # ansible anserver -m shell -a '/tmp/test.sh' 若文件无执行权限,则可使用以下 # ansible anserver -m shell -a '/bin/bash /tmp/test.sh' ``` ### 在playbook中使用格式 ``` --- - name: shell and command test hosts: s.hi.com tasks: - name: shell test shell: hostname - name: command test command: hostname ``` ### 补充 当不指定模块时,默认使用`command`模块 `ansible hostname -a 'hostname'` ## 示例 ~~~ # 使用args来执行一些选项 - name: This command will change the working directory to somedir/ and will only run when somedir/somelog.txt doesn't exist. shell: somescript.sh >> somelog.txt args: chdir: somedir/ creates: somelog.txt executable: /bin/bash # /bin/sh不能同时处理重定向和通配符操作,使用/bin/bash可以 - name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does) shell: cat < /tmp/*txt args: executable: /bin/bash # 在另一个解释器下执行 - name: Run expect to wait for a successful PXE boot via out-of-band CIMC shell: | set timeout 300 spawn ssh admin@{{ cimc_host }} expect "password:" send "{{ cimc_password }}\n" expect "\n{{ cimc_name }}" send "connect host\n" expect "pxeboot.n12" send "\n" exit 0 args: executable: /usr/bin/expect delegate_to: localhost ~~~ [1]:http://docs.ansible.com/ansible/shell_module.html