Main Page

From My wiki
Jump to navigation Jump to search

How to Manage AWS Lambda Functions with Terraform

Getting proper knowledge about the skills related to serverless computing is crucial in the present scenario of changing cloud computing. This blog will cover AWS Lambda and Terraform and any DevOps engineer or cloud architect will find it useful.

In this case, we will introduce more complicated scenarios of Lambda function updates as well as the maintenance and strengthening of non-variability in serverless systems.

After synchronizing AWS Lambda through the format of IaC - in Terraform, the readers will comprehend how they might enhance the efficiency and pliability in their endeavors at work. Join us on this journey of expanding the knowledge base on Serverless, and changing the way you approach your Cloud servers.

What is AWS Lambda Function in Terraform?

AWS Lambda is a module of services resident in the cloud that allows code to run without needing the user to deal with servers, and it shall scale the code depending on the events incurred. The aws_lambda_function resource is used in Terraform to manage AWS Lambda functions; it enables you to set up the runtime environment for your code, whether Python or Node.js, set the handler method, and configure memory and timeouts, among others. With AWS Lambda and Terraform, one is in a position to automate the process of deploying the function, which also ensures that you have an up-to-date infrastructure or even rollback changes when necessary. Terraform allows writing the code to create the infrastructure, which will vary in different environments but will be version-controlled. To learn more about AWS and its functionalities, check out our AWS Training.

What is AWS Lambda used for?

AWS Lambda is very flexible to use and can be implemented for many different purposes. This makes it more suitable for event-driven apps, data processing, and handling with the business logic.

Here are some of the primary use cases for AWS Lambda:

● Event-Driven Applications: AWS Lambda can be invoked by events such as changes to specific rows in the database utilized, changes to an S3 bucket, or the number of messages in the SQS queue. It makes it appropriate for use in streamlining processes that require real-time processing. ● Web and Mobile Backends: AWS Lambda, by integrating with API Gateway, is made use of to process backend logic for web and/or mobile applications. This setup enables Lambda functions to be invoked through HTTP calls and thus makes it simple to have microservices. ● Machine Learning and Data Processing: Due to Lambda support, A9 is perfect for executing machine learning algorithms or working with big amounts of data. Using AWS Lambda, Python libraries such as NumPy and TensorFlow can easily perform these tasks with relatively smaller time complexity.

With no need to manage servers, AWS Lambda enables businesses to concentrate on codes and functionalities rather than having to constantly worry about the infrastructure.

How to Manage AWS Lambda Functions with Terraform

Terraform simplifies the creation and management of AWS Lambda functions. Below, we outline the steps required to manage an AWS Lambda function using Terraform, from setting up IAM roles to verifying the function's execution.

Prerequisites:

● Terraform Installed: Ensure Terraform is installed on your machine. You can check this by running the command $ terraform -version. ● AWS Account: You must have an active AWS account to deploy Lambda functions using Terraform.

Step-by-Step Guide:

1. Set Up IAM Roles and Policies

For AWS Lambda to be created and managed, proper IAM roles and policies must be assigned to it. These specify the privilege that your lambda function will have in AWS.

Example IAM Role Configuration:

Let’s generate a new file named main. tf and add the following block to define a role that AWS Lambda can assume:

resource "aws_iam_role" "lambda_role" {

 name = "Terraform_Lambda_Function_Role"
 assume_role_policy = <<EOF
 {
   "Version": "2012-10-17",
   "Statement": [
     {
       "Action": "sts:AssumeRole",
       "Principal": {
         "Service": "lambda.amazonaws.com"
       },
       "Effect": "Allow",
       "Sid": ""
     }
   ]
 }

EOF }

This role gives Lambda the necessary permissions to execute the function. Next, create a policy that allows Lambda to write logs to CloudWatch: resource "aws_iam_policy" "lambda_logging_policy" {

 name        = "lambda_logging_policy"
 description = "IAM policy for Lambda logging"
 policy = <<EOF
 {
   "Version": "2012-10-17",
   "Statement": [
     {
       "Action": [
         "logs:CreateLogGroup",
         "logs:CreateLogStream",
         "logs:PutLogEvents"
       ],
       "Effect": "Allow",
       "Resource": "arn:aws:logs:*:*:*"
     }
   ]
 }

EOF }

Attach this policy to the IAM role: resource "aws_iam_role_policy_attachment" "lambda_role_policy_attachment" {

 role       = aws_iam_role.lambda_role.name
 policy_arn = aws_iam_policy.lambda_logging_policy.arn

}

2. Write Your Lambda Code

The next step is to write the code which when triggered will run in the Lambda function. For this example, let’s create a simple Python function:

def lambda_handler(event, context):

   return {
       'statusCode': 200,
       'body': 'Hello from AWS Lambda!'
   }

Save this Python script as index.py in a python directory.

3. Package the Lambda Code

AWS Lambda works such that the function code has to be uploaded in the form of a ZIP file. Use Terraform’s archive_file data source to package your code: data "archive_file" "lambda_zip" {

 type        = "zip"
 source_dir  = "${path.module}/python/"
 output_path = "${path.module}/lambda_function.zip"

}

4. Define the Lambda Function in Terraform

Now that we have the IAM roles, policies, and the function code, it’s time to create the AWS Lambda function. Add the following block to your main.tf: resource "aws_lambda_function" "lambda_function" {

 filename         = data.archive_file.lambda_zip.output_path
 function_name    = "Terraform_Lambda_Function"
 role             = aws_iam_role.lambda_role.arn
 handler          = "index.lambda_handler"
 runtime          = "python3.8"
 memory_size      = 128
 timeout          = 30
 source_code_hash = filebase64sha256(data.archive_file.lambda_zip.output_path)

}


5. Apply Terraform Configuration

Now that the setup is complete, run the following commands to deploy the Lambda function: $ terraform init $ terraform plan $ terraform apply

Terraform will create the necessary IAM roles, package the Lambda code, and deploy the function. Once the process is complete, you can verify the Lambda function in the AWS Management Console.

6. Verify the Function in AWS Console

Navigate to the AWS Lambda service in the AWS console and search for your function (e.g., Terraform_Lambda_Function). You can test the function by creating a test event in the AWS console. Check out our comprehensive guide to AWS interview questions to learn more about them and prepare for job interviews.

7. Monitor with CloudWatch

AWS CloudWatch automatically logs function executions and any errors that occur. You can define a log group using Terraform for easier management: resource "aws_cloudwatch_log_group" "lambda_log_group" {

 name              = "/aws/lambda/Terraform_Lambda_Function"
 retention_in_days = 14

}

Other Useful Terraform Resources for AWS Lambda

aws_lambda_permission: Use this to allow other AWS services, like API Gateway, to invoke your Lambda function.

resource "aws_lambda_permission" "allow_api_gateway" {

 statement_id  = "AllowInvokeAPI"
 action        = "lambda:InvokeFunction"
 function_name = aws_lambda_function.lambda_function.function_name
 principal     = "apigateway.amazonaws.com"

} 1. aws_lambda_alias: Set up aliases to manage multiple versions of your Lambda function.

resource "aws_lambda_alias" "dev_alias" {

 name             = "development"
 function_name    = aws_lambda_function.lambda_function.function_name
 function_version = "$LATEST"

} 2. These resources allow for better flexibility and management when working with AWS Lambda in production environments.

Conclusion

Automating the setup of AWS Lambda functions using the tool called Terraform can be seen as advantageous in many ways; it is automated, repeatable, and consistent. As to AWS Lambda, you can configure it by using Terraform, define IAM roles, and deploy as many functions as you need. This means that it is time efficient and eliminates most of the additional operating costs of the organization. If you are a beginner at AWS and want to learn AWS practically, then it is suggested to register with AWS Training classes to have better knowledge.