Python Lambda函数搜索所有正在运行的EC2实例,添加标记';名称';如果不存在,则向其添加标签';s关联卷?

Python Lambda函数搜索所有正在运行的EC2实例,添加标记';名称';如果不存在,则向其添加标签';s关联卷?,python,amazon-web-services,amazon-ec2,aws-lambda,keyerror,Python,Amazon Web Services,Amazon Ec2,Aws Lambda,Keyerror,我有一些代码可以向所有挂起和运行的实例添加标记,然后搜索它们的关联卷,并向这些实例添加标记。然而,如果我启动了一个没有任何标记的新实例,我会得到一个keyrerror,并且它不起作用。我想做的是: 搜索所有正在运行和挂起的EC2 如果实例上不存在“Name”标记,请添加键:“Name”标记以及键:“test\u key”,值:“test\u value” 如果key:'Name'标记确实存在,只需将key:'test_key',value:'test_value'添加到EC2的 向与正在运行/挂

我有一些代码可以向所有挂起和运行的实例添加标记,然后搜索它们的关联卷,并向这些实例添加标记。然而,如果我启动了一个没有任何标记的新实例,我会得到一个keyrerror,并且它不起作用。我想做的是:

  • 搜索所有正在运行和挂起的EC2
  • 如果实例上不存在“Name”标记,请添加键:“Name”标记以及键:“test\u key”,值:“test\u 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'}
                        ])
    
    如果在新实例上有一个“Name”标记,它可以正常工作,但是如果没有“Name”标记,它就不起作用。它抛出以下错误:

    { “errorMessage”:“标签”, “errorType”:“KeyError”, “stackTrace”:[ “文件“/var/task/lambda_function.py”,lambda_处理程序中的第38行,用于实例['Tags']中的标记:\n” ] }


    我认为这是因为它正在搜索一个标记,但新实例没有标记,因此它会出错。

    我编辑并添加了以下内容,现在它可以工作了。对于标记,我添加了第二个名为mytags2的列表,该列表也有“Name”标记:

    for reservation in instances['Reservations']:
        for instance in reservation['Instances']:
            if 'Tags' in instance:
                ec2.create_tags(
                    Resources = [instance["InstanceId"] ],
                    Tags = mytags)
            elif 'Tags' not in instance:
                ec2.create_tags(
                    Resources = [instance["InstanceId"] ],
                    Tags = mytags2)
    

    然后,我重新运行descripe_实例并将标记添加到卷中。

    如果实例没有标记,则不会有任何
    标记
    字段。因此,您必须检查以下内容:

        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']       
    

    “不起作用”-什么不起作用?什么是错误消息?您的代码尝试添加
    test\u键
    ,即使它已经存在。此外,如果缺少
    Name
    标记,它似乎不会添加该标记。如果创建实例时没有“Name”标记,则它不会向实例或卷添加标记。它在lambda_handler中的第38行出现了错误:{“errorMessage”:“Tags'”,“errorType”:“KeyError”,“stackTrace”:[“File\”/var/task/lambda_function.py\”,用于实例['Tags']:\n“]}中的标记。是的,这是缺少的部分,谢谢!我在实例中添加了if'Tags',执行此操作,如果不在实例中添加了elif'Tags',执行此操作。可以添加标签了。@cdh12没问题。很高兴它成功了:-)