用于搜索所有 运行 EC2 实例的 Lambda 函数,如果不存在则添加标签 'Name',然后将标签添加到它的关联卷?
Lambda function to search for all running EC2 instances, add tag 'Name' if not present, and then add tags to it's associated volumes?
我有一些代码可以将标签添加到所有待定和 运行 实例,然后搜索它们的关联卷,并向它们添加标签。但是,如果我启动一个完全没有标签的新实例,我会得到一个 KeyError 并且它不起作用。我想要做的是:
- 搜索所有 运行 和待处理的 EC2
- 如果实例上不存在 'Name' 标签,请添加键:'Name' 标签以及键:'test_key',值:'test_value'.
- 如果键:'Name' 标签确实存在,只需添加键:'test_key',值:'test_value' 到 EC2 的
- 向与 running/pending 个实例关联的所有卷添加标签
代码如下:
#!/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'}
])
如果新实例上有 'Name' 标签,它工作正常,但如果 'Name' 标签不存在,则不起作用。它抛出以下错误:
{
"errorMessage": "'Tags'",
"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']
我有一些代码可以将标签添加到所有待定和 运行 实例,然后搜索它们的关联卷,并向它们添加标签。但是,如果我启动一个完全没有标签的新实例,我会得到一个 KeyError 并且它不起作用。我想要做的是:
- 搜索所有 运行 和待处理的 EC2
- 如果实例上不存在 'Name' 标签,请添加键:'Name' 标签以及键:'test_key',值:'test_value'.
- 如果键:'Name' 标签确实存在,只需添加键:'test_key',值:'test_value' 到 EC2 的
- 向与 running/pending 个实例关联的所有卷添加标签
代码如下:
#!/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'}
])
如果新实例上有 'Name' 标签,它工作正常,但如果 'Name' 标签不存在,则不起作用。它抛出以下错误:
{ "errorMessage": "'Tags'", "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']