AWS Boto 3-无法创建标签,找不到实例ID-不同的区域

时间:2019-02-04 12:17:38

标签: python aws-lambda boto3

我正在尝试使用Lambda函数在多个区域的实例上设置标签:

print instance_ids给我正确的ID

['i-008a4292a5928c85f']

['i-008a4292a5928c85f','i-03253cdbe35bfb1e2']

  instance_ids = []
    launch_date = ""
    launched = ""
    launched1 = ""
    ec = boto3.client('ec2')
    ec2_regions = [region['RegionName'] for region in ec.describe_regions()['Regions']]
    for region in ec2_regions:
     ec = boto3.client('ec2', region_name=region)
     ec2 = boto3.resource('ec2',region_name=region)
     reservations = ec.describe_instances().get('Reservations', []) 

     for reservation in reservations:
      for instance in reservation['Instances']:
         tags = {}
         for tag in instance['Tags']:
             tags[tag['Key']] = tag['Value']
             if tag['Key'] == 'Name':
               name=tag['Value']
         if not 'Owner' in tags or tags['Owner']=='unknown' or tags['Owner']=='Unknown':
              instance_ids.append(instance['InstanceId'])  
              if not 'TerminateOn' in tags:#, create it
                 print  instance_ids
                 ec2.create_tags(Resources=instance_ids ,Tags=[{'Key':'TerminateOn','Value':date_after_month.strftime('%d/%m/%Y')}])

['i-008a4292a5928c85f']位于不同的区域,lambda为此创建标签:

i-03253cdbe35bfb1e2与lambda处于同一区域,尽管lambda抱怨无法找到创建标签的实例,但并未创建该机器的标签

ClientError: An error occurred (InvalidInstanceID.NotFound) when calling the CreateTags operation: The instance ID 'i-008a4292a5928c85f' does not exist

如果手动指定实例ID,没有问题

因此创建后可以放置instance_id而不是列表:

if not 'TerminateOn' in tags:
                  a = "'" + instance['InstanceId'] + "'"
                  #print a
                  ec2.create_tags(Resources=[a] ,Tags=[{'Key':'TerminateOn','Value':date_after_month.strftime('%d/%m/%Y')}])

but getting The ID ''i-008a4292a5928c85f'' is not valid"

1 个答案:

答案 0 :(得分:0)

通过指定实例ID的变量,以这种方式工作(不知道为什么它不会将list作为参数)

if not 'Owner' in tags or tags['Owner']=='unknown' or tags['Owner']=='Unknown':
              #ec2 = boto3.resource('ec2',region_name=region)
              instance_ids.append(instance['InstanceId'])  
              if not 'TerminateOn' in tags:

                  ec2.create_tags(Resources=[instance['InstanceId']] ,Tags=[{'Key':'TerminateOn','Value':date_after_month.strftime('%d/%m/%Y')}])
相关问题