Ansible 命令
Ansible 命令
Ansible 命令模块用于在远程目标机器上运行任何命令或运行任何脚本。或者用于在远程节点上执行命令。
命令模块用于在远程节点或服务器上运行简单的Linux命令,远程节点或服务器是主机组中提到的主机组或独立服务器的一部分.
Ansible 命令模块和Shell 模块
当我们需要在远程服务器中执行命令时,在您选择的shell 中使用shell 模块。默认情况下,命令在 /bin/sh 外壳上运行。您可以使用诸如"|"、"<"、">"等各种操作以及$HOME 等环境变量。
命令模块没有通过shell处理命令。所以它不支持上述操作。
你给出你想要执行的命令,就像你在 UNIX shell 上提供它一样,命令名后跟参数。
-name: Executing a command using the shell module
shell: ls-lrt > temp.txt
第一个命令列出当前文件夹中的所有文件并将其写入文件 temp.txt。
-name: Executing a command using the command module
command: hello.txt
上面的例子显示了hello.txt文件的内容。
更改默认目录
该命令将始终在默认目录中执行。您可以使用 chdir 参数更改和指定要在其中运行命令的目录路径。此参数可用于命令和 shell 模块。
您还可以通过在可执行参数中指定 require shell 的绝对路径来更改默认 shell。
--hosts: loc
tasks:
-name: ansible command with chdir and executable parameters
command: ls-lrt
args:
chdir: /home/Ansible/command_chdir_example
executable: /bin/bash
在上面的例子中,通过给过时的路径/bin/bash来使用"Bourne Again Shell"。并将目录改为/home/Ansible/command_chdir_example。
执行多个命令
如果你需要运行多个命令,那么你可以把它们给两个shell和使用"with_items"的命令模块。
示例 1:
-hosts: loc
tasks:
-name: Ansible command module multiple commands
command: "touch {{ item }}"
with_items:
-hello.txt
-hello1.txt
-hello2.txt
args: chdir: /root/ansible
示例 2:
-hosts: loc
tasks:
-name: Ansible shell module multiple commands
shell: "cat {{ item }} | grep ansible"
with_items:
-hello.txt
-hello1.txt
-hello2.txt
args:
chdir: /root/ansible
在上面的例子中,我们要执行三个文件; hello.txt、hello1.txt 和 hello2.txt。由于我在命令中给出了 {{item}} 关键字,因此在每次迭代中它将被替换为列表的一个元素。确保"with_item"的缩进级别与模块名称在同一级别。