简体   繁体   中英

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

Here is my cloud formation 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`

and here is my 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) };
  }
};

Every time I make an API request, for some reason I get an error saying "Invalid parameter: TopicArn or TargetArn Reason: no value for required parameter".

Any advice would be much appreciated.

Few issues with template i noted.

Environment and Policies Should be under Properties just below Type . currently its outside Properties

Also i believe Policies format is kind of wrong. Normally its kind of like

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

In your case this will be sns:publish and things like that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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