6
votes

I ran into a following requirement where I need to pass Terraform outputs or Terraform dynamically created resource ids as environment variables to the Lambda function which is in the same terraform template.

My terraform creates bunch of resources such as Lambda Functions, API Gateways, gateway Methods, gateway resources etc.. I need to send the API Gateway resource id as an environment variable to the Lambda function. Unfortunately I can not put "Depends on " in the Lambda function because it is create cycle dependency.

Anyway we can pass these dynamically created resource ids as input environment variables to lambda function?

Thanks

1

1 Answers

3
votes

You could try utilizing SSM Parameter Store inside your lambda code to avoid hack-y solutions for this problem.

You could have Terraform create a parameter with a unique path that references some variable you supply, and just set this path as an environment variable within the lambda resource declaration, to be referenced within the code.

Terraform side may look something like this:

resource "aws_ssm_parameter" "resource_id" {
  name  = "${var.resource_id_path}" // This is the 'unique key'
  type  = "String"
  value = "${some-apigateway-resource.value}"
}

resource "aws_lambda_function" "my_lambda" {
  ...

  environment {
    variables = {
      ssm_path = "${var.resource_id_path}"
    }
  }
}

Lambda side can look something like this (Python):

import boto3

client = boto3.client('ssm')
response = client.get_parameter(
   Name=os.environ['ssm_path']
   WithDecryption=False
)

Hope this helps