Amazon ec2 在boto3中实现EC2及其相关资源的自动标记
作为boto3的新手,我们需要对AWS中的所有资源实现特定的标记,我想从EC2开始。我的要求是,当我们为EC2实例创建具有特定值的名称标记时,将特定标记应用于EC2及其资源(ENI、卷、EIP…)。我确实创建了一个Lambda函数,并配置了一个触发器“CreateTags”。我可以对我试图创建名称标记的实例进行文件归档,但不知道如何使用特定值查询名称和标记,并为其分配特定标记及其资源,需要帮助Amazon ec2 在boto3中实现EC2及其相关资源的自动标记,amazon-ec2,aws-lambda,tags,boto3,Amazon Ec2,Aws Lambda,Tags,Boto3,作为boto3的新手,我们需要对AWS中的所有资源实现特定的标记,我想从EC2开始。我的要求是,当我们为EC2实例创建具有特定值的名称标记时,将特定标记应用于EC2及其资源(ENI、卷、EIP…)。我确实创建了一个Lambda函数,并配置了一个触发器“CreateTags”。我可以对我试图创建名称标记的实例进行文件归档,但不知道如何使用特定值查询名称和标记,并为其分配特定标记及其资源,需要帮助 import json import boto3 ec2 = boto3.resource('ec
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
让我们从头开始。。。我知道您希望使用AWS Lambda函数。您希望“触发”Lambda函数的事件是什么?是否只有在启动AmazonEC2实例时,或者在连接/分离事物时,您希望标记也发生更改?或者,您是否尝试在将标记添加到实例时触发,然后复制这些标记?另一种方法是定期扫描资源并更新丢失的标记,但这不一定会捕获“分离”的资源,这可能会丢失相关的标记?你好,John,定期扫描资源并更新丢失的标记真是个好主意,但唯一的条件是根据名称标记的值添加缺少的标记。这意味着,若名称标签的值为“ABC”,则将这些标签添加到EC2及其资源中。