Automating Serverless Deployment of Lambda Function with Terraform using Github Actions

Automating Serverless Deployment of Lambda Function with Terraform using Github Actions

Automating Serverless Deployment of Lambda Function with Terraform using Github Actions

Agenda

  1. Push terraform and infra code and python code into repo, in this case it is Github repo..

  2. Import your code to Github.

  3. Add .github/workflows/main.yml file in the workspace.

  4. Update your main.yml file as per need, and run the pipeline.

  • Python code we are using here

# python_files/python.py
import json

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': json.dumps('Hello Terraform !!! LAMBDA here, How you Doing? for Git Actions')
    }

Terraform main.tf file:

This is the most important file for the CI/CD deployment using terraform.

  • Location terraform_aws_lambda/main.tf.

  • Important code snippets:

# Creating a lambda function with code from Zip files, and giving [REQUIRED] role to it
resource "aws_lambda_function" "test_lambda" {
  filename         = "${path.module}/zip/python_files.zip"
  function_name    = var.lambda_function_name.lambda
  role             = aws_iam_role.iam_for_lambda_tf.arn
  handler          = var.handler_name.handle # this is required since package type is a zip
  source_code_hash = data.archive_file.python_zip.output_base64sha256
  runtime          = var.runtime.version
}

Potential problems you might face:

  • In “resource "aws_lambda_function" "test_lambda" {...}”

“handler” is an important tag, the value of which determines whether your code runs on Lambda function or not.

So, stay attentive with it. “handler_name.handle” has a value stored in variable.tf.

How to write “handle” value:

Tips: always write, “filename.function_name” format to make your handler work. In our case it was “python.lambda_handler”.

“python” python file name, “lambda_handler” function name used in the file.

Context

In this captivating blog post, our main focus shines on a remarkable aspect of Github**: the ability to effortlessly deploy serverless infrastructure VIA Github Actions pipeline**s. By combining the powers of Github Actions pipleine and Terraform on AWS, we can swiftly create resources, such as an AWS Lambda, in just a matter of minutes. It's a truly impressive and efficient feat!

Prepare for an exhilarating journey through this blog as we embark on an enthralling quest to craft and deploy our "Hello World" Lambda Function with the seamless aid of Github Actions CI/CD prowess.

Let’s Look at the prerequisite you would need.

Pre-Requisites

Before embarking on our journey, let's ensure we have the essential prerequisites in place:

  • AWS Account: Our expedition involves deploying resources on AWS, so having an AWS account is paramount. If you don't have one yet, you can easily create it by visiting the AWS website.

  • Code Repository: This tutorial assumes that you possess a repository housing your precious Terraform scripts. For this guide, we'll utilize the "AutoScaleupInfra Code Repository" specifically designed for the Lambda Function.

  • Github Account: Finally, to unlock the full potential of our adventure, you'll need a Github account Worry not, Github offers a freemium account that's more than sufficient to begin your journey. You can sign up for a Github account here, and you also have the option to use your Google credentials for seamless registration.

Our Deployment Goal

Welcome to this informative guide! Our goal is to use Terraform scripts to deploy an AWS Lambda function, and we'll make this happen using the capabilities of Github's CI/CD pipelines. By the time you finish reading this tutorial, you'll have the ability to easily deploy your Lambda to your AWS account by simply pushing your code to your repository.

In the upcoming sections, we'll lead you through the process of setting up your Github project smoothly. Then, we'll show you how to create your own CI/CD pipeline. Lastly, we'll share in the joy of successfully deploying your Lambda function. Get ready for an empowering journey ahead!

Now, it's time to embark on our journey. Let's begin!

Creating a new Repository

  • Create the repo with the appropriate name.

Upload local code

  • Now upload your local code to the github repository.

Add “.github/workflows” directory and in that directory add “main.yml” file.

With the following configuration in the “main.yml” file.

# create a file in the folder named ".github/worflows"
# file name should be "main.yml"

name: Terraform AWS

on:
  push:
    branches:
      - master

jobs:
  terraform:
    name: Terraform
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v2

      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ap-northeast-1

      - name: Terraform Init
        run: terraform init

      - name: Terraform Plan
        run: terraform plan

      - name: Terraform Apply
        run: terraform apply -auto-approve

      - name: Terraform Destroy
        run: terraform destroy -auto-approve

Don’t forgot to add your secrets in the variables of Github Actions

Here’s how you add secret variables

  • Navigate to “Settings”

From the side tab, navigate to “security” and then navigate to “secrets and variables” and then “actions”.

Click on “new repository secrets” and add your AWS secrets.

Add your variables here.

Trouble creating variables for AWS to start with.

Here you can get to know more about this.

Next run your pipeline.

Navigate to “Actions” from the top section.

You can see a failed run, due to secrets not set yet, re-run this pipeline, by clicking on it.

All jobs will run successfully now.

Results Snapshots

Github Actions pipeline run.

  • Check your AWS account.

  • Navigate to Lambda functions.

  • Click on the lambda function.

  • Click on the public URL.

  • You can see the resultant python app output.

Pipeline Run Successful

  • On complete run, you can see, your lambda function has been destroyed and everything is cleaned-up, you can change clean-up whenever you need from .yml file.

  • In our situation, we performed a cleanup because it was a test environment, and we wanted to avoid incurring costs for resources not actively in use.

Looking for complete code repository visit

To sum it up, we have experienced the fusion of Github Actions pipeline with Terraform, effortlessly automating the deployment of Lambda Function. This dynamic alliance enhances efficiency, minimizes errors, and propels software delivery to new heights.

We pushed our local code to the repository of Github.

  1. We created a .yml file and pushed it to the same Github repository.

  2. Spin up the lambda function and access the public url for the output.

Did you find this article valuable?

Support Infrasity Blog by becoming a sponsor. Any amount is appreciated!