Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set fact with dynamic key name in ansible

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?

like image 420
Nick Roz Avatar asked Jul 01 '16 10:07

Nick Roz


People also ask

Can ansible-playbook set fact?

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.

How do you assign values in ansible?

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!


2 Answers

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}}" 
like image 76
Konstantin Suvorov Avatar answered Sep 22 '22 16:09

Konstantin Suvorov


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

like image 26
user2854753 Avatar answered Sep 19 '22 16:09

user2854753