Create a AWS Lambda function using Terraform and Python
Introduction
In this article we’ll be creating a very simple AWS lambda function with terraform.
AWS Lambda
AWS lambda is a serverless service from AWS that let you run functions in many different languages without configuring servers, networking and so on…
Why Python?
Python is a very common way for infrastructure automation. Automations with Python and Boto3 is a largely used choice probably because the amount off examples available .
Lets Code
First of all, will be creating a folder separated for aws lambda called “lambda” and inside it, create three files: “cloudwatch.tf”, “iam.tf”, “lambda.tf”.
Creating IAM role
We’ll start from the IAM role and policies. This will define what your function will be able to access and perform inside your AWS account.
Inside the “iam.tf” file, we’ll define the AIM policies and role for our function. For this example we’ll keep it very simple.
Fist create the iam policy document with the code bellow:
data "aws_iam_policy_document" "lambda_assum_role_policy"{
statement {
effect = "Allow"
actions = ["sts:AssumeRole"] principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
}
}
Than we add a iam role that assume hat policy document:
resource "aws_iam_role" "lambda_role" {
name = "lambda-lambdaRole-waf"
assume_role_policy = data.aws_iam_policy_document.lambda_assume_role_policy.json
}
This is a very simple policy, but it can run the “Hello Worl” example.
Create the Lambda function
Now it’s time to create our python code. For this we’ll create a folder “./code” and create a file named lambda_function.py
import boto3def lambda_handler(event, context):
result = "Hello World"
return {
'statusCode' : 200,
'body': result
}
Nothing special here, this code just return a “Hello World” with a 200 status code.
Now that we have our Python function it’s time to code our “lambda.tf”.
Let’s create the archive file from the “lambda_function.py”, this block of code creates an .zip file to send to AWS Lambda.
Insert this code in the begining of the file to “create archive_file” data:
data "archive_file" "python_lambda_package" {
type = "zip"
source_file = "${path.module}/code/lambda_function.py"
output_path = "nametest.zip"
}
Note that here I used “${path.module}” to get the module path, if you are not using module, just get the path to “lambda_function.py”.
Than create the “aws_lambda_function” resource:
resource "aws_lambda_function" "test_lambda_function" {
function_name = "lambdaTest"
filename = "nametest.zip"
source_code_hash = data.archive_file.python_lambda_package.output_base64sha256
role = aws_iam_role.lambda_role.arn
runtime = "python3.6"
handler = "lambda_function.lambda_handler"
timeout = 10
}
Create the trigger with cloudwatch event
In this example the python script will run periodically using Event Bridge with cloudwatch events.
First lets create “aws_cloudwatch_event_rule” that we will use on the event target.
Insert this block of code on “cloudwatch.tf”:
resource "aws_cloudwatch_event_rule" "test-lambda" {
name = "run-lambda-function"
description = "Schedule lambda function"
schedule_expression = "rate(60 minutes)"
}
Now create “aws_cloudwatch_event_target” to run the function using the rule created above:
resource "aws_cloudwatch_event_target" "lambda-function-target" {
target_id = "lambda-function-target"
rule = aws_cloudwatch_event_rule.test-lambda.name
arn = aws_lambda_function.test_lambda_function.arn
}
Now let’s give permission to “lambda-function-target” to run the AWS lambda function with this code:
resource "aws_lambda_permission" "allow_cloudwatch" { statement_id = "AllowExecutionFromCloudWatch"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.test_lambda_function.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.test-lambda.arn
}
Run and test
At this moment your code must be very similar to this.
Now apply the code and go to the amazon interface to see if everything is working fine.
Go to Lambda panel:
Now click on the function and go to “monitor”:
Conclusion
We’ve created a very simple function on this example, the next step is to create a more advanced script. The permissions that we set on this example is very limited, if we want to access any resourse on AWS we need to add permission on the “iam.tf” file.
On this repository I hope to add more examples : https://github.com/HaissamHammoud/terraform-examples
Hope it helps