Search code examples
linuxansibleyamlansible-template

How to insert ansible dictionary variable as yaml in template output file


I have this dictionary

env2:
  a: 20
  b: 50
  d: 90

Now i have this template file

name: "test"

env: "{{ env2 | to_nice_yaml(indent=8) }}"

When i run the playbook i get output as

env: "a: 20
b: 50
d: 90
"

how can i get output as

env:
  a: 20
  b: 50
  d: 90

Solution

  • Use the Jinja filter indent. For example, the template below

    shell> cat test.yml.j2
    name: test
    
    env:
      {{ env2|to_nice_yaml|indent(2) }}
    

    and the playbook

    - hosts: localhost
    
      vars:
    
        env2:
          a: 20
          b: 50
          d: 90
    
      tasks:
    
        - template:
            src: test.yml.j2
            dest: /tmp/test.yml
    

    create the file

    shell> cat /tmp/test.yml
    name: test
    
    env:
      a: 20
      b: 50
      d: 90