ansiblejinja2

Joining elements of nested lists in Ansible


I have a nested list str that looks like below:

[["22","ABC","XYZ"],["555","IJK","PQR"],...] 

I have to combine the elements of the inside list with a / then join them with a , to form a string as:

22/ABC/XYZ,555/IJK/PQR,...

I tried with set_fact and jinja2 but no luck.

- set_fact:
     str1: |-
       {%- set fs = "" -%}
       {%- set im = "" -%}
       {%- for i in str -%}
         {%- for elem in i -%}
           {%- set im = im + "/" + elem -%}
         {%- endfor -%}
         {%- set fs = fs + "," + im -%}
       {%- endfor -%}
       {{ fs }}
- debug: var=str1      

Output:

TASK [debug var=str1] **********************************
ok: [host1] => {
    "str1": "" 

Expected output:

TASK [debug var=str1] **********************************
ok: [host1] => {
    "str1": "22/ABC/XYZ,555/IJK/PQR" 

Thanks


Solution

  • First map the filter join(/) to the items of the list and then join(,) them

      - set_fact:
          str1: "{{ str | map('join', '/') | join(',') }}"
      - debug: var=str1
    

    gives

      str1: 22/ABC/XYZ,555/IJK/PQR