Hello - I’m trying to register a variable on dynamic host {{ target }} and use it on a different host ptl01a0fap005. The dynamic host {{ target }} is passed in as an extra-var on the command line.
I’ve found that I can successfully debug the variable I want on the different host, in green below. However, if I try to set_fact the with the same syntax it fails. The last attempt would normally work, but in this case doesn’t due to the nested variable.
Why does this syntax work for debug but not set_fact? How can I actually use the debug output on the other host?
Playbook:
`
Why does this syntax work for debug but not set_fact? How can I actually
use the debug output on the other host?
Pure luck that the debug work and you yaml syntax is wrong of set_fact.
*Playbook:*
---
- name: Target Host
hosts: "{{ target }}"
tasks:
- name: Register foo
command: 'echo Hello World'
register: foo
- name: Different Host
hosts: ptl01a0fap005
tasks:
- debug: var=hostvars[groups['{{ target }}'][0]]['foo']['stdout']
You should not use {{ }} and ', correct syntax is
- debug: var=hostvars[groups[target][0]]['foo']['stdout']
- name: set_fact bar
set_fact:
bar=hostvars['{{ target }}'][0]]['foo']['stdout']
<snip />
- name: set_fact bar
set_fact:
bar="{{ hostvars['{{ target }}'][0]]['foo']['stdout'] }}"
This is wrong yaml syntax.
bar= should be bar:
And also here you can't use {{ }} inside a template, and a '' indicate a string not a variable.
Correct syntax is
bar: "{{ hostvars[target][0]]['foo']['stdout'] }}"
But I guess this will also fail since target=Test5 that is a group, so it will not find hostvars for a host called Test5. Maybe you forgot to include the group as you did in debug task.
Kai - Thank you very much. Everything you mentioned was exactly right. Helped me learn a thing or two about proper syntax…and reminding me not to code too late into the evening. haha.
Final Playbook:
`