Open In App

Integrating AWS Lambda With Terraform

Terraform is an Infrastructure As Code tool used to provision infrastructure on any cloud platform on the other hand AWS Lambda is a serverless compute service used to run the code without any management of servers by the user. In this guide, I will first discuss what AWS Lambda is. Then I will discuss Terraform. After this, I will walk you through the different steps to create an AWS Lambda function using Terraform.

What is AWS Lambda?

AWS Lambda is a serverless computing service that runs the code without any management of servers by the user. AWS Lambda supports different programming languages like Python, Golang, Java, Node.Js, and many more. The AWS Lambda functions execute the code if there is any specific event occurs or any scheduled time or interval is mentioned. For example, let’s say you are running many EC2 instances. Some of the EC2 instances are not used for a very long period. Running the unnecessary EC2 instances will lead to incurring more costs on the AWS account. You can write a simple code in AWS Lambda that will automatically delete those unused EC2 instances after crossing a certain threshold time. Apart from this Lambda function can automatically scale up or scale down on the amount of traffic it receives. In summary, we can say that AWS Lambda simplifies the development of serverless applications and provides a flexible, scalable, and cost-effective platform for running the code without any code management.



What is Terraform?

Terraform is an Infrastructure As Code tool that is used to create and provision infrastructure on different cloud platforms. Terraform uses a declarative configurational language that is Hashicorp Configurational Language (HCL). It supports multiple cloud platforms like AWS, GCP, Azure, and many more cloud platforms. Using Terraform allows organizations to follow multiple cloud strategies to provision infrastructure. In this way, organizations will not be dependent on a single cloud platform to provision their infrastructure. Apart from this, building complex infrastructure on a cloud platform by using only a console is very hard for infrastructure management. If any type of manual error occurs while creating complex infrastructure, it will be very difficult to pinpoint and fix those errors. If the same complex infrastructure is built using Terraform, the occurrence of such manual errors will be eliminated. This increases the reliability of Terraform to provision the infrastructure on any cloud platform. Overall we can say Terraform has become an important tool for organizations to maintain control, reliability, and scalability on the different cloud platforms.

Pre-requisites

Before moving to the next section make sure that you have installed Terraform on your system. If Terraform is not installed, then follow this detailed geeks for geeks article Setup Terraform On Linux and Windows Machine to install Terraform on your system.



Steps To Create A Lambda Function Using Terraform

Step 1: Mention the cloud provider and region in which you want to create the infrastructure .

provider.tf

provider "aws" {
region = "us-east-1"
}

Step 2: Then write the simple code for lambda function . Here i have used boto3 library to check the number of running and terminated EC2 instances .

check_running_instance.py

import boto3
ec2 = boto3.client('ec2')

def lambda_handler(event, context):
resp = ec2.describe_instances()
running_instances = 0
terminated_instances = 0
# print(resp)
if 'Reservations' in resp:
if len(resp['Reservations']) > 0:
for rsv in resp['Reservations']:
for instance in rsv['Instances']:
id = instance['InstanceId']
ec2_state = instance['State']['Name']
# print(ec2_state)
if ec2_state=='running':
print(f"EC2 Instance having ID : {id} is running!!!")
running_instances+=1
elif ec2_state=='terminated':
print(f"EC2 Instance having ID : {id} is terminated!!!")
terminated_instances+=1
else:
print("There are no running EC2 Instances!!!")
else:
print("There are no running EC2 Instances!!!")
print(f"Total running instances: {running_instances}")
print(f"Total EC2 Instances in terminated state: {terminated_instances}")


Step 3: Create an IAM role for amazon Lambda service . Here i have attached the permissions to AWS Lambda to access EC2.

iam.tf

resource "aws_iam_role" "lambda_iam_role" {
name = "lambda-EC2-IAM-Role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Sid = ""
Principal = {
Service = "lambda.amazonaws.com"
}
},
]
})
}
resource "aws_iam_policy_attachment" "ec2_policy" {
name = "ec2-policy"
roles = [aws_iam_role.lambda_iam_role.name]
policy_arn = "arn:aws:iam::aws:policy/AmazonEC2FullAccess"
}


Step 4: Create a lambda function and here mention the code file name which you want to use with lambda function.

lambda.tf

data "archive_file" "make_zip" {
type = "zip"
source_file = "check_running_instance.py"
output_path = "check_running_instance.zip"
}
resource "aws_lambda_function" "lambda" {
function_name = "check_running_instance"
filename = "${data.archive_file.make_zip.output_path}"
source_code_hash = "${data.archive_file.make_zip.output_base64sha256}"
role = aws_iam_role.lambda_iam_role.arn
handler = "check_running_instance.lambda_handler"
runtime = "python3.10"
}


Step 5: After this execute all the terraform files using the commands below one by one.

terraform init
terraform plan
terraform apply


Step 6: After this go to AWS Lambda on the AWS console . Here you test the code.

After all these steps complete you can use the command below to delete all the resources.

terraform destroy


Conclusion

Here in this article you have first learned about AWS serverless compute service that is AWS Lambda. Then you have understand what is Terraform. Then you have written a simple python code using boto3 library. After this you have written the terraform files which will zip the python code and run this code on AWS cloud platform using the Lambda function.

Integrating AWS Lambda With Terraform-FAQ’s

What is the difference between EC2 and Lambda ?

When you run a code on EC2 instance , you have to basically manage and download all the dependencies that is required to run the code . But in AWS Lambda , you have to just write the code and execute the code without managing any server .

What is the terraform command which checks the terraform syntax ?

The command terraform validate is used to check the terraform syntax .

What is maximum execution time of Lambda function ?

The maximum execution time of a Lambda function is 15 minutes .

What is the basic resource you need to create , before integrating any service to Lambda ?

You have to first create an IAM role for AWS Lambda having permissions for Lambda service to access other AWS services .

What is resource used to create Lambda function using terraform ?

The resource aws_lambda_function is used to create Lambda function using terraform .


Article Tags :