Ansible: How to apply defaults to each complex arg

2019-06-11 04:01发布

I have the following list and default variables:

my_list_complex:
- key1: val1
  key2: val2
  key3: val3
  keyN: valN
- key1: val1
  key3: val3
  keyN: valN

key2: default2
key3: default3
key4: default4

I need to map my_list_complex to apply all the defaults to it. Please note the following:

  • the list of keys in complex is unbounded and unpredictable. Only the keys which have defaults and don't exist within the elements of the list should be set with default values

The expected output is:

my_list_complex_default_applied:
- key1: val1
  key2: val2
  key3: val3
  key4: default4
  keyN: valN
- key1: val1
  key2: default2
  key3: val3
  key4: default4
  keyN: valN

I've looked into combine, map and with_items but I haven't succeeded in achieving the task

How would I do this with an Ansible task or role?

1条回答
叼着烟拽天下
2楼-- · 2019-06-11 05:05

With recent version of Ansible, you can do:

---
- hosts: localhost
  gather_facts: no
  vars:
    my_list_complex:
      - key1: val1
        key2: val2
        key3: val3
        keyN: valN
      - key1: val1
        key3: val3
        keyN: valN
    my_template:
      key2: default2
      key3: default3
      key4: default4

  tasks:
    - set_fact:
        merged_list: "{{ (merged_list | default([])) + [ my_template | combine(item) ] }}"
      with_items: "{{ my_list_complex }}"
    - debug:
        msg: "{{ merged_list }}"

I can't remember since what version you can grow lists with set_fact and with_items, but I thing you should be fine with Ansible 2.1+.

查看更多
登录 后发表回答