'Find and update key values in a file using ansible role

I need to update the key values using regex and replace like all user input ,username and password using a separate new task.

inventory/main.yml

service1 : abc.com/s1
service2 : def.com/s2
username : user
password: pass

values.yml

---
service1:
  image:
    name: <user input> # service1 image

service2:
  config:
    range: 127.0.0.0
  image:
    name: <user input> # service2 image
  id:
    username:  # DB username
    password:  # DB Password

Expectation :

values.yml

---
service1:
  image:
    name: abc.com/s1 # service1 image

service2:
  config:
    range: 127.0.0.0
  image:
    name: def.com/s2 # service2 image
  id:
    username: user # DB username
    password: pass # DB Password

Should create a update_values.yml task which will find the values.yml path and replace the required values

My attempt as update_values.yml

---
- name: update value
  replace:
    path: <path>/values.yml
    regexp: "service1.image.name: <user input>"
    replace: "abc.com/s1"


Solution 1:[1]

In Ansible, this is a typical use-case of a template. Create the template

shell> cat values.yml.j2
---
service1:
  image:
    name: {{ service1 }}  # service1 image

service2:
  config:
    range: 127.0.0.0
  image:
    name: {{ service2 }}  # service2 image
  id:
    username: {{ username }}  # DB username
    password: {{ password }}  # DB Password

Then, the tasks below

    - include_vars: inventory/main.yml
    - template:
        src: values.yml.j2
        dest: values.yml

create the file

shell> cat values.yml
---
service1:
  image:
    name: abc.com/s1  # service1 image

service2:
  config:
    range: 127.0.0.0
  image:
    name: def.com/s2  # service2 image
  id:
    username: user  # DB username
    password: pass  # DB Password

Q: "Is there any other method using regex and replace?"

A: You can use lineinfile if you want to. For example

    - lineinfile:
        path: values.yml
        regexp: "{{ item.regexp }}"
        line: "{{ item.line }}"
        backrefs: true
      loop:
        - {regexp: '^(\s*)name: <user input>(.*)$', line: '\1name: {{ service2 }}\2'}
        - {regexp: '^(\s*)name: <user input>(.*)$', line: '\1name: {{ service1 }}\2'}
        - {regexp: '^(\s*)username:\s+.*?(\s+#.*)$', line: '\1username: {{ username }}\2'}
        - {regexp: '^(\s*)password:\s+.*?(\s+#.*)$', line: '\1password: {{ password }}\2'}

change the file

shell> cat values.yml
---
service1:
  image:
    name: abc.com/s1 # service1 image

service2:
  config:
    range: 127.0.0.0
  image:
    name: def.com/s2 # service2 image
  id:
    username: user  # DB username
    password: pass  # DB Password

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1