I am trying to shrink several chunks of similar code which looks like:
- ... multiple things is going here register: list_register - name: Generating list set_fact: my_list="{{ list_register.results | map(attribute='ansible_facts.list_item') | list }}" # the same code repeats...
In fact, the only difference between them is that I am using different list names here instead of my_list
In fact I want to do this:
set_fact: "{{ some var }}" : "{{ some value }}"
I came across this post but didn't find any answer here.
Is it possible to do so or is there any workaround?
This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module. These variables will be available to subsequent plays during an ansible-playbook run. Set cacheable to yes to save variables across executions using a fact cache.
Assigning a value to a variable in a playbook is quite easy and straightforward. Begin by calling the vars keyword then call the variable name followed by the value as shown. In the playbook above, the variable name is salutations and the value is Hello world!
take a look at this sample playbook:
--- - hosts: localhost vars: iter: - key: abc val: xyz - key: efg val: uvw tasks: - set_fact: {"{{ item.key }}":"{{ item.val }}"} with_items: "{{iter}}" - debug: msg="key={{item.key}}, hostvar={{hostvars['localhost'][item.key]}}" with_items: "{{iter}}"
The above does not work for me. What finally works is
- set_fact: example_dict: "{'{{ some var }}':'{{ some other var }}'}"
Which is in the end obvious. You construct a string (the outer double quotes) which is then interpreted as a hash. In hashes key and value must be single quotes (the inner single quotes around the variable replacements). And finally you just place your variable replacements as in any other string.
Stefan
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With