Skip to main content

Amazon Web Services

How to Integrate AWS Lambda with Amazon API Gateway Using Terraform Code

Istock 1194430859

In the most scenario we integrated AWS Lambda with API Gateway to run our application which are written in Python, Node.js, Go, .NET, Java, Ruby, etc.

A Lambda integration traces a path and HTTP method combination to a Lambda function. We can configure the API Gateway to pass the content of the HTTP request as is or to summarize the requested content in a document that includes all the information including headers, resource, path, and method.

1

What is Terraform?

Terraform is an infrastructure as code tool that allows you to build, change, manage and version your infrastructure. It is one of the most popular infrastructure as code (Iac) tools, used to automate infrastructure tasks, and automate the provisioning of your cloud resources. It is opensource. Terraform can manage low-level components like compute, storage, and networking resources, as well as high-level components like DNS entries and SaaS features.

 

What is AWS Lambda?

AWS Lambda is a serverless computing platform provided by AWS where you can upload your code and it is executed automatically using AWS severs.

The concept of serverless computing refers to the idea that you don’t need to maintain or manage your own servers to run certain functions. Which means we can just upload our code (Python, Node.js, Go, .NET, Java, Ruby) and Lambda will manage functions like runtime, scaling, load balancing, and more

 

What is Amazon API Gateway?

API Gateway is a fully managed service that helps developers create APIs to back-end-systems running on Amazon EC2, lambda, or any publicly addressable web service. API Gateway supports RESTful APIs including RESTAPIs, HTTP APIs, as well as web socket APIs.

APIs are able to modify the information in the request and forward it onto something like a Lambda function API Gateway service, which you can use to create application programming interfaces.

 

Pre-Requirements:

  • An AWS account
  • VS code studio
  • Terraform installed on your machine.

 

Workflow of Terraform Code:

To run the terraform script follow the steps below:

Before we begin, we must create modules of IAM roles, Lambda functions and an API Gateway. To do so we need to create separate main, variable, and output files as shown in the workflow. In our Lambda modules we will create our python file which we want to run then create the main, variable, and output files for our main terraform code.

 

|– Integrate lambda with API gateway(directory name)

|      `

|—-modules

|    |– IAM Role

|    |   |– main.tf

|    |   |– outputs.tf

|    |   |– variables.tf

|    |

|    |

|    |– LAMBDA

|    |   |– main.tf

|    |   |– outputs.tf

|    |   |– variables.tf

|    |   |– hello_lambda

|    |   |   hello_lambda.py

|    |–hello_lambda.zip

|     |

|     |

|     |– API GATEWAY

|     |     |– main.tf

|     |      |– outputs.tf

|     |      |– variable.tf

|     |      |

|     |      |

|     | — |– main.tf

|     | —  |– outputs.tf

|     |–   |– terraform.tfvars

|     | —  |– terraform tfstate

Amazon Web Services - Avoid Contact Center Outages: Plan Your Upgrade to Amazon Connect
Avoid Contact Center Outages: Plan Your Upgrade to Amazon Connect

Learn the six most common pitfalls when upgrading your contact center, and how Amazon Connect can help you avoid them.

Get the Guide

|     |     |

`

 

IAM Role Module

Main file of IAM role Module:

We need to create the main file of IAM role modules for the lambda function and API Gateway, which means we will need to dictate the assume role, lambda permission, and lambda execution.

2

Assume_role_policy –The policy that gives an entity permission to assume the role.

Now, we have to provide AWS Lambda permission to the API Gateway by attaching IAM role policy to Lambda execution.

3

aws_lambda_permission – Allowing API Gateway and  AWS Lambda to access  one other.

aws_iam_role_policy _attachment for vpc_access _execution to access vpc with AWS Lambda.

 

Variable File of IAM Role Module:

This is the variable file of the IAM module, in which we have defined the IAM role name, API Gateway arn, Lambda arn, and IAM role arn.

4

Output File of IAM Role Module:

In this file we will need to define the IAM role arn.

5

Lambda Function Module:

The second module that you will need to create is the Lambda function and archive file, which contains the application in which you will need to run the main file of the Lambda module.

 

Write the Python Application:

Let’s call the Python application which we will be running on the Lambda function. For that you will need to:

  1. Create a directory hello_lambda parallel to main.tf
  2. In that directory, create a file hello_lambda.py
  3. Add the following Python script to run:

import json

def lambda_handler(event, context):

# TODO implement

return {     ‘statuscode’ : 200,

‘body’ : json.dumps(‘Hello Lambda’)

}

 

