'How to get a Terraform object into an AWS Lambda environment

Lambda functions support the environment parameter and make it easy to define a key-value pair. But what about getting an object (defined by a module variable eg) into the function's environment?

Quick example of what I'm trying to accomplish in python 3.7:

Terraform:

# variable definition

variable foo {
  type = map(any)
  default = {
    a = "b"
    c = "d"
  }
}


resource "aws_lambda_function" "lambda" {
  .
  .
  .
  environment {
    foo = jsonencode(foo)
  }
}

and then in my function:

def bar:
  for k in os.environ["foo"]:
     print(k)

Thanks !



Solution 1:[1]

Same question

resource "aws_lambda_function" "test_lambda" {
  filename      = var.filename
  function_name = var.function_name
  role          = var.iam_lambda
  handler       = "lambda_handler"
  source_code_hash = filebase64sha256("lambda_function.zip")

  runtime = "python3.9"

  environment {
    variables = {
      instances = "${var.instances}",
      region = "us-east-2"
    }
  }
} 

lambda_function.zip

import boto3
region = 'region'
instances = ['i-092222222222', 'i-00433333333','i-09b24444444444']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    ec2.start_instances(InstanceIds=instances)
    print('started your instances: ' + str(instances))

How correct define the variables in Python code?

I found a more elegant solution here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1