Reputation: 31
I have a lambda function that triggers every 24 hours to create an instance based on a specific LaunchTemplate.
import boto3
AWS_REGION = XXXX
EC2_CLIENT = boto3.resource('ec2', region_name=AWS_REGION)
def lambda_handler(event, context):
instance = EC2_CLIENT.create_instances(
LaunchTemplate={
'LaunchTemplateName': 'ingestion-rclone'
},
MinCount=1,
MaxCount=1,
)
I have this source code in my Terraform and it creates it's own ZIP from it.
data "archive_file" "zip_the_python_code" {
type = "zip"
source_dir = "${path.module}/python"
output_path = "${path.module}/python/lambda_function.zip"
depends_on = [aws_launch_template.ingest_server_lt]
}
Do I have any options on how I can populate the 'LaunchTemplateName' or the alternative 'LaunchTemplateId' value with variables from the TerraForm resources before the python get's zipped up?
I've tried something like this but it just take the text as it to the lambda.
LaunchTemplate={
'LaunchTemplateId': '${aws_launch_template.ingest_server_lt.id}'
},
Upvotes: 2
Views: 1400
Reputation: 31
Turns out I didn't have a good command of how Environmental Variables worked with Lambda. This was the missing logic to solve my desired behavior.
In my modules main.tf I had to define an environment block inside my aws_lambda_fucntion to declare a variable for the launchtemplateid.
resource "aws_lambda_function" "ingest_server_lambda" {
function_name = "ingestion-lambda-mockprovider-cac1-dev"
role = "arn:aws:iam::#########:role/service-role/ingestion-ec2-build"
filename = "${path.module}/python/lambda_function.zip"
handler = "lambda_function.lambda_handler"
runtime = "python3.9"
depends_on = [aws_iam_role_policy_attachment.attach_iam_policy_to_iam_role]
source_code_hash = filebase64sha256("${path.module}/python/lambda_function.zip")
environment {
variables = {
EC2_LT_ID = "${aws_launch_template.ingest_server_lt.id}"
}
}
}
With that I could reference it with my Lambda
import boto3
import os
AWS_REGION = XXXXXXXX
EC2_CLIENT = boto3.resource('ec2', region_name=AWS_REGION)
lt_id = os.environ['EC2_LT_ID']
def lambda_handler(event, context):
instance = EC2_CLIENT.create_instances(
LaunchTemplate={
'LaunchTemplateId': lt_id
},
MinCount=1,
MaxCount=1,
)
Works great now.
Upvotes: 1