Ansible:将命令的标准输出存储在新变量中吗? [英] Ansible: Store command's stdout in new variable?

查看:130
本文介绍了Ansible:将命令的标准输出存储在新变量中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的剧本中,我想创建一个变量,用于保存外部命令的输出.之后,我想在几个模板中使用该变量.

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

让我们说这是我的模板:

and let's say this is my template:

[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