Ansible replace all values with matching variable name

ansibleconfigurationdeployment

I'm a noob to Ansible, and could be going the wrong way about this, but this is the only way I know how to deal with this problem.

I have an ini file that's 4000 someodd entries long. In an attempt to do configuration as code, I have extracted out the values of each entry out into a variable file in the format of sectionheader--keyname: originalvalue and replaced them with a token pattern and the name of the variable that now contains their value.

I know Ansible can do regex replacement, but haven't been able to find a way that can do it as dynamically as this.

original file:

[sectionheader1]

keyname1=value1

[sectionheader2]

keyname1=value2

file with token replacements now kept in source and deployable:

[sectionheader1]

keyname1=%<sectionheader1--keyname1>

[sectionheader2]

keyname1=%<sectionheader2--keyname1>

variables:

testenvironment:
  sectionheader1--keyname1: value1
  sectionheader2--keyname1: value2
prodenvironment:
  sectionheader1--keyname1: value1 (specific to prod)
  sectionheader2--keyname1: value2 (specific to prod)

And then the idea is, I would replace every occurence of the token pattern %<> that I find a matching variable name for, and viola, I've constructed my config file specific to the environment I'm operating in. And now, I can check and if I have any lingering %<> patterns, I know that not all of the variables were defined, and can throw an error. Octopus deploy handles variable replacement in config files this way, which is what I have the most experience with.

Does Ansible have any way of doing this? I could write a script to do it I suppose and just have Ansible call that, but I was hoping for a built in way of configuration variable replacement as code.

Best Answer

The ini_file module might be used.

The task below

- ini_file:
    path: /scratch/testenvironment.ini
    section: "{{ item.key.split('--').0 }}"
    option: "{{ item.key.split('--').1 }}"
    value: "{{ item.value }}"
  loop: "{{ testenvironment|dict2items }}"

gives

$ cat /scratch/testenvironment.ini 

[sectionheader2]
keyname1 = value2
[sectionheader1]
keyname1 = value1

If the sections shall be alphabetically sorted use

 loop: "{{ testenvironment|dict2items|sort(attribute='key') }}"