37

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...

The only difference between them is list name 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?

Nick Roz
  • 3,918
  • 2
  • 36
  • 57

6 Answers6

33

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}}"
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • 9
    In fact, the simplified answer would be `set_fact: {"{{ key }}":"{{ val }}"}` – Nick Roz Jul 01 '16 at 12:10
  • Thanks for the idea, I got around by using list of dictionaries `[{key: var1, val: val1}, {key: var2, val: val2}]` instead of a single dictionary `{var1: val1, var2: val2}`. – haridsv Jul 07 '17 at 13:42
18

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

Matthew
  • 6,351
  • 8
  • 40
  • 53
user2854753
  • 181
  • 1
  • 3
  • 5
    Here, `example_dict` ends up being a string, not a dictionary. – haridsv Jul 07 '17 at 13:08
  • 1
    I had to define it this way as well, surrounded by double quotes, with ansible 2.3.2.0. It did not end up as a string, printing it with `debug:` showed it had the correct dictionary structure. – Matthew Aug 16 '17 at 21:43
  • Thanks a lot! This also works for the situation, where your environment variable key names are dynamic based on names just known at runtime. Therefore one can use `environment:` at module level described in the docs at http://docs.ansible.com/ansible/latest/user_guide/playbooks_environment.html and create the variables with `- "{'dynamic environment variable key name inkl. {{ vars }}':'{{ dynamic environment variable value}}'}"` ([here´s a full example](https://gist.github.com/jonashackt/5c04edb58e12669fd11371441244ad16)). – jonashackt May 19 '18 at 11:13
6

As of 2018, using ansible v2.7.1, the syntax you suggest in your post works perfectly well.

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

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

And that in role "b" :

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

And execution goes :

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
theenglishway
  • 231
  • 3
  • 6
  • Using ansible 2.9.0 this does not work: ```- set_fact: _register_role_run: "{{ register_role_run_conf.name }}": "{{ register_role_run_conf.state }}" - debug: var: register_role_run_conf - debug: var: _register_role_run``` outputs ```TASK [register_role_run : debug] ok: [apigw-adco] => { "register_role_run_conf": { "name": "host_config", "state": true } } TASK [register_role_run : debug] ok: [apigw-adco] => { "_register_role_run": { "{{ register_role_run_conf.name }}": true } }``` – Adam Dec 02 '19 at 17:33
3
- set_fact: '{{ some_var }}={{ some_value }}'

It creates a string of inline module parameter expression by concatenating value of some_var (fact name), separator = and value of some_value (fact value).

czerny
  • 15,090
  • 14
  • 68
  • 96
1
- set_fact:
    var1={"{{variable_name}}":"{{ some value }}"}

This will create a variable "var1" with your dynamic variable key and value.


Example: I used this for creating dynamic tags in AWS Autoscaling group for creating kubernetes tags for the instances like this:

- name: Dynamic clustertag
  set_fact:
    clustertag={"kubernetes.io/cluster/{{ clustername }}":"owned"}
- name: Create the auto scale group
  ec2_asg:
    .
    .
    .
    tags:
      - "{{ clustertag }}"
Arash
  • 400
  • 4
  • 11
1

Beware of a change in 2.9 – the behaviour changed rendering all the answers invalid. https://github.com/ansible/ansible/issues/64169

Rafał W.
  • 109
  • 5
  • What is the correct behavior then? – Nick Roz Apr 05 '22 at 08:56
  • I don't have an answer here – except maybe for creating a string with a JSON and importing it. I wanted to create a dictionary consisting of a single entry based on a dictionary with multiple app configurations – and the name of the app was stored in a variable. I resorted to looping over the original dictionary and calling the include with just one definition. But it's a workaround in code, not an alternative to the original problem. OTOH, I'd guess most of these cases can be converted to this approach. – Rafał W. Apr 08 '22 at 07:22
  • That was a bug, and as the bug status _closed_ indicates, it has been fixed. – β.εηοιτ.βε Apr 08 '22 at 21:58