Question:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[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:
You have to store the content as a fact:
1 2 3 |
- set_fact: string_to_echo: "{{ command_output.stdout }}" |