diegus diegus - 6 months ago 14
Python Question

Python: write an INI file for Ansible

I would like to generate a simple .INI file using python with a precise structure, i.e.

[win_clones]
cl1 ansible_host=172.17.0.200
cl3 ansible_host=172.17.0.202


So far this is what I was able to produce:

[win_clones]
ansible_host = 172.17.0.200

[win_clones]
ansible_host = 172.17.0.202


I would like to:


  • have only one [win_clones]

  • include the name cl1/cl3

  • remove the spaces, i.e. ansible_host=172.17.0.200



Below my data (a nested dictionary) and the script I am using:

from ConfigParser import ConfigParser
topush = { 'cl1': {'ansible_host': ['172.17.0.200']},
'cl3': {'ansible_host': ['172.17.0.202']} }


def gen_host(data, group):
''' Takes a dictionary. It creates a INI file'''
config = ConfigParser()
config.add_section(group)
with open('host_test', 'w') as outfile:
for key, value in data.iteritems():
config.set(group,'ansible_host',''.join(value['ansible_host']))
config.write(outfile)

if __name__ == "__main__":
gen_host(topush, 'win_clones')

Answer

This is an "INI-like" file, not an INI file. You'll have to write it manually:

topush = {
    'cl1': {'ansible_host': ['172.17.0.200']},
    'cl3': {'ansible_host': ['172.17.0.202']}
}


def gen_host(data, group):
    ''' Takes a dictionary. It creates a INI file'''

    with open('host_test', 'w') as outfile:
        outfile.write("[{}]\n".format(group))

        for key, value in data.iteritems():
            outfile.write("{} ansible_host={}\n".format(key, value['ansible_host']))

if __name__ == "__main__":
    gen_host(topush, 'win_clones')
Comments