[英]AWS - How to pass ARN from cloud formation template to aws lambda function
I have a AWS lambda which sends notification to SNS topic.我有一个向 SNS 主题发送通知的 AWS lambda。
Lambda Function Lambda Function
def send_sns_notification(message):
sns = boto3.client('sns')
response = sns.publish(
TopicArn='arn:aws:sns:ca-central-1:xxxxx',
Message=message,
MessageAttributes={
'AWS.SNS.SMS.SenderID': {
'DataType': 'String',
'StringValue': 'Airflow'
},
'AWS.SNS.SMS.SMSType': {
'DataType': 'String',
'StringValue': 'Transactional'
}
}
)
And we use cloud formation template to deploy SNS Topic
, AWS Lambda
and SNS Subscription
.我们使用云形成模板来部署
SNS Topic
、 AWS Lambda
和SNS Subscription
。 How do I access the ARN for the topic created through CloudFormation.如何访问通过 CloudFormation 创建的主题的 ARN。
Cloud Formation Template云形成模板
Lambda:
Type: AWS::Serverless::Function
Properties:
Description: sends sns notification if dag in airflow fails
FunctionName: "airflow-notification"
Handler: send_sns_notification.py
Runtime: python3.6
ReservedConcurrentExecutions: !Ref AWS::NoValue
Role: !FindInMap [EnvVariables, Parameters, LambdaRole]
VpcConfig:
SecurityGroupIds:
- !FindInMap [EnvVariables, Parameters, VPCSecurityGroupId]
SubnetIds:
- !FindInMap [EnvVariables, Parameters, VPCSubnetId1]
- !FindInMap [EnvVariables, Parameters, VPCSubnetId2]
SNSTopic:
Type: AWS::SNS::Topic
Properties:
TopicName: !FindInMap [EnvVariables, Parameters, SNSTopicName]
DisplayName: airflow
KmsMasterKeyId: !FindInMap [EnvVariables, Parameters, SNSCMK]
SNSSubscription:
Type: AWS::SNS::Subscription
Properties:
Endpoint: gaurangnshah@gmail.com
Protocol: email
TopicArn: !Ref 'SNSTopic'
Pass the ARN in as an environment variable.将 ARN 作为环境变量传入。
Lambda:
Type: AWS::Serverless::Function
Properties:
Description: sends sns notification if dag in airflow fails
FunctionName: "airflow-notification"
Handler: send_sns_notification.py
Runtime: python3.6
ReservedConcurrentExecutions: !Ref AWS::NoValue
Role: !FindInMap [EnvVariables, Parameters, LambdaRole]
VpcConfig:
SecurityGroupIds:
- !FindInMap [EnvVariables, Parameters, VPCSecurityGroupId]
SubnetIds:
- !FindInMap [EnvVariables, Parameters, VPCSubnetId1]
- !FindInMap [EnvVariables, Parameters, VPCSubnetId2]
Environment:
Variables:
TopicArn: !Ref 'SNSTopic'
Alternative, approach is as follows;替代方法如下;
account_id = boto3.client('sts').get_caller_identity().get('Account')
currentRegion = os.environ['AWS_REGION']
# write logic to define SNS_TOPIC variable, you can keep/form it from environment variables or hardcode or other suitable alternative. Here, SNS_TOPIC will hold only name of the SNS Topic
Finally, set/form value for TopicArn using one of the following statements;最后,使用以下语句之一设置/形成 TopicArn 的值;
TopicArn = ":".join(["arn", "aws", "sns", currentRegion, account_id, SNS_TOPIC])
OR或者
TopicArn= ":".join(["arn:aws:sns:ca-central-1",SNS_TOPIC])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.