Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get SNS topic ARN inside lambda handler and set permissions to wite to it?

I have two lambda functions defined in serverless.yml: graphql and convertTextToSpeech. The former (in one of the GraphQL endpoints) should write to SNS topic to execute the latter one. Here is my serverless.yml file:

service: hello-world

provider:
  name: aws
  runtime: nodejs6.10

plugins:
  - serverless-offline

functions:
  graphql:
    handler: dist/app.handler
    events:
      - http:
          path: graphql
          method: post
          cors: true
  convertTextToSpeach:
    handler: dist/tasks/convertTextToSpeach.handler
    events:
      - sns:
          topicName: convertTextToSpeach
          displayName: Convert text to speach

And GraphQL endpoint writing to SNS:

      // ... 
      const sns = new AWS.SNS()

      const params = {
        Message: 'Test',
        Subject: 'Test SNS from lambda',
        TopicArn: 'arn:aws:sns:us-east-1:101972216059:convertTextToSpeach'
      }
      await sns.publish(params).promise()
      // ...

There are two issues here:

  1. Topic ARN (which is required to write to a topic) is hardcoded it. How I can get this in my code "dynamically"? Is it provided somehow by serverless framework?

  2. Even when topic arn is hardcoded lambda functions does not have permissions to wrote to that topic. How I can define such permissions in serverless.yml file?

like image 634
user606521 Avatar asked Jan 30 '18 13:01

user606521


1 Answers

1) You can resolve the topic dynamically.

This can be done through CloudFormation Intrinsic Functions, which are available within the serverless template (see the added environment section).

functions:
  graphql:
    handler: handler.hello
    environment:
      topicARN:
        Ref: SNSTopicConvertTextToSpeach
    events:
      - http:
          path: graphql
          method: post
          cors: true
  convertTextToSpeach:
    handler: handler.hello
    events:
      - sns:
          topicName: convertTextToSpeach
          displayName: Convert text to speach

In this case, the actual topic reference name (generated by the serverless framework) is SNSTopicConvertTextToSpeach. The generation of those names is explained in the serverless docs.

2) Now that the ARN of the topic is mapped into an environment variable, you can access it within the GraphQL lambda through the process variable (process.env.topicARN).

  // ... 
  const sns = new AWS.SNS()

  const params = {
    Message: 'Test',
    Subject: 'Test SNS from lambda',
    TopicArn: process.env.topicARN
  }
  await sns.publish(params).promise()
  // ...
like image 129
jens walter Avatar answered Sep 23 '22 15:09

jens walter