4

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 !

2
  • 1
    How did it go? Still unclear what you can do? Commented Jan 15, 2022 at 7:58
  • The task is currently on hold, I'll definitely make an update once i start working on it and find a solution! Commented Jan 17, 2022 at 10:49

2 Answers 2

5

In python, you will have to get json string and convert it to dict:

import json

def bar:
  for k in json.loads(os.environ["foo"]):
     print(k)
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

They're placed into the runtime environment by the terraform's environment and have to be pulled from the environment by python's os.environ Also, terraform should jsonencode and python should json.loads them. Read the answer
Thank you, but an example will be very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.