Replace Line In YAML While Keeping Indentation Using Ansible

In theory Ansible should be declarative and have full control over the systems we touch with it.

In practice, this is unfortunately not always the case.

With this nifty task we can replace the value of a key (given as yaml_key) to a new value (given as new_value) while preserving it’s indentation.

- name: Replace values in YAML file while keeping their indentation
  lineinfile:
    backup: true
    backrefs: true
    state: present
    path: foo.yaml
    regexp: '^(\s*){{ yaml_key }}:.*'
    line: '\1{{ yaml_key }}: {{ new_value }}'

#ansible