beforesunset666
beforesunset666

Reputation: 33

Export vars element to yaml file with to_nice_yaml mantaining root and nested elements

I have the variable CONNECTION_DATA in the vars group inside an ansible playbook:

vars:
  CONNECTION_DATA:
    HOST: xxx
    PORT: xxx
    USER: xxx
    PWD: xxx

I need to write CONNECTION_DATA with its nested elements into a yaml file. For this I use the following task:

vars:
  CONNECTION_DATA:
    HOST: xxx
    PORT: xxx
    USER: xxx
    PWD: xxx
tasks:
  - name: Writing vars to file yaml
    ansible.builtin.copy:
      dest: /tmp/vars.yml
      content:  "{{ CONNECTION_DATA | to_nice_yaml }}"

Only problem is this outputs to:

HOST: xxx
PORT: xxx
USER: xxx
PWD: xxx

Instead I would like to have:

CONNECTION_DATA:
   HOST: xxx
   PORT: xxx
   USER: xxx
   PWD: xxx

Is there a workaround to achieve this?

Upvotes: 2

Views: 1655

Answers (1)

Frenchy
Frenchy

Reputation: 17027

you could modify your playbook like this:

- hosts: localhost
  gather_facts: false
  vars:
    CONNECTION_DATA:
      HOST: xxx
      PORT: xxx
      USER: xxx
      PWD: xxx
  tasks:    
    - name: Writing vars to file yaml
      ansible.builtin.copy:
        dest: /tmp/vars.yml
        content:  "{{ _output | to_nice_yaml }}"
      vars:
        _output: "{{  {'CONNECTION_DATA': CONNECTION_DATA} }}"

result:

CONNECTION_DATA:
    HOST: xxx
    PORT: xxx
    PWD: xxx
    USER: xxx

Upvotes: 4

Related Questions