Kevin C
Kevin C

Reputation: 5720

Append key/value on nested dict

Assume these dummy variables:

var_list_one:
  acc: abc
  prod: def
var_list_two:
  acc: xyz
  prod: whatever

my_var:
  one_key:
    one_string: great
    environment: Acceptance
  two_key:
    two_string: great
    environment: Production
  three_key:
    three_string: woow
    environment: else

How do I configure Ansible to append the key and value from the lists to the required dict keys.

End goal:

my_var:
  one_key:
    one_string: great
    environment: Acceptance
    var_list_one: abc
    var_list_two: xyz
  two_key:
    two_string: great
    environment: Production
    var_list_one: def
    var_list_two: whatever
  three_key:
    three_string: woow
    environment: else

I've tried using combine, but this case seems too complex for simple combine since this a nested dict.

Upvotes: 1

Views: 1512

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67984

Start solving the rebus by creating the list of the 'var_list_.*' variables

    - set_fact:
        var_list: "{{ query('varnames', 'var_list_.*') }}"

gives

  var_list:
  - var_list_one
  - var_list_two

Then create the list of all values

    - set_fact:
        var_list_all: "{{ var_list_all|d([]) + [lookup('vars', item)|
                                                combine({'key': item})] }}"
      loop: "{{ var_list }}"

gives

  var_list_all:
  - acc: abc
    key: var_list_one
    prod: def
  - acc: xyz
    key: var_list_two
    prod: whatever

Update the items of the dictionary according to the attribute environment, e.g.

    - set_fact:
        my_var: "{{ my_var|combine({item.key: my_var[item.key]|combine(_dict)}) }}"
      loop: "{{ my_var|dict2items }}"
      vars:
        _env:
          Acceptance: acc
          Production: prod
        _attr: "{{ _env[item.value.environment] }}"
        _dict: "{{ var_list_all|items2dict(key_name='key', value_name=_attr) }}"
      when: item.value.environment in _env

gives what you want

  my_var:
    one_key:
      environment: Acceptance
      one_string: great
      var_list_one: abc
      var_list_two: xyz
    three_key:
      environment: else
      three_string: woow
    two_key:
      environment: Production
      two_string: great
      var_list_one: def
      var_list_two: whatever

Upvotes: 1

Related Questions