Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 906
Shoe Diamente Avatar asked Dec 11 '25 19:12

Shoe Diamente


1 Answers

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/
like image 124
Vladimir Botka Avatar answered Dec 14 '25 08:12

Vladimir Botka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!