繁体   English   中英

Python:为Ansible写一个INI文件

[英]Python: write an INI file for Ansible

我想使用具有精确结构的 python 生成一个 simple.INI 文件,即

[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- like ”文件,而不是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)

添加到已接受的答案但适用于 Python 3(无法请求编辑):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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