Search code examples
aws-lambdaterraformamazon-sns

how to refer sns arn from terraform code in a lambda python py file?


my lambda python uses SNS topic arn. But this sns arn id is generated from terraform code. Is there way to refer it somehow in python lambda code?

def lambda_handler(event, context):
    try:            
        #some code                  
        publish_vote(vote, voter)

    except:
        #some code
    
    return {'statusCode': 200, 'body': '{"status": "success"}'}

def publish_vote(vote, voter):
    sns = boto3.client('sns', region_name='us-east-1')

    sns.publish(
        TopicArn='arn:aws:sns:us-east-1:025416187662:erjan',
        Message='""',
        MessageAttributes={
            "vote": {
                "DataType": "String",
                "StringValue": vote,
            },
            "voter": {
                "DataType": "String",
                "StringValue": voter,
            }          
        }
    )

SNS terraform code:

resource "aws_sns_topic" "vote_sns" {
  name = "erjan-sns"
}

resource "aws_sns_topic_policy" "vote_sns_access_policy" {
  arn = aws_sns_topic.vote_sns.arn

  policy = data.aws_iam_policy_document.vote_sns_access_policy.json
}

data "aws_iam_policy_document" "vote_sns_access_policy" {
  policy_id = "__default_policy_ID"

  statement {
    #some stuff code 
    }

}


output "sns_arn_erjan" {
  value       = aws_sns_topic.vote_sns.arn
  description = "aws full sns topic"
}

Solution

  • Your terraform code does not have code for creating the lambda function itself. Are you creating it manually? If yes, then first create that as well using terraform. A basic example is mentioned here

    Within the definition, there is an argument for environment. Use that to define your env variables as:

      environment {
        variables = {
          SNS_ARN = aws_sns_topic.vote_sns.arn # Arn from the defined sns resource.
        }
      }
    

    Then refer the same in your python code as:

    import os
    SNS_ARN = os.environ.get("SNS_ARN")
    ...
    

    Alternatively, you could also consider using AWS SAM