Shoe Diamente
Shoe Diamente

Reputation: 794

How do I transform a list of objects in a list of strings in Ansible?

I have a variable in the form:

vars:
  somelist:
    - abc: 1
      def: 'somestring1'
    - abc: 2
      def: 'somestring2'
    - abc: 3
      def: 'somestring3'

and I'd like to pass the following list to some role's variable:

    - import_role:
        name: somerole
      vars:
        somevar:
          - '/somestring1/1/'
          - '/somestring2/2/'
          - '/somestring3/3/'

how can I map the objects of somelist to the string /{{ def }}/{{ abc }}/ and pass the resulting list to somevar?

Upvotes: 3

Views: 2168

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68404

In Ansible, the task below does the job

    - set_fact:
        somevar: "{{ somevar|default([]) +
                     [ '/' ~ item.def ~ '/' ~ item.abc ~ '/'] }}"
      loop: "{{ somelist }}"

The next option is to select values, add empty strings in front and after the attributes, and join the items of the lists. e.g.
    - set_fact:
        somevar: "{{ somelist|json_query('[].[``,def,abc,``]')|
                              map('join','/')|
                              list }}"

gives

  somevar:
  - /somestring1/1/
  - /somestring2/2/
  - /somestring3/3/

Upvotes: 3

Related Questions