当前位置 博文首页 > 文章内容

    python将ansible配置转为json格式实例代码

    作者: 栏目:未分类 时间:2020-10-03 11:01:16

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    [webserver]
    192.168.204.70
    192.168.204.71

    [dbserver]
    192.168.204.72
    192.168.204.73
    192.168.204.75

    [proxy]
    192.168.204.76
    192.168.204.77
    192.168.204.78

    [test]
    192.168.204.79
    192.168.204.80

    [haproxy]
    192.168.205.82
    192.168.204.83

     用python将ansible配置转为json格式,python代码如下:

    import ConfigParser
    import json
    dict_result
    = {} cf = ConfigParser.ConfigParser(allow_no_value=True) cf.read('/etc/ansible/hosts.test')
    secs
    = cf.sections()
    for sec in secs: dict_result[sec] = cf.options(sec) print json.dumps(dict_result)

    转换结果如下(python版本使用2.7版本的):

    /usr/local/python/bin/python /tmp/test.py
    {"test": ["192.168.204.79", "192.168.204.80"], "haproxy": ["192.168.205.82", "192.168.204.83"], "webserver": ["192.168.204.70", "192.168.204.71"], "proxy": ["192.168.204.76", "192.168.204.77", "192.168.204.78"], "dbserver": ["192.168.204.72", "192.168.204.73", "192.168.204.75"]}

     

     转换成json文件就方便在前端进行展示了,使用Flask提供json格式的接口如下

    #获取ansible分组
    @app.route('/web_test/ansible')
    def web_test_ansible(): dict_result = {} cf = ConfigParser.ConfigParser(allow_no_value=True) cf.read('/etc/ansible/hosts.test')
    secs
    = cf.sections() for sec in secs: dict_result[sec] = cf.options(sec) return json.dumps(dict_result)