使用无服务器创建lambda函数,我正在尝试使用电子邮件协议创建一个SNS主题。然后,我想将该ARN作为ENV变量传递给Lambda函数。除了附加主题以在创建过程中运行的主题外,我找不到任何文档。感谢任何帮助/示例(我在Python工作)。
要详细说明,以下将创建一个带有SNS主题的函数。:
functions:
dispatcher:
handler: dispatcher.dispatch
events:
- sns: dispatch
想要做"某事"(这不起作用...只是一个例子):
events:
sns:
topicName: thing
subscription:
- endPoint: "myemail@thing.com"
- protocol: "email"
functions:
dispatcher:
handler: dispatcher.dispatch
environment:
SNS_TOPIC: {Ref: ThingSnsTopic}
理想情况下,SNS部分将在函数之外创建,而I可以参考SNS ARN并将其用作Env var
使用无服务器时,您可以在.yml文件中使用环境变量:
myProperty: ${env:MY_ENV_VAR}
如果要将其绑定到SNS,则.yml文件应该看起来像:
service: my-service
provider:
name: aws
runtime: python3.6
functions:
hello:
handler: handler.hello
events:
- sns: ${env:MY_ENV_VAR}
现在,如果您想从lambda函数中访问环境变量,它将取决于您正在编码的语言,但是由于您使用的是Python,它将是:
import os
print("environment variable: " + os.environ['MY_ENV_VAR'])
编辑:在OP的评论之后,我认为我完全理解了问题:
arns是可预测的值。它们几乎是您的区域/用户ID/主题名称的串联,例如:
arn:aws:sns:us-east-1:00000000:aaa
如果您为您的serverless.ym提供了一个环境变量,例如:
provider:
name: aws
stage: ${opt:stage, 'dev'}
environment:
MY_SECRET: ${env:MY_ENV_VAR}
然后,您可以根据可预测的订阅的ARN 您定义的环境变量来编程为该主题创建订阅。
另一个选项是定义.yml文件上的"输出"部分,并使用CloudFormation事件触发lambda,该lambda将根据输出的ARN
i在资源部分中创建SNS主题和订阅,然后在lambda角色中添加策略,该策略可以分配给lambda函数,例如
Resources:
# SNS Topic Resources for email notification
uploadProgressNotificationTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: "The notification topic for upload progress"
TopicName: ${self:custom.uploadProgressNotificationTopicName}
# SNS email subscription for upload completion
emailToSNSUploadProgressNotificationTopicSubscription:
Type: AWS::SNS::Subscription
Properties:
Endpoint: "$subscription_email_here"
Protocol: "email"
TopicArn: ${self:custom.uploadProgressNotificationTopicArn}
然后您的lambda角色资源看起来像下面(个人,我将SNS和Lambda角色资源分为不同的yaml)
Resources:
# Upload lambda roles
UploadLambdaRole:
Type: AWS::IAM::Role
Properties:
RoleName: ${self:custom.uploadLambdaRoleName}
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: AccessUploadProgressNotificationSNSTopic
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "sns:*"
Resource: "${self:custom.uploadProgressNotificationTopicArn}"
最后,您可以在lambda函数中使用此lambda角色,如
upload:
handler: src/handler/upload-handler
role: UploadLambdaRole
...
因此,此功能的作用是您的lambda可以向您的SNS主题发出消息,而SNS会将消息转发到您的电子邮件中。
尝试以下:
MyTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: topic-display-name
TopicName: topic-name
Subscription:
- Endpoint: email_address1@mail.com
Protocol: email
- Endpoint: email_address2@mail.com
Protocol: email