Home > Enterprise >  AWS lambda function not giving correct output
AWS lambda function not giving correct output

Time:01-23

I am new to python using boto3 for AWS. I am creating a lambda function that will return orphaned snapshots list. Code is -

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)))

This returns list of snapshots & tags too in incorrect format.

enter image description here

Surprisingly, when I run same code in another account, it gives lambda function error -

enter image description here

I have created same permissions IAM role. But different results in different accounts is something i am not gettting.

CodePudding user response:

You are printing snapshot object but you want to print id. Second problem is all snapshot do not need to have tags, you need to check if snapshot have tags or not.

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('\n Snapshot ID is :-    '   snapshot.id)
    for snapshot in snapshots:
        if snapshot.volume_id not in volumes:
            osl.append(snapshot.id)
            print('\n Snapshot ID is :-    '   snapshot.id)
            if snapshot.tags:
                for tag in snapshot.tags:
                    if tag['Key'] == 'Name':
                        value = tag['Value']
                        print('\n Snapshot Tags are '  tag['Key']   ", value = "   value)
                        break
    print('Total orphaned snapshots are:-    ' str(len(osl)))
  • Related