boto3的新手,我们要求对AWS中的所有资源实施特定的标签,我想从EC2开始。我的要求是在创建具有特定值的EC2实例的名称标签时,将特定标签应用于EC2及其资源(ENI,卷,EIP ..)。我确实创建了Lambda函数,并配置了触发器“ CreateTags”。我可以进入一个阶段,在该阶段可以提交我试图创建Name标签的实例,但是却迷失了如何查询Name和具有特定Value的标签以及如何为其分配特定标签及其资源的需求帮助。
import json
import boto3
ec2 = boto3.resource('ec2')
def lambda_handler(event, context):
print('Event: ' + str(event))
print(json.dumps(event))
# Contain all the identifiers of EC2 resources founds in a given event.
# IDs could be EC2 instances, EBS Volumes, EBS snapshots, ENIs, or AMIs.
ids =[]
try:
region = event['region']
detail = event['detail']
eventname = detail['eventName']
print('region: ' + region)
print('eventName: ' + eventname)
print('detail: ' + str(detail))
if not detail['responseElements']:
print('No responseElements found')
if detail['errorCode']:
print('errorCode: ' + detail['errorCode'])
if detail['errorMessage']:
print('errorMessage: ' + detail['errorMessage'])
return False
if eventname == 'CreateTags':
items = detail['responseElements']['instancesSet']['items']
for item in items:
ids.append(item['instanceId'])
print(ids)
print('number of instances: ' + str(len(ids)))
base = ec2.instances.filter(InstanceIds=ids)
#loop through the instances
for instance in base:
for vol in instance.volumes.all():
ids.append(vol.id)
for eni in instance.network_interfaces:
ids.append(eni.id)
else:
print('Not supported action')
if 'Tags' in ids:
for tags in ids['Tags']:
if tags["Key"] == 'Name':
tag_value = tag["prod-app*"]
print('Tagging resource' + resourceid)
ec2.create_tags(Resources=ids, Tags=[
{'Key': 'Product', 'Value': 'trial1'},
{'Key': 'Compliance', 'Value': 'trial2'}])
print('Done tagging.')
return True
except Exception as e:
print('Something Went wrong: ' + str(e))
return False
我的要求有些相似。我已经将ec2和相关资源标记为错误,但错误。所以我需要可以标记ec2实例及其相关资源的脚本的帮助。该脚本可以在python,aws cli等中使用