Dragon B
Dragon B

Reputation: 78

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 !

Upvotes: 4

Views: 2039

Answers (2)

Dmitrii Kalashnikov
Dmitrii Kalashnikov

Reputation: 97

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

Upvotes: 0

Marcin
Marcin

Reputation: 238189

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)

Upvotes: 5

Related Questions