Ansible:将命令的标准输出存储在新变量中? [英] Ansible: Store command's stdout in new variable?
问题描述
在我的剧本中,我想创建一个变量来保存外部命令的输出.之后我想在几个模板中使用该变量.
Inside my playbook I'd like to create a variable holding the output of an external command. Afterwards I want to make use of that variable in a couple of templates.
以下是剧本的相关部分:
Here are the relevant parts of the playbook:
tasks:
- name: Create variable from command
command: "echo Hello"
register: command_output
- debug: msg="{{command_output.stdout}}"
- name: Copy test service
template: src=../templates/test.service.j2 dest=/tmp/test.service
- name: Enable test service
shell: systemctl enable /tmp/test.service
- name: Start test service
shell: systemctl start test.service
假设这是我的模板:
[Unit]
Description=MyApp
After=docker.service
Requires=docker.service
[Service]
TimeoutStartSec=0
ExecStartPre=-/usr/bin/docker kill busybox1
ExecStartPre=-/usr/bin/docker rm busybox1
ExecStartPre=/usr/bin/docker pull busybox
ExecStart=/usr/bin/docker run --name busybox1 busybox /bin/sh -c "while true; do echo {{ string_to_echo }}; sleep 1; done"
[Install]
WantedBy=multi-user.target
(注意{{ string_to_echo }}
)
所以我基本上要寻找的是一种将 command_output.stdout
(在第一个任务期间生成/检索)的内容存储在新变量 string_to_echo中的方法代码>.
之后我想在多个模板中使用该变量.
So what I'm basically looking for is a way to store the contents of command_output.stdout
(which is generated/retrieved during the first task) in a new variable string_to_echo
.
That variable I'd like to use in multiple templates afterwards.
我想我可以在模板中使用 {{command_output.stdout}}
,但为了可读性我想去掉那个 .stdout
.
I guess I could just use {{command_output.stdout}}
in my templates, but I want to get rid of that .stdout
for readability.
推荐答案
你必须将内容存储为事实:
- set_fact:
string_to_echo: "{{ command_output.stdout }}"
这篇关于Ansible:将命令的标准输出存储在新变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!