Home > Software design >  Sending the output of AWS lambda through SNS
Sending the output of AWS lambda through SNS

Time:12-21

I have the following code, where I want to send the output of previous function as an SNS email. However, when I run this I get "[ERROR] NameError: name 'i' is not defined". Can someone help, please or tell me how to do handle this in any other way? I am new to lambda so need help. Also, help me with some good reads to learn.

import boto3
client = boto3.client('sns') 
def lambda_handler(event, context):
  instances = [i for i in boto3.resource('ec2', region_name='us-east-1').instances.all()]
# Print instance_id of instances that do not have a Tag of Key='Owner' and 'Env'
  for i in instances:
    if i.tags is not None and ('Owner') and ('Env') not in [t['Key'] for t in i.tags]:
      print ("missing tags in:- " i.instance_id)
snsArn = 'arn:aws:sns:us-east-1:accountid:required_tags_are_missing'
message = i.instance_id
response = client.publish(
      TopicArn = snsArn,
      Message = message,
      Subject='Hello'
    )

Tried the solution as above, where I have tried to send the i.instance_id as message body.

CodePudding user response:

It should be indented as follows:

import boto3
client = boto3.client('sns') 

def lambda_handler(event, context):
  instances = [i for i in boto3.resource('ec2', region_name='us-east-1').instances.all()]
  # Print instance_id of instances that do not have a Tag of Key='Owner' and 'Env'
  for i in instances:
    if i.tags is not None and ('Owner') and ('Env') not in [t['Key'] for t in i.tags]:
      print ("missing tags in:- " i.instance_id)
      snsArn = 'arn:aws:sns:us-east-1:accountid:required_tags_are_missing'
      message = i.instance_id
      response = client.publish(
        TopicArn = snsArn,
        Message = message,
        Subject='Hello'
      )

Update: To send all the instance ids in one email you can do the following.

import boto3
client = boto3.client('sns') 

def lambda_handler(event, context):
  instances = [i for i in boto3.resource('ec2', region_name='us-east-1').instances.all()]
  # Print instance_id of instances that do not have a Tag of Key='Owner' and 'Env'
  instance_ids = []
  for i in instances:
    if i.tags is not None and ('Owner') and ('Env') not in [t['Key'] for t in i.tags]:
      print ("missing tags in:- " i.instance_id)
      snsArn = 'arn:aws:sns:us-east-1:accountid:required_tags_are_missing'
      instance_ids.append(i.instance_id)
  response = client.publish(
    TopicArn = snsArn,
    Message = ",".join(instance_ids),
    Subject='Hello'
  )
  • Related