python - 用于搜索所有正在运行的 EC2 实例的 Lambda 函数,如果不存在则添加标签“名称”,然后将标签添加到它的关联卷?
问题描述
我有一些代码可以将标签添加到所有挂起和正在运行的实例,然后搜索它们的关联卷,并将标签也添加到这些卷中。但是,如果我启动一个根本没有标签的新实例,我会得到一个 KeyError 并且它不起作用。我要做的是:
- 搜索所有正在运行和挂起的 EC2
- 如果实例上不存在“名称”标签,请添加键:“名称”标签以及键:“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": "'Tags'", "errorType": "KeyError", "stackTrace": [" File "/var/task/lambda_function.py", line 38, in lambda_handler\n for tag in instance['标签']:\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']
推荐阅读
- php - 如何在字符串类型的数据库列中插入数组?
- python - 从 csv 文件读取图形时出现问题。不会读取 CSV 文件的标题
- r - 如何使用 dplyr 扩展和插值数据帧中的分组数据,每个组的插值点数量相等?
- html - 使用 nbconvert 时如何更改代码背景颜色?
- php - 如何使用来自数据库的动态输入在 select 语句中声明选定选项?
- java - 如何测试 Hibernate JPA 持久层?
- ios - 在将统一构建集成到现有 xcode 项目中时获取“未找到架构 arm64 的符号”
- java - 如何使用 dcm4che 在 DICOM 中创建新/自定义标签?
- oracle - 某些带有 .PDF 扩展名的文件不可读
- javascript - addEventListener 随机工作,我不知道为什么