繁体   English   中英

定义 cloudFormation 脚本时,无法从 lambda function 中的环境访问 SNS_TOPIC_ARN 值

[英]Unable to get access to SNS_TOPIC_ARN value from environment in lambda function when defining a cloudFormation script

这是我的云形成脚本

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs12.x
      Events:
        HelloWorldApi:
          Type: Api
          Properties:
            Path: /
            Method: GET
    Policies:
      - SNSPublishMessagePolicy:
          TopicName: !GetAtt HelloWorldTopic.TopicName
    Environment:
      Variables:
        SNS_TOPIC_ARN: !Ref HelloWorldTopic
  HelloWorldTopic:
    Type: AWS::SNS::Topic
    Properties:
      Subscription:
        - Endpoint: benjamintlee600@gmail.com
          Protocol: email`enter code here`

这是我的 Lambda function:

const aws = require('aws-sdk');
aws.config.update({ region: 'eu-west-2' });
const sns = new aws.SNS({ region: 'us-east-1' });

exports.handler = async function (event, context) {
  console.log('SNS_TOPIC_ARN: ' + process.env.SNS_TOPIC_ARN);
  const params = {
    Message: 'Hello World!',
    Subject: 'SNS Notification from Lambda',
    TopicArn: process.env.SNS_TOPIC_ARN,
  };
  try {
    await sns.publish(params).promise();
    return { statusCode: 200, body: 'Message sent' };
  } catch (err) {
    return { statusCode: 500, body: JSON.stringify(err) };
  }
};

每次我发出 API 请求时,由于某种原因,我都会收到一条错误消息:“无效参数:TopicArn 或 TargetArn 原因:所需参数没有值”。

任何建议将不胜感激。

我注意到模板的几个问题。

Environment and Policies应位于Type下方的Properties下。 目前它的外部Properties

我也相信Policies格式有点错误。 通常它有点像

Policies:
- AWSLambdaExecute
- Version: '2012-10-17' 
  Statement:
    - Effect: Allow
      Action:
        - s3:GetObject
        - s3:GetObjectACL
      Resource: 'arn:aws:s3:::my-bucket/*'

在你的情况下,这将是sns:publish和类似的东西

暂无
暂无

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

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