1

I am using ansible 2.9 and cannot lookout for a way to append below JSON structure with data

"Variables":[
    {
        "Strings": [
            "abc",
            "xyz"
        ],
        "Inputs": true
    }
]

I want to add 'efg' in strings, but not sure what is the syntax to be used in this. using Ansible set_fact for appending this.

I know we can do this using combine_filter but that only works for ansible 2.10 I guess. Any suggestion on how to do this.

AniK
  • 13
  • 4
  • 1
    ``Variables`` is a list. Do you want to modify only the first item of the list (atm the only one), or do you want to modify any other item in the list as well, if applicable? – Vladimir Botka Aug 18 '21 at 11:36
  • I just want to append a new data to Strings, rest all should be as it is. don't want to alter any other content in this. – AniK Aug 18 '21 at 11:40
  • Do you mean that you only want to change the _first_ `Strings` list, and do not change any additional `Strings` lists that are added later? – Michael Hampton Aug 21 '21 at 18:21
  • got the answer to above, i meant to add only in Strings list and rest everything should be intact. – AniK Aug 23 '21 at 04:52

1 Answers1

1

You can use combine filter in 2.9. It's been in Ansible since 2.3. What you can't use in 2.9 is the option list_merge. In this case, you can iterate the list and merge the lists on your own, e.g. the play

- hosts: localhost
  vars:
    to_add: efg
    Variables:
      - Strings: [abc, xyz]
        Inputs: true
  tasks:
    - set_fact:
        V2: "{{ V2|d([]) + [item|combine({'Strings': _Strings})] }}"
      loop: "{{ Variables }}"
      vars:
        _Strings: "{{ item.Strings + [to_add] }}"
    - set_fact:
        Variables: "{{ V2 }}"
    - debug:
        var: Variables

does the job

  Variables:
  - Inputs: true
    Strings:
    - abc
    - xyz
    - efg
Vladimir Botka
  • 5,138
  • 8
  • 20