The perennial question of how to deploy Terraform and AWS Lambda functions in tandem is finally answered. Learn the same steps that I did, so you can get up-and-running with this technology quickly.
Terraform is a tool that allows users to create, change, and manage infrastructure. This includes AWS Lambda functions. With Terraform, you are able to execute multiple lambda functions in parallel. Read more in detail here: terraform multiple lambda functions.
If you’re going to be constructing a lot of AWS Lambda functions as part of a bigger automation routine, Terraform could be the way to go. Using Terraform to create Lambda functions reduces the need for human labor and helps you to accelerate your automation efforts.
In this article, you’ll learn how to create and execute a Terraform setup to create an AWS Lambda function from scratch!
Let’s get started!
Prerequisites
This article will be a step-by-step guide. If you want to join in, make sure you have the following items:
How to Install Terraform on Windows is a related topic.
- A code editor — While you may work with Terraform configuration files with any text editor, you should have one that understands the HCL Terraform language. Visual Studio (VS) Code is a good place to start.
Constructing a Terraform Configuration
Terraform is a configuration-based infrastructure as code tool that enables you to create, edit, and version infrastructure. Let’s begin this lesson by creating that setup, which will ultimately be used to create an AWS Lambda function.
1. Make a folder called /terraform-lambda-function-demo and move the working directory to it (cd). This folder will hold your configuration file as well as any Terraform-generated files.
mkdir /terraform-lambda-function-demo/terraform-lambda-function-demo/terraform-lambda-function-demo cd /terraform-lambda-function-demo/terraform-lambda-function-demo/terraform-lambda-function-dem
2. In your preferred code editor, copy/paste the following setup and save it as main.tf in the /terraform-lambda-function-demo directory.
The main.tf file produces the following resources:
- An AWS Lambda IAM role grants access to AWS services and resources to the soon-to-be-created function. This role is utilized while constructing the Lambda function as well as when executing or calling it.
- Allows the Lambda function to produce logs and events using an AWS Identity and Access Management (IAM) Policy. The Lambda role will have this policy connected to it.
- The Lambda function — This is the actual function that will be called when it is needed. To launch a Lambda function, you’ll need code and an IAM role.
# Creating IAM role so that Lambda service to assume the role and access other AWS services. resource “aws_iam_role” “lambda_role” { name = “iam_role_lambda_function” assume_role_policy = <<EOF { “Version”: “2012-10-17”, “Statement”: [ { “Action”: “sts:AssumeRole”, “Principal”: { “Service”: “lambda.amazonaws.com” }, “Effect”: “Allow”, “Sid”: “” } ] } EOF } # IAM policy for logging from a lambda resource “aws_iam_policy” “lambda_logging” { name = “iam_policy_lambda_logging_function” path = “/” description = “IAM policy for logging from a lambda” policy = <<EOF { “Version”: “2012-10-17”, “Statement”: [ { “Action”: [ “logs:CreateLogGroup”, “logs:CreateLogStream”, “logs:PutLogEvents” ], “Resource”: “arn:aws:logs:*:*:*”, “Effect”: “Allow” } ] } EOF } # Policy Attachment on the role. resource “aws_iam_role_policy_attachment” “policy_attach” { role = aws_iam_role.lambda_role.name policy_arn = aws_iam_policy.lambda_logging.arn } # Generates an archive from content, a file, or a directory of files. data “archive_file” “default” { type = “zip” source_dir = “${path.module}/files/” output_path = “${path.module}/myzip/python.zip” } # Create a lambda function # In terraform ${path.module} is the current directory. resource “aws_lambda_function” “lambdafunc” { filename = “${path.module}/myzip/python.zip” function_name = “My_Lambda_function” role = aws_iam_role.lambda_role.arn handler = “index.lambda_handler” runtime = “python3.8” depends_on = [aws_iam_role_policy_attachment.policy_attach] }
3. Create a Python file index.py in the /terraform-lambda-function-demo directory and a new folder files in the /terraform-lambda-function-demo directory. This Python script will contain the code that will be executed by the function.
touch index.py mkdir files cd /files
4. Paste the Python code below into the index.py Python script. A Python function called lamda handler is used in the code below. This function makes advantage of event data that is supplied to the Lambda function during execution. The first name and last name will be parsed, and a message response will be returned.
# # # # # # # # # # # # # # # # # # # Declaring the lambda handler Python function using the event parameter def lambda handler(event, context): ‘Hello!’ is the message. event[‘first name’], event[‘last name’]) format(event[‘first name’], event[‘last name’]) ‘message’: message’return’: message’return’: message’return’: message’return
5. In /terraform-lambda-function-demo/terraform-lambda-function-demo/terraform-lambda-function-demo/terraform-lambda-function-demo/terraform-lambda-function-demo/terraform-lam When you run Terraform in the next section, this configuration file informs it to refer to the lambda role and lambda logging resources specified in the main.tf configuration file and send the data to the console.
value = aws iam role.lambda role.name output “lambda role name” “lambda role arn” is the output. value = aws iam role.lambda role.arn aws iam role.lambda role.arn aws iam role.lambda_ value = aws iam policy.lambda logging.arn output “aws iam policy lambda logging arn” value = aws iam policy.lambda logging.arn
6. Create a new file named provider.tf in the /terraform-lambda-function-demo directory and put the following code in it. The Terraform AWS provider is specified in this Terraform configuration file, and it tells Terraform how to communicate with all of the AWS resources you created in the previous phases.
The focus of the lesson will be on resource creation in the US-East-2 area.
region = “us-east-2” provider “aws”
7. Now, open your preferred terminal and use the tree command to check that the folder has all of the essential files.
All Terraform configuration files necessary for the lambda function are shown using the tree command.
Using Terraform to create an AWS Lambda Function
It’s time to start Terraform and construct the AWS Lambda function now that you have the Terraform configuration files ready! Terraform normally employs a three-command technique in order to supply a Terraform configuration:
- init terraform
- strategy for terraforming
- apply terraform
Let’s go through each step one by one.
- Navigate to the terraform-lambda-function-demo directory in a terminal.
cd terraform-lambda-function-demo/terraform-lambda-function-demo/terraform-lambda-function-
- Run the init terraform command in the same directory. The init terraform command initializes the plugins and providers which are required to work with resources.
If everything works properly, the message Terraform has been successfully started should appear in the output, as seen below.
Getting the Terraform up and running
Now, run the strategy for terraforming command. This Terraform command ensures your configuration’s syntax is correct and gives you an overview of which resources will be provisioned in your infrastructure.
If the command was successful, you should see a message in the output that says Plan: “X” to add, “Y” to alter, or “Z” to destroy. Terraform will also show you every AWS resource it proposes to generate.
Running the strategy for terraforming command
Next, run the apply terraform command to provision the AWS Lambda function. When you invoke, apply terraform, Terraform will read the configuration (main.tf) and the other files to compile a configuration. It will then send that configuration to AWS as instructions to build the Lambda function and other components. apply terraform
Running the apply terraform command.
AWS Lambda function verification
Now that you’ve generated the Lambda function using Terraform, make sure it’s there by manually checking the AWS Management Console for the Lambda function.
1. Go to the AWS Management Console in your chosen web browser and log in.
2. In the Console, go to the top-right search box and type in “Lambda,” then choose the Lambda menu option.
Getting started with AWS Lambda
- Click Functions once you’ve arrived at the Lambda page. The My Lambda function should have been successfully constructed.
My Lambda function was successfully constructed.
4. Finally, as seen below, click the Test button to put your Lambda function to the test.
My Lambda function is being tested.
5. After you hit the Test Button for the first time, you will be prompted to configure test event details. These test events will be used as a parameter to run the Python code in the Lambda function that you created earlier in step 4 of Constructing a Terraform Configuration for an AWS Lambda functions section.
The name of the event is Fullname, and the key: value pair is first name: Adam and last name: Lisktek, respectively, in the Configure test event windows below.
Setting up the test events
To test the Lambda function, click the Test button one again. The Lambda function was successfully performed this time, as shown by the following response message: Good day, Adam Listek.
The Lambda function is being used.
Building Your First AWS Lambda Python Function is a related article.
Conclusion
You learnt how to use Terraform to deploy an AWS Lambda function and its components using Terraform in this tutorial.
Building a serverless application using Lambda is simple and enables you to grow as required.
You’re now ready to apply what you’ve learned to additional AWS services and develop powerful applications on top of them.
Terraform is a tool for building, changing, and deploying infrastructure safely and efficiently. Terraform-AWS lambda github is an open source project that allows users to create AWS Lambda functions from Terraform scripts. Reference: terraform-aws lambda github.
Related Tags
- terraform lambda
- terraform aws lambda permission
- terraform aws lambda function
- terraform lambda layers
- terraform aws lambda tutorial