Replacing variables in external file through playbook

Viewed 74

I would like to use variables (vars.yaml) to replace the content in a config file (config.yaml) and automatise the process in the playbook (playbook.yaml). But I can't found a type of process that automaticly search for vars inside an external file through the playbook.yaml.

My files look like this : vars.yaml

---
var1: content1
var2: content2
var3: content3

config.yaml:

apiVersion: 1
 
datasources:
  - name: {{ var1 }}
    type: {{ var2 }}
    access: proxy
    url: {{ var3 }}

playbook.yaml:

---
- name: Deploy
  hosts: localhost
  tasks:
    - include_vars: ./vars.yaml

    - name: Update config file
      # Something to replace all vars in the config file using the content of vars.yaml

Can you help me and tell me if there is something possible instead of doing a regex for each variable ...?

1 Answers

The file with the unresolved variables is actually a template. Let's name it this way

shell> cat config.yaml.j2
apiVersion: 1

datasources:
  - name: {{ var1 }}
    type: {{ var2 }}
    access: proxy
    url: {{ var3 }}

Use the template module to update config.yaml, e.g.

    - include_vars: vars.yaml
    - name: Update config file
      template:
        src: config.yaml.j2
        dest: config.yaml

gives

shell> cat config.yaml
apiVersion: 1

datasources:
  - name: content1
    type: content2
    access: proxy
    url: content3
Related