How to format a dict to a string in ansible

Viewed 4606

I want to format a dict in ansible like so,

from

{'a': 1, 'b': 2, 'c': 3}

to

'a=1,b=2,c=3'

and have to set it as an environment variable in a block like so,

vars:
  test_env:
    a: 1
    b: 2
    c: 3

- block:
    # tasks
  environment:
    SOME_ENV: 'a=1,b=2,c=3'

here I want to convert test_env dict to 'a=1,b=2,c=3' I can not set the fact to modify the dict and then set it to the SOME_ENV because environment is a different clause, maybe I can modify the dict in the vars clause but is there any other solution?

1 Answers

Decompose the dictionary to the lists of keys and values. Then zip the lists and join the items. For example,

    - block:
        - command: echo $SOME_ENV
          register: result
        - debug:
            var: result.stdout
      environment:
        SOME_ENV: "{{ test_env.keys()|
                      zip(test_env.values())|
                      map('join', '=')|
                      join(',') }}"

give

  result.stdout: a=1,b=2,c=3
Related