2
votes

I have a CDK stack that creates both a lambda and a SNS topic. The policies are set to allow the lambda to publish to the SNS topic.

I am having a hard time trying to specify the Topic ARN within my lambda runtime code as it is technically not created yet, just in the stack.

How can I reference the Topic ARN in the Lambda code so lambda publishes to the topic? Lambda is written in python. I am using the fromAsset method (https://docs.aws.amazon.com/cdk/api/latest/docs/aws-lambda-readme.html) to specify my lambda runtime code in my stack.

sns = boto3.client('sns')
responce = sns.publish(
  TopicArn="arn would go here --- not sure what to put here w/ no arn",
  Message="my_message"
)
2

2 Answers

4
votes

You can pass your topic ARN as an environment variable in your Lambda

topic = sns.Topic(self, "MyTopic")

lambda.Function(
  self, "MyLambda",
  ...,
  environment={'TOPIC_ARN': topic.topic_arn}
)

and then use it in your runtime code:

sns = boto3.client('sns')
responce = sns.publish(
  TopicArn=os.environ.get('TOPIC_ARN'),
  Message="my message"
)
0
votes

Adding to @jogold's answer, the environment variable can be created in cdk by using arn of the SNS created. It will look like below,

{"topic_arn":sns_topic.topicArn}

topic_arn is the name of the env variable & sns_topic is the reference variable for SNS created by cdk.