Set fact with dynamic key name in ansible

2019-01-18 10:52发布

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?

4条回答
劫难
2楼-- · 2019-01-18 11:12
- 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).

查看更多
时光不老,我们不散
3楼-- · 2019-01-18 11:20

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
查看更多
Melony?
4楼-- · 2019-01-18 11:35

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}}"
查看更多
疯言疯语
5楼-- · 2019-01-18 11:35

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

查看更多
登录 后发表回答