Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Terraform Outputs as Environment Variables of Lambda function

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

like image 945
Hyvrt Avatar asked Sep 28 '18 03:09

Hyvrt


1 Answers

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

like image 89
Jin Avatar answered Sep 28 '22 08:09

Jin