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
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.
Contact Us