简体   繁体   English

通过 SNS 发送 AWS lambda 的输出

[英]Sending the output of AWS lambda through SNS

I have the following code, where I want to send the output of previous function as an SNS email.我有以下代码,我想将上一个函数的输出作为 SNS 电子邮件发送。 However, when I run this I get "[ERROR] NameError: name 'i' is not defined".但是,当我运行它时,我得到“[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.我是 lambda 的新手,所以需要帮助。 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.尝试了上述解决方案,我尝试将 i.instance_id 作为消息正文发送。

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.更新:要在一封电子邮件中发送所有实例 ID,您可以执行以下操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM