Ansible: Store command's stdout in new variable?

Forivin picture Forivin · Mar 17, 2016 · Viewed 167.2k times · Source

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

(Notice the {{ 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.

I guess I could just use {{command_output.stdout}} in my templates, but I want to get rid of that .stdout for readability.

Answer

udondan picture udondan · Mar 17, 2016

You have to store the content as a fact:

- set_fact:
    string_to_echo: "{{ command_output.stdout }}"