「Python3」获取本地代码信息写入aws tag中 -- 整理版来了

「Python3」获取本地代码信息写入aws tag中 -- 整理版来了

五月 15, 2019

此脚本是获取playbook/files/200-204下的fact信息,写入aws web备注,已在国服测试使用
默认执行打印信息,如需导入aws web备注中,打开下面response注释即可
因各个地区可能目录结构和地区、秘钥不一样,需要更改3个地方使用

  1. 更改秘钥credentials.ini
  2. 更改地区local
  3. 更改目录dire

说明: 当服务部署有迁移或合并时,aws实例tag信息跟着变动,手动修改费时又费劲,当当当脚本来了,还是利用aws SDK功能
2个脚本,一个为秘钥配置信息,一个获取本地代码中的服务的信息整理写入aws tag

秘钥配置信息脚本:

1
2
3
4
[aws_cn]
aws_access_key_id=XXX
aws_secret_access_key=XXX
aws_region=XXX

导入脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#此脚本是获取playbook/files/200-204下的fact信息,写入aws web备注,已在国服测试使用
#默认执行打印信息,如需导入aws web备注中,打开下面response注释即可
#因各个地区可能目录结构和地区、秘钥不一样,需要更改3个地方使用
#1. 更改秘钥credentials.ini
#2. 更改地区local
#3. 更改目录dire
import configparser
import boto3
import json
import os

cfg = configparser.ConfigParser()
cfg.read('credentials.ini')
local = 'aws_cn'
dire = 'playbook/register/files/'
session = boto3.session.Session(aws_access_key_id=cfg.get(local, 'aws_access_key_id'),
aws_secret_access_key=cfg.get(local, 'aws_secret_access_key'),
region_name=cfg.get(local, 'aws_region'))
def get_facts(directory):
fact_list = []
for root,dirs,files in os.walk(directory):
for file in files:
fact = os.path.join(root,file)
fo = open(os.path.join(fact))
item = json.loads(fo.read())
facts = {}
facts['hostname'] = file
facts['facts'] = [fact for fact in item['shardsinfo']]
fact_list.append(facts)
fo.close()
return fact_list

def get_aws_info(local):
ec2_resource = session.resource('ec2')
ec2_list = []
for instance in ec2_resource.instances.all():
ec2_server = {}
gamex_server = {}
ec2_Name_index = [i for i, x in enumerate(instance.tags) if x['Key'].find('Name') == 0]
ec2_Service_index = [i for i, x in enumerate(instance.tags) if x['Key'].find('Service') == 0]
ec2_server['hostname'] = instance.tags[ec2_Name_index[0]]['Value']
if ec2_server['hostname'].__contains__('gamex'):
gamex_server['id'] = instance.id
gamex_server['hostname'] = instance.tags[ec2_Name_index[0]]['Value']
gamex_server['service'] = instance.tags[ec2_Service_index[0]]['Value']
ec2_list.append(gamex_server)
return ec2_list

def write_gamex_info():
gamex_list = get_facts(dire)
ec2_list = get_aws_info(local)
gamex_service = []
for ec2_hostname in ec2_list:
ec2_service = {}
for gamex_hostname in gamex_list:
if ec2_hostname['hostname'] == gamex_hostname['hostname']:
ec2_service['id'] = ec2_hostname['id']
ec2_service['service'] = gamex_hostname['facts']
gamex_service.append(ec2_service)
return gamex_service

if __name__ == '__main__':
ec2_client = session.client('ec2')
service_list = write_gamex_info()
for i in service_list:
ami = i['id']
values = i['service']
v = ','.join(values)
print(v)
# response = ec2_client.create_tags(Resources=[ami,],Tags=[{'Key': 'Service','Value': v,},],)
# print(response)