After you have called the Python application, you will need to create a .zip file. The AWS Lambda function need to have code stored in a .zip to correctly upload to the AWS servers. This .zip that we are going to upload will be mentioned in the main.tf code.

 

Main File of Lambda Function Module:

6

aws_lambda_function.KClambda – configures the Lambda function containing your function code. It also sets the runtime to Python3.8, and assigns the handler to the handler function defined in hello_lambda.py.

 

Variable File for Lambda Function Module:

Here you will declare the variables like function name of Lambda, Lambda arn, and IAM role arn for the Lambda function. The resource IAM_role_arn specifies a role which grants the function permission to access AWS services and resources in your account.

7

Output File for Lambda Function Module:

This is the output file of the Lambda function where you declared lambda_arn.

Invoke arn – The arn to invoke the lambda function.

8

 

API Gateway Module:

In this step we will create POST & OPTION method, integrate this method, and deploy it.

API Gateway is an AWS managed service that allows you to create and manage HTTP APIs. It supports integrations with AWS Lambda functions, allowing us to implement an HTTP API using Lambda functions to handle and respond to HTTP requests.

 

Main File of API Gateway Module:

Here we will create the rest_api gateway. rest_API is a collection of resources and methods that are integrated with backend HTTP endpoints, Lambda functions, or other AWS services.

9

In the below diagram, we will encounter content such as:

  • rest_api_id – defines the ID of our associated REST API.
  • stage_name – defines the name of the stage.
  • resource_id – defines the REST API resource ID.
  • http_method-the method which calling associated resource.

10

  • aws_api_gateway_rest_api defines a name for the API Gateway and sets its protocol to HTTP method.
  • aws_api_gateway_integration configures the API Gateway to use your Lambda function
  • aws_api_gateway_deployment – The deployment can then be published to callable endpoints via the aws_api _gateway _stage resource.

 

Variable File of API Gateway Module:

Here we declared the API name and Lambda arn to integrate the API method.

11

Output File of API Gateway Module:

Here we checked the api_arn that we used the execution arn of api_gateway.

execution_arn – The execution ARN to be used in lambda_permission’s source arn when allowing API Gateway to invoke a Lambda function.

12

Main File of Terraform Script:

Here, we need to write a terraform script. We will create a main file where we call the modules, which are the IAM role, Lambda function, and API Gateway.

13

Terraform Tfstate File:

Terraform state file is updated simultaneously when creating a new resource. Tfstate files track all the changes you make like creating, deleting, or updating. It tells what terraform version we are using.

 This is the most important file within terraform, without it the process simply does not work. (All contents in this file are in JSON format.)

 

Run the following command for provisioning:

  • Terraform init: Used to initialize a working directory containing Terraform configuration files.
  • Terraform plan: Checks which resources will be created when deploying terraform apply. For that we used terraform plan.
  • Terraform apply: Deployed  to build up infrastructure.

 

OUTPUT on AWS Console:

Here we see the IAM role is created which was written in our terraform script,

14

Then, we can see the Lambda Function:

15

The API Gateway name “demo-api” is created with POST and OPTION method as we mention in terraform code.

16

 

Conclusion:

This is the final output where we can see  AWS Lambda function is integrated with API Gateway successfully using terraform code. In the first stage of output, we can see the IAM role is created, after which we  see the Lambda Function and API Gateway is created successfully.

 

How can Perficient help you?

Perficient is a certified Amazon Web Services partner with more than 10 years of experience delivering enterprise-level applications and expertise in cloud platform solutions, contact center, application modernization, migrations, data analytics, mobile, developer and management tools, IoT, serverless, security, and more. Paired with our industry-leading strategy and team, Perficient is equipped to help enterprises tackle the toughest challenges and get the most out of their implementations and integrations.

Learn more about our AWS practice and get in touch with our team here!

Thoughts on “How to Integrate AWS Lambda with Amazon API Gateway Using Terraform Code”

  1. Suraj Singh Thakur

    Awesome!! Blog Kunal, Very well explained and written the complete process.

  2. Ajinkya Gadge

    A proper and deeply explained article!!👌

    Many, many congratulations, Kunal, for this gem of an informative blog-post!! 😊😊👍👍💐💐
    Looking forward to reading many more such articles from you in future!
    All the best!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Kunal Choudharkar

Kunal Choudharkar is a Technical Consultant at Perficient with 2.7years of experience in cloud & DevOps services. He is also a Certified AWS Solutions Architect Associate. Kunal is willing to share his knowledge through blogging in the future.

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram