使用AWS Lambda函数来触发SNS主题在S3上传时。

3
我是一名有用的助手,可以进行文本翻译。

我对SNS和Lambda还比较陌生。我已成功创建了一个SNS主题,并能够发送文本消息。我设置了一个S3事件,当上传文件时触发。但是,我想更改该消息的文本内容,因此从蓝图中创建了一个Lambda函数,该函数应该向SNS主题发送消息。

以下是设计师的截图

Here is a screenshot of the Designer

这是我正在使用的蓝图代码:
from __future__ import print_function

import json
import urllib
import boto3

print('Loading message function...')


    def send_to_sns(message, context):
    
        # This function receives JSON input with three fields: the ARN of an SNS topic,
        # a string with the subject of the message, and a string with the body of the message.
        # The message is then sent to the SNS topic.
        #
        # Example:
        #   {
        #       "topic": "arn:aws:sns:REGION:123456789012:MySNSTopic",
        #       "subject": "This is the subject of the message.",
        #       "message": "This is the body of the message."
        #   }
    
        sns = boto3.client('sns')
        sns.publish(
            TopicArn=message['arn:aws:sns:MySNS_ARN'],
            Subject=message['File upload'],
            Message=message['Files uploaded successfully']
        )
    
        return ('Sent a message to an Amazon SNS topic.')

当测试Lambda函数时,我收到以下错误:
Response:
{
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      25,
      "send_to_sns",
      "TopicArn=message['arn:aws:sns:MySNS_ARN'],"
    ]
  ],
  "errorType": "KeyError",
  "errorMessage": "'arn:aws:sns:MySNS_ARN'"
}

Request ID:
"7253aa4c-7635-11e8-b06b-838cbbafa9df"

Function Logs:
START RequestId: 7253aa4c-7635-11e8-b06b-838cbbafa9df Version: $LATEST
'arn:aws:sns:MySNS_ARN': KeyError
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 25, in send_to_sns
    TopicArn=message['arn:aws:sns:MySNS_ARN'],
KeyError: 'arn:aws:sns:MySNS_ARN'

END RequestId: 7253aa4c-7635-11e8-b06b-838cbbafa9df
REPORT RequestId: 7253aa4c-7635-11e8-b06b-838cbbafa9df  Duration: 550.00 ms Billed Duration: 600 ms     Memory Size: 128 MB Max Memory Used: 30 MB  

我不确定我理解出了什么问题,希望能得到帮助!谢谢!
2个回答

1
你的代码似乎来自一个旧的AWS步骤函数手册,与你的用例不相关。
当Amazon S3发送“事件通知”时,它包含以下信息(来自Event Message Structure - Amazon Simple Storage Service):
{  
   "Records":[  
      {  
         "eventVersion":"2.0",
         "eventSource":"aws:s3",
         "awsRegion":"us-east-1",
         "eventTime":The time, in ISO-8601 format, for example, 1970-01-01T00:00:00.000Z, when S3 finished processing the request,
         "eventName":"event-type",
         "userIdentity":{  
            "principalId":"Amazon-customer-ID-of-the-user-who-caused-the-event"
         },
         "requestParameters":{  
            "sourceIPAddress":"ip-address-where-request-came-from"
         },
         "responseElements":{  
            "x-amz-request-id":"Amazon S3 generated request ID",
            "x-amz-id-2":"Amazon S3 host that processed the request"
         },
         "s3":{  
            "s3SchemaVersion":"1.0",
            "configurationId":"ID found in the bucket notification configuration",
            "bucket":{  
               "name":"bucket-name",
               "ownerIdentity":{  
                  "principalId":"Amazon-customer-ID-of-the-bucket-owner"
               },
               "arn":"bucket-ARN"
            },
            "object":{  
               "key":"object-key",
               "size":object-size,
               "eTag":"object eTag",
               "versionId":"object version if bucket is versioning-enabled, otherwise null",
               "sequencer": "a string representation of a hexadecimal value used to determine event sequence, 
                   only used with PUTs and DELETEs"            
            }
         }
      },
      {
          // Additional events
      }
   ]
}

你可以访问触发事件的文件信息。例如,这个Lambda函数将消息发送到SNS队列:
import boto3

def lambda_handler(event, context):

    bucket = event['Records'][0]['s3']['bucket']['name']
    key =    event['Records'][0]['s3']['object']['key']

    sns = boto3.client('sns')
    sns.publish(
        TopicArn = 'arn:aws:sns:ap-southeast-2:123456789012:stack',
        Subject = 'File uploaded: ' + key,
        Message = 'File was uploaded to bucket: ' + bucket
    )

然而,由于您想要发送短信,您实际上可以绕过需要SNS主题的步骤,直接发送短信:

import boto3

def lambda_handler(event, context):

    bucket = event['Records'][0]['s3']['bucket']['name']
    key =    event['Records'][0]['s3']['object']['key']

    sns = boto3.client('sns')
    sns.publish(
        Message = 'File ' + key + ' was uploaded to ' + bucket,
        PhoneNumber = "+14155551234"
    )

使用AWS Lambda中的测试功能是编写此类代码最简单的方法。它可以模拟来自各种来源(如Amazon S3)的消息。实际上,这就是我测试上述函数的方式 - 我编写代码并使用测试功能来测试代码,而无需离开Lambda控制台。

非常感谢。我也找到了一个可行的NodeJs示例,现在在这里发布它。 - Meisold

0
我找到了一个可用的NodeJs示例:
console.log('Loading function');

var AWS = require('aws-sdk');  
AWS.config.region = 'us-east-1';

exports.handler = function(event, context) {  
    console.log("\n\nLoading handler\n\n");
    var sns = new AWS.SNS();

    sns.publish({
        Message: 'File(s) uploaded successfully',
        TopicArn: 'arn:aws:sns:_my_ARN'
    }, function(err, data) {
        if (err) {
            console.log(err.stack);
            return;
        }
        console.log('push sent');
        console.log(data);
        context.done(null, 'Function Finished!');  
    });
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接