Ansible任务可以有不同的输出格式,其中常见的有默认的“human-readable”和“json”格式。可以通过在Ansible Playbook的任务中使用“register”关键字来指定一个变量来存储任务输出结果,然后通过“debug”模块将其打印出来,如下所示:
- name: Run a command and store its stdout into a variable
command: echo "Hello world"
register: command_output
- name: Print the variable
debug:
var: command_output
以上示例中,“command”模块将命令的输出打印到标准输出流,而“register”关键字将其存储到“command_output”变量中。接下来,“debug”模块使用“var”参数将该变量打印到控制台。
如果要将任务输出结果保存为JSON格式,可以在Playbook最开始使用“defaults”模块定义“stdout_callback”参数值为“json”,如下所示:
- hosts: all
gather_facts: false
defaults:
- stdout_callback: json
tasks:
- name: Run a command and show its output in json format
command: echo "Hello world"
以上示例中,“stdout_callback”参数设置为“json”,然后在任务中执行“command”模块并打印结果。执行后,任务将以JSON格式的形式输出到控制台。