import json import os import boto3 if __name__ == "__main__": apply_labels_list = json.load(open('labels_aws_apply_labels_list.json', 'r')) for request in apply_labels_list: if request['status']['account_id'] != os.getenv('AWS_ACCOUNT_ID'): continue spec = request['spec'] tags = [] kv_tags = {} for k, v in spec.items(): if k in ["environment", "servicetype", "usedby", "component", "tenant", "project", "cluster"]: tags.append({'Key': k, 'Value': v}) kv_tags[k] = v try: response = None if spec['product'] == 'ec2': client = boto3.client('ec2', region_name=spec['region']) response = client.create_tags( Resources=[ spec['resource_id'], ], Tags=tags ) elif spec['product'] == 'ebs': client = boto3.client('ec2', region_name=spec['region']) response = client.create_tags( Resources=[ spec['resource_id'] ], Tags=tags) elif spec['product'] == 'nlb': elbclient = boto3.client('elbv2', region_name=spec['region']) response = elbclient.add_tags( ResourceArns=[ spec['resource_id'], ], Tags=tags ) elif spec['product'] == 'clb': elbclient = boto3.client('elb', region_name=spec['region']) response = elbclient.add_tags( LoadBalancerNames=[ spec['resource_id'].split('/')[-1], ], Tags=tags ) elif spec['product'] == 'nat': client = boto3.client('ec2', region_name=spec['region']) response = client.create_tags( Resources=[ spec['resource_id'].split('/')[-1], ], Tags=tags ) elif spec['product'] == 'eks': client = boto3.client('eks', region_name=spec['region']) response = client.tag_resource( resourceArn=spec['resource_id'], tags=kv_tags ) else: print(f'unsupported resource {spec["product"]}/{spec["resource_id"]} in region({spec["region"]}') continue print(f'apply tags for {spec["product"]}/{spec["resource_id"]} in {spec["region"]}' f', response: {response}') except Exception as e: print(e) continue