Append new key value pair with correct indentation in yml file

Hi,

I’m trying to append new key-value pair in the existing yml (subcluster_to_subnet_map.yml) file using combine. New values are getting appended correctly but it’s getting added without spaces.

I need help with adding 2 spaces in starting so that the indentation is maintained. Please suggest how this can be achieved. (I don’t want to use lineinfile here)

Yaml file on which key-value pair should be added: subcluster_to_subnet_map.yml

subcluster_to_subnet_map:
ee: ee-ci9-sc8
test: test-ci1-sc1

<<new value should have 2 spaces>>

I’m using below code for this -

  • name: append new subnet and subcluster values
    set_fact:
    subcluster_to_subnet_map: “{{ subcluster_to_subnet_map | default({}) | combine ({input_subcluster: input_subnet}) }}”

  • debug:
    var: subcluster_to_subnet_map

  • name: write var to file
    copy:
    content: “{{ subcluster_to_subnet_map | to_nice_yaml }}”
    dest: environment/subcluster_to_subnet_map.yml

The output I’m getting now is -

subcluster_to_subnet_map:
ee: ee-ci9-sc8
test: test-ci1-sc1
test1: infra-nodes

Hi Team,

Looking forward to any input.

Thanks

Where are these variables defined?

subcluster_to_subnet_map
input_subcluster
input_subnet

Please share the complete playbook and variables.

I’m taking user input for variables: input_subcluster, input_subnet and subcluster_to_subnet_map is defined in subcluster_to_subnet_map.yml file.

Here is my code -

  • hosts: localhost
    connection: local
    gather_facts: True

I'm taking user input for variables: *input_subcluster, input_subnet *and *subcluster_to_subnet_map* is defined in subcluster_to_subnet_map.yml file.

Here is my code -

- hosts: localhost
connection: local
gather_facts: True

#
## Taking inputs for subcluster and subnet
#
vars_prompt:
- name: "input_subcluster"
prompt: "Enter subcluster name"
private: no

- name: "input_subnet"
prompt: "Enter subnet name"
private: no

- include_vars:
file: environment/Dev/subcluster_to_subnet_map.yml
name: subcluster_to_subnet_map

- name: append new subnet and subcluster values
set_fact:
subcluster_to_subnet_map: "{{ subcluster_to_subnet_map | default({}) | combine ({input_subcluster: input_subnet}) }}"

\- debug:
       var: subcluster\_to\_subnet\_map

\- name: write var to file
  copy:
       content: &quot;\{\{ subcluster\_to\_subnet\_map | to\_nice\_yaml \}\}&quot;

This means the content of subcluster_to_subnet_map variable, which does not include its own name. You should explicitly write that out.
Try this:

content: "{{ {'subcluster_to_subnet_map': subcluster_to_subnet_map} | to_nice_yaml }}"

It gave the below output:

subcluster_to_subnet_map:
subcluster_to_subnet_map:
ee: ee-ci9-sc8
test: test-ci1-sc1
test1: infra-nodes

The expected output is:

subcluster_to_subnet_map:

ee: ee-ci9-sc8
test: test-ci1-sc1
test1: infra-nodes

Hi All,

Any help would be appreciated here.

Thanks