gen_inventory.py 2.87 KB
#!/usr/bin/python
# -*- coding: UTF-8 -*-

""""
   generate ansible inventory files from auto-deploy: http://git.yoho.cn/yohoops/auto_deploy/tree/master/scripts/iptable
"""


import json
import os
from subprocess import call
from jinja2 import Environment, PackageLoader
import collections

# clone deploy project to local
HOME = os.path.expanduser("~")
PATH = os.path.join(HOME, ".tmp/auto_deploy")
if os.path.isdir(PATH):
    call("echo 'start to remove local git files'", shell=True)
    call("rm -rf %s" % PATH, shell=True)

call("mkdir -p %s"  % PATH, shell=True)
call("git clone  --recursive git@git.yoho.cn:yohoops/auto_deploy.git  %s" % PATH, shell=True)


# get iptables info from git files.
azs_mappings = {"qcloud": "az1", "qcloudaz2": "az2", "qcloudaz3": "az3"}
host_group = {"yoho_gateway": "java-gateway",
               "yoho_users": "java-users",
               "yohobuy_resources": "java-resources",
               "yohobuy_order" : "java-order",
               "yohobuy_promotion": "java-promotion",
               "yohobuy_product": "java-product",
               "yoho_message": "java-message",
               "yoho_sns": "java-sns",
               "yohobuy_brower": "java-brower",
               "yohobuy_activity": "java-activity",
               "yoho_erp_gateway": "java-erpgateway",
               "yohobuy_wechat":  "java-wechat",
               "yohobuy_union": "java-union",
               "uic": "java-uic"
             }
# all available zone groups
all_groups = {}
for _az in azs_mappings.keys():
    groups = {}
    all_groups[azs_mappings[_az]] = groups
    file = open(os.path.join(PATH, "scripts/iptable/", _az, "app-iptable.sh"),  'r')
    for line in file:
        for deploy_prj_name in host_group.keys():
            if line.strip().startswith(deploy_prj_name):
                 g_hosts = []
                 groups[host_group[deploy_prj_name]] = g_hosts
                 i_1 = line.index("(")
                 i_2 = line.index(")")
                 sub = line[i_1 + 1 : i_2]
                 for user_ip in sub.split("master@"):
                    if user_ip.strip() != '':
                       g_hosts.append(user_ip.strip())


    file.close()

print("get all inventory info success. \n")
print(all_groups)

# generate az inventory files
env = Environment(loader=PackageLoader('inventory'))

for _az in azs_mappings.keys():
    az = azs_mappings[_az]

    # backup old file and open new file
    hosts = os.path.join("./inventories", az, "hosts")
    call("mv %s %s" % (hosts, os.path.join("./inventories", az, "hosts.bak")), shell=True)
    file = open(hosts, 'w')

    # write template, sort the dict by key
    sorted_dict = collections.OrderedDict(sorted(all_groups[az].items(),  key=lambda t: t[0]))
    template = env.get_template('inventory-%s.j2' % az)
    file.write(template.render(groups = sorted_dict ))
    file.close()

print "success generate ansible inventory files ! ."