Set fact with dynamic key name inaccessible

I am trying to compress several pieces of similar code that looks like this:

- ... 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 the two is that I use different list names here instead of my_list

Actually I want to do this:

 set_fact: "{{ some var }}" : "{{ some value }}" 

I came across this post but could not find the answer here.

Can this be done or is there a workaround?

+17
variables dynamic ansible
source share
5 answers

take a look at this test book:

 --- - 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}}" 
+19
source share

The above does not work for me. What ultimately works

 - set_fact: example_dict: "{'{{ some var }}':'{{ some other var }}'}" 

This is, after all, obvious. You are building a string (external double quotes), which is then interpreted as a hash. In hashes, the key and value must be single quotes (internal single quotes around variable substitutions). And finally, you just put your variable replacements, as on any other line.

Stephen

+6
source share
 - set_fact: '{{ some_var }}={{ some_value }}' 

It creates a built-in module expression string by concatenating the value of some_var (fact name), separator = and the value of some_value (fact value).

+1
source share

Since 2018, using ansible v2.7.1, the syntax that you suggest in your post has been working fine.

At least in my case, I have this in the role of "a":

 - name: Set fact set_fact: "{{ variable_name }}": "{{ variable_value }}" 

And this is in the role of "b":

 - debug: msg: "variable_name = {{ variable_name }}" 

And the execution is:

 TASK [role a : Set fact] ******************************************************* ok: [host_name] => { "ansible_facts": { "variable_name": "actual value" }, "changed": false } ... TASK [role b : debug] ********************************************************** ok: [host_name] => {} MSG: variable_name = actual value 
+1
source share
 - set_fact: var1={"{{variable_name}}":"{{ some value }}"} 

This will create the variable " var1 " with the key and value of the dynamic variable.


Example: I used this to create dynamic tags in an AWS Autoscaling group to create kubernetes tags for instances like this:

 - name: Dynamic clustertag set_fact: clustertag={"kubernetes.io/cluster/{{ clustername }}":"owned"} 
 - name: Create the auto scale group ec2_asg: . . . tags: - "{{ clustertag }}" 
0
source share

All Articles