Ansible执行和显示多个命令的问题

50次阅读
没有评论

问题描述

有一个简单的Ansible脚本,其中包含多个命令。他想知道如何在执行每个命令时显示输出。

解决方案

请注意以下操作注意版本差异及修改前做好备份。

方案1

在运行playbook时,可以使用-vvv参数来获取命令的输出。
以下是如何在运行playbook时显示每个命令的输出的步骤:
1. 创建一个Ansible playbook文件,比如commands.yml
2. 在该文件中定义主机和任务。
3. 使用command模块来执行命令,并使用with_items指定要执行的命令列表。
4. 在command模块中添加register参数,以便将命令的输出保存到一个变量中。
5. 在任务中添加一个debug模块,以便显示命令的输出。
以下是一个示例commands.yml文件:

- hosts: myhost
  tasks:
    - name: few commands
      command: "{{ item }}"
      with_items:
        - ls -l
        - df -h
        - cat /tmp/1
      register: command_output

    - name: display command output
      debug:
        var: item.stdout
      with_items: "{{ command_output.results }}"

在上面的示例中,我们定义了一个名为few commands的任务,使用command模块执行了三个命令,并将命令的输出保存到command_output变量中。然后,我们添加了一个名为display command output的任务,使用debug模块显示每个命令的输出。

方案2

如果你只想在特定任务中显示命令的输出,可以使用debug模块来显示命令的输出。
以下是一个示例Ansible playbook,演示了如何在特定任务中显示命令的输出:

- hosts: myhost
  tasks:
    - name: execute commands
      command: "{{ item }}"
      with_items:
        - ls -l
        - df -h
        - cat /tmp/1
      register: command_output

    - name: display command output
      debug:
        var: item.stdout
      with_items: "{{ command_output.results }}"
      when: "'cat /tmp/1' in item.cmd"

在上面的示例中,我们使用command模块执行了三个命令,并将命令的输出保存到command_output变量中。然后,我们添加了一个名为display command output的任务,使用debug模块显示命令的输出。但是,我们只在命令cat /tmp/1执行时显示输出,通过使用when条件来实现。
请注意,以上解决方案中的示例代码仅供参考,你可以根据自己的需求进行修改和扩展。

正文完