首页 > 解决方案 > 用于搜索所有正在运行的 EC2 实例的 Lambda 函数,如果不存在则添加标签“名称”,然后将标签添加到它的关联卷?

问题描述

我有一些代码可以将标签添加到所有挂起和正在运行的实例,然后搜索它们的关联卷,并将标签也添加到这些卷中。但是,如果我启动一个根本没有标签的新实例,我会得到一个 KeyError 并且它不起作用。我要做的是:

  1. 搜索所有正在运行和挂起的 EC2
  2. 如果实例上不存在“名称”标签,请添加键:“名称”标签以及键:“test_key”,值:“test_value”。
  3. 如果 key: 'Name' 标签确实存在,只需将 key: 'test_key' , value: 'test_value' 添加到 EC2 的
  4. 将标签添加到与运行/挂起实例关联的所有卷

这是代码:

#!/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" ] }

我认为这是因为它正在搜索标签,但新实例没有标签,所以它会出错。

标签: pythonamazon-web-servicesamazon-ec2aws-lambdakeyerror

解决方案


如果实例没有标签,则不会有任何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']       

推荐阅读