【问题标题】:AWS lambda function not giving correct outputAWS lambda 函数没有给出正确的输出
【发布时间】:2023-01-22 19:31:10
【问题描述】:

我是使用 boto3 for AWS 的 python 新手。我正在创建一个 lambda 函数,它将返回孤立的快照列表。代码是 -

def lambda_handler(event, context):
    ec2_resource = boto3.resource('ec2')
    
    # Make a list of existing volumes
    all_volumes = ec2_resource.volumes.all()
    volumes = [volume.volume_id for volume in all_volumes]
    
    # Find snapshots without existing volume
    snapshots = ec2_resource.snapshots.filter(OwnerIds=['self'])
    
    # Create list of all snapshots
    osl =[]
    
    for snapshot in snapshots:
        if snapshot.volume_id not in volumes:
            osl.append(snapshot)
            print('\n Snapshot ID is :-    '+str(snapshot))
            #snapshot.delete()
            continue
        for tag in snapshot.tags:
          if tag['Key'] == 'Name':
              value=tag['Value']
              print('\n Snapshot Tags are:- '+str(tag))
              break
    print('Total orphaned snapshots are:-    '+str(len(osl)))

这也会以不正确的格式返回快照和标签列表。

令人惊讶的是,当我在另一个帐户中运行相同的代码时,它会给出 lambda 函数错误 -

我创建了相同权限的 IAM 角色。但不同账户的不同结果是我没有得到的。

【问题讨论】:

    标签: amazon-web-services aws-lambda boto3


    【解决方案1】:

    您正在打印 snapshot 对象,但您想打印 id。 第二个问题是所有快照不需要tags,你需要检查快照是否有tags

    def lambda_handler(event, context):
        ec2_resource = boto3.resource('ec2')
        
        # Make a list of existing volumes
        all_volumes = ec2_resource.volumes.all()
        volumes = [volume.volume_id for volume in all_volumes]
        
        # Find snapshots without existing volume
        snapshots = ec2_resource.snapshots.filter(OwnerIds=['self'])
        
        # Create list of all snapshots
        osl =[]
        
        for snapshot in snapshots:
            if snapshot.volume_id not in volumes:
                osl.append(snapshot.id)
                print('
     Snapshot ID is :-    ' + snapshot.id)
                #snapshot.delete()
                continue
            if snapshot.tags:
                for tag in snapshot.tags:
                    if tag['Key'] == 'Name':
                        value=tag['Value']
                        print('
     Snapshot Tags are '+ tag['Key'] + ", value = " + value)
                        break
        print('Total orphaned snapshots are:-    '+str(len(osl)))
    

    【讨论】:

      猜你喜欢
      • 2013-07-30
      • 1970-01-01
      • 2013-10-23
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多