AWS Lambda Terraform
Welcome, in this tutorial, we will understand how to create AWS lambda using terraform scripting language.
1. Introduction to AWS Lambda
AWS Lambda is a serverless computing service that allows developers to launch the resources without thinking about the infrastructure problem. With serverless computing in place, developers need to focus on their code and not worry about which AWS resource to launch, or how to manage them. AWS Lambda executes the backend code and AWS automatically manages the AWS resources.
1.1 How does lambda work?
To work lambda a developer have the push the code to the lambda and all the other sources like instance, monitoring, networking, and security are automatically taken care of and managed by AWS. Important aspects from lambda working are –
- Function
- Event source – Helps to trigger the user-created function
- Log streams – Automatically monitor the function and report the results on cloud watch. For application, logs can be checked under log groups in the cloud watch
2. Terraform
Terraform is an open-source tool developed by HashiCorp for building, changing, and versioning the infrastructure safely and efficiently. It is used to manage the infrastructure of the popular cloud service providers and custom in-house solutions. It helps manage both low-level (Compute, Storage, Networking, etc.) and high-level components (such as SaaS, DNS, etc.) Terraform deployment automation is divided into different sections i.e.:
- IaaC – IaaC is popularly known as the Infrastructure as a Code wherein the infrastructure is described using a high-level configuration syntax. This allows a blueprint of the infrastructure which can be deployed, versioned, and shared for re-use
- Execution Plans – Terraform has a planning step where it generates an execution plan. The execution plan tells the administrator what Terraform will do once applied and helps to avoid any surprises when it creates the infrastructure
- Resource Graph – Terraform builds a graph of all the resources and parallelizes the creation and modification of non-dependent resources. This offers insights into learning the dependencies in their infrastructure
- Change Automation – Terraform allows to apply of complex changesets to the infrastructure with minimal human intervention
2.1 Steps
To create the infrastructure via the Terraform scripts following commands need to be executed in a sequence. However, details and actions may differ between workflows.
terraform init
– Initializing the new or existing terraform configurationterraform plan
– Generate the execution plan from the resources specified in the fileterraform apply
– Create the infrastructure from the resources specified in the fileterraform destroy
– Destroy the created infrastructure
3. AWS Lambda Terraform
To start with the creation of AWS Lambda I am hoping that you’re aware of the basic concepts for AWS lambda and Terraform. Now let us, deep-dive, into the programming stuff required for this tutorial.
3.1 Creating the hello world file
To being with this tutorial let us create an index file responsible to print the console log when the lambda is run successfully. Make note that for this tutorial I’ll be creating the nodejs based aws lambda function.
index.js
// hello world nodejs application running on aws environment exports.handler = async (event, context, callback) => { console.log('Hello world!'); callback(null, 'done'); }
3.2 Creating lambda terraform file
Once the index file is created in sector3.1 let us make an implementation file that will refer to the index file for deploying the lambda function.
lambda.tf
# simple aws lambda example in terraform # uses index.js file in the same directory variable "aws_access_key" { type = string description = "cli user access key" default = "YOUR_AWS_ACCESS_KEY" } variable "aws_secret_key" { type = string description = "cli user secret key" default = "YOUR_AWS_SECRET_KEY" } variable "aws_region" { type = string description = "lambda deployment region" default = "ap-south-1" } data "archive_file" "lambda_zip" { type = "zip" source_file = "index.js" output_path = "lambda_function.zip" } resource "aws_iam_role" "iam_for_lambda_tf" { name = "iam_for_lambda_tf" description = "role for lambda" /* jsonencode better than EOF. EOF breaks the new terraform code. */ assume_role_policy = jsonencode({ "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "lambda.amazonaws.com" }, "Effect": "Allow", "Sid": "" } ] }) } resource "aws_lambda_function" "test_lambda" { filename = "lambda_function.zip" function_name = "test_lambda" role = "${aws_iam_role.iam_for_lambda_tf.arn}" handler = "index.handler" source_code_hash = "${data.archive_file.lambda_zip.output_base64sha256}" runtime = "nodejs14.x" }
Remember to create the provider file before you go ahead and deploy this sample code in the aws environment. I am skipping this for brevity. In case you’re interested to see how a provider file looks please go through this tutorial at the javacodegeeks website.
4. Code run & demo
Navigate to the project directory containing the above scripts and open the terminal. Execute the below commands in the respective order within the directory.
Commands
-- step1: initializing the new or existing terraform configuration -- terraform init -- step2: generating the execution plan -- terraform plan -- step3: building the infrastructure -- -- auto-approve flag skips interactive approval of the plan before applying terraform apply --auto-approve -- step4: destroying the infrastructure -- -- auto-approve flag skips interactive approval of the plan before applying terraform destroy --auto-approve
Once these scripts are executed successfully head over to the aws console to confirm that the required resources such as iam role and lambda function are created successfully.
That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!
5. Summary
In this section, you learned the following:
- Introduction to AWS Lambada and terraform
- Simple application to understand aws lambda and terraform scripting language
You can download the source code from the Downloads section.
6. Download the Project
This was a tutorial to under the aws lambda using the terraform scripting language.
You can download the full source code of this example here: AWS Lambda Terraform