JeremyCanfield
JeremyCanfield

Reputation: 673

Replace nested variable in a file using Ansible

Let's say vars.yml contains the following.

john:
  foo: "bar"
jane:
  foo: "bar"

And I want to update the file so that only the john.foo nested variable contains Hello World.

john:
  foo: "Hello World"
jane:
  foo: "bar"

I suspect, but am not certain, that the playbook should have something like this. In this scenario, the shell module runs some command on the managed node that returns "Hello World", stored in the out variable. However, this fails to update the vars.yml file.

---
- hosts: all
  tasks:
    - shell: "some command here"
      register: out

    - replace:
        path: vars.yml
        regexp: "john: john | combine( {'foo': '{{ out.stdout }}'}, recursive=True)"
        replace: 'foo: "Hello World"'

Upvotes: 1

Views: 958

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68189

If you want to use combine to modify the dictionary include the variable and rewrite the file, e.g.

    - command: echo Hello World
      register: out
    - include_vars:
        file: vars.yaml
        name: _dict
    - copy:
        content: |
          {{ _dict_update|to_nice_yaml }}
        dest: vars.yaml
      vars:
        _value: "{{ _dict.john|combine({'foo': out.stdout}) }}"
        _dict_update: "{{ _dict|combine({'john': _value}) }}"

gives

shell> cat vars.yaml 
jane:
    foo: bar
john:
    foo: Hello World

The filter to_nice_yaml doesn't quote the strings.

Upvotes: 1

Related Questions