Search code examples
ansiblejinja2

Ansible YAML Output Formatting For List of Dictionaries


In Ansible, is it possible to output a list of dictionaries in pretty print YAML with flow style mapping?

Example of source list of dict:

my_servers:
  - hostname: myhostname1
    id: 101
    reverse: 'true'
    type: red
  - hostname: myhostname2
    id: 102
    reverse: 'false'
    type: white
  - hostname: myhostname3
    id: 103
    reverse: 'true'
    type: blue
  - hostname: myhostname4
    id: 104
    reverse: 'false'
    type: green

I'd like to output to be like this:

my_servers:
  - {hostname: myhostname1, id: 101, type: red, reverse: "true"}
  - {hostname: myhostname2, id: 102, type: white, reverse: "false"}
  - {hostname: myhostname3, id: 103, type: blue, reverse: "true"}
  - {hostname: myhostname4, id: 104, type: green, reverse: "false"}

The only way I got it to look like this was through custom Jinja templating. Is there another way someone can share?


Solution

  • @β.εηοιτ.βε above led to dig further and found the answer.

    The key is to set default_flow_style=none in the to_yaml filter.

    - name: Test
      hosts: "localhost"
      gather_facts: no
      serial: 1
    
      vars:
        my_servers:
          - hostname: myhostname1
            id: 101
            reverse: 'true'
            type: red
          - hostname: myhostname2
            id: 102
            reverse: 'false'
            type: white
          - hostname: myhostname3
            id: 103
            reverse: 'true'
            type: blue
          - hostname: myhostname4
            id: 104
            reverse: 'false'
            type: green
    
      tasks:
      - debug: 
          msg: | 
            my_servers:
            {{  my_servers | to_yaml(default_flow_style=none) }}
    

    Gives this:

    ok: [localhost] => {}
    
    MSG:
    
    my_servers:
    - {hostname: myhostname1, id: 101, reverse: 'true', type: red}
    - {hostname: myhostname2, id: 102, reverse: 'false', type: white}
    - {hostname: myhostname3, id: 103, reverse: 'true', type: blue}
    - {hostname: myhostname4, id: 104, reverse: 'false', type: green}
    

    The problem now is to get proper indentation.