我有一些代码可以将标签添加到所有待处理和正在运行的实例,然后搜索其关联的卷,并向这些实例添加标签。但是,如果我启动一个根本没有标签的新实例,我会得到一个 KeyError 并且它不起作用。我想做的是:
- 搜索所有正在运行和待处理的 EC2
- 如果实例上不存在“Name”标签,请添加键:“Name”标签以及键:“test_key”、值:“test_value”。
- 如果 key: 'Name' 标签确实存在,只需将 key: 'test_key' 、 value: 'test_value' 添加到 EC2 的
- 向与正在运行/待处理的实例关联的所有卷添加标签
这是代码:
#!/usr/bin/env python
import boto3
ec2 = boto3.resource('ec2')
ec2client = boto3.client('ec2')
#-----Define Lambda function-----#
def lambda_handler(event, context):
#-----Check& filter Instances which Instance State is running-----#
instances = ec2client.describe_instances(
Filters=[{
'Name': 'instance-state-name',
'Values': ['pending', 'running']
}]
)
#-----Define dictionary to store Tag Key & value------#
dict={}
mytags = [{
"Key" : "test_key", "Value" : "test_value"
}]
#-----Store Key & Value of Instance ------#
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
ec2.create_tags(
Resources = [instance["InstanceId"] ],
Tags = mytags)
for tag in instance['Tags']:
if tag['Key'] == 'Name':
print ( instance['InstanceId'],tag['Value'])
#ids.append(( instance['InstanceId'],tag['Value']))
dict[instance['InstanceId']]= tag['Value']
#-----Store Key & Value with attached instance ID of all volumes ------#
volumes = ec2.volumes.all()
for volume in volumes:
#-----compare dictionary value Key:InstanceID and volume attached Key:InstanceID ------#
for a in volume.attachments:
for key, value in dict.items():
#-----Add tags to volumes ------#
if a['InstanceId'] == key:
volume.create_tags(Tags =[{
'Key': 'test_key', 'Value': 'test_value'}
])
如果新实例上有“名称”标签,则它可以正常工作,但如果没有“名称”标签,则它不起作用。它抛出以下错误:
{ "errorMessage": "'标签'", "errorType": "KeyError", “堆栈跟踪”: [ "文件 "/var/task/lambda_function.py",第 38 行,在 lambda_handler\n 中,用于实例 ['Tags'] 中的标记:\n" ] }
我认为这是因为它正在搜索标签,但新实例没有标签,所以会出错。
最佳答案
如果实例没有标签,则不会有任何 Tags
字段。所以你必须检查一下:
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
ec2.create_tags(
Resources = [instance["InstanceId"] ],
Tags = mytags)
if 'Tags' in instance:
for tag in instance['Tags']:
if tag['Key'] == 'Name':
print ( instance['InstanceId'],tag['Value'])
#ids.append(( instance['InstanceId'],tag['Value']))
dict[instance['InstanceId']]= tag['Value']
关于python - 用于搜索所有正在运行的 EC2 实例的 Lambda 函数,添加标签 'Name'(如果不存在),然后将标签添加到其关联的卷?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67117220/