Python:为Ansib编写一个INI文件

2024-10-02 00:21:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

[win_clones]
cl1 ansible_host=172.17.0.200
cl3 ansible_host=172.17.0.202

到目前为止,我所能做的就是:

^{pr2}$

我想:

  • 只有一个[win_克隆体]

  • 包括名称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')

Tags: 文件confighostdatagroupansiblewinini
2条回答

需要稍微纠正gen_主机的功能:

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)

这是一个“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')

相关问题 更多 >

    热门问题