简体   繁体   中英

Python: write an INI file for Ansible

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

[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, ie 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')

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')

Need to slightly correct function gen_host:

def gen_host(data, group):
    ''' Takes a dictionary. It creates a INI file'''
    config = ConfigParser()
    config.add_section(group)
    for key, value in data.iteritems():
        config.set(group,'{0:s} ansible_host'.format(key),''.join(value['ansible_host']))

    with open('host_test', 'w') as outfile: config.write(outfile)

Adding on to the accepted answer but adapted to Python 3 (can't request an edit):

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(f"[{group}]\n")

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM