Python: напишите INI файл для Ansible
Я хотел бы создать простой.INI файл, используя python с точной структурой, т.е.
[win_clones]
cl1 ansible_host=172.17.0.200
cl3 ansible_host=172.17.0.202
Пока это то, что я смог произвести:
[win_clones]
ansible_host = 172.17.0.200
[win_clones]
ansible_host = 172.17.0.202
Я бы хотел:
есть только один [win_clones]
укажите имя cl1/cl3
удалите пробелы, т.е. ansible_host = 172.17.0.200Ниже моих данных (вложенный словарь) и скрипта, который я использую:
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')
Это "INI-подобный" файл, а не INI файл. Вам нужно будет написать его вручную:
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')
Необходимо немного исправить функцию 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)