Home > front end >  Get the list of EC2 volumes which doesn't have tags or tags are null
Get the list of EC2 volumes which doesn't have tags or tags are null

Time:01-11

import boto3
client = boto3.client('sns')
def lambda_handler(event, context):
    ec2 = boto3.resource('ec2')
    volume = ec2.volumes.all()
    for vol in volume:
        if vol.tags is not None and ('custName') not in [t['Key'] for t in vol.tags]:
            vol_id = []
            print(vol.id)
            #print(vol.tags)
        elif vol.tags is None:
            print(vol.id)
            #print(vol.tags)
        snsArn = 'SNS ARN'
        vol_id.append(vol.id)
    response = client.publish(
        TopicArn = snsArn,
        Message = "".join('%s' %id for id in vol.id),
        Subject='EC2 missing required-tags',
)
   

This is the code I have created to list down all the EC2 volumes with or without tags. Now, I want to send the output of it through SNS. However, I am only getting the last volume id and not all through SNS. I am new to python and learning, so please assist.

CodePudding user response:

You are initing vol_id in for each volume and Sending wrong object in sendMessage to sns

import boto3
client = boto3.client('sns')
def lambda_handler(event, context):
    ec2 = boto3.resource('ec2')
    volume = ec2.volumes.all()
    vol_id = []
    snsArn = 'SNS ARN'
    for vol in volume:
        if vol.tags is not None and ('custName') not in [t['Key'] for t in vol.tags]:
            print(vol.id)
            vol_id.append(vol.id)
            #print(vol.tags)
        elif vol.tags is None:
            print(vol.id)
            vol_id.append(vol.id)
            #print(vol.tags)
       
    response = client.publish(
        TopicArn = snsArn,
        Message = "".join('%s' %id for id in vol_id),
        Subject='EC2 missing required-tags',
)
  • Related