在Ansible中,可以使用register
关键字来将任务的结果保存到一个变量中,然后可以使用stdout
或stdout_lines
属性来获取结果的值。
以下是一个示例代码:
- name: Run a command and get the result
shell: ls /path/to/directory
register: command_result
- name: Print the result
debug:
var: command_result.stdout
- name: Use the result in a conditional statement
debug:
msg: "Directory exists"
when: command_result.stdout != ""
在上面的示例中,第一个任务运行了一个shell命令ls /path/to/directory
,并将结果保存到command_result
变量中。然后,我们使用debug
模块打印了command_result.stdout
的值,以查看结果。最后,我们使用条件语句来检查结果是否为空,并根据结果打印不同的消息。
注意,command_result.stdout
是命令的标准输出的值,如果命令有多行输出,可以使用command_result.stdout_lines
来获取每行的值。