API Gateway invoking Lambda function with Terraform
In this post, we'll setup an API Gateway that invokes Lmabda function that takes an input. We'll do that via Terraform.
We'll follow the guidelines from:
Here is the manifest file, api_gateway.tf:
resource "aws_api_gateway_rest_api" "examplepy" { name = "Serverlessexamplepy" description = "Terraform Serverless Application Example python" } resource "aws_api_gateway_resource" "number" { parent_id = aws_api_gateway_rest_api.examplepy.root_resource_id rest_api_id = aws_api_gateway_rest_api.examplepy.id path_part = "{${var.resource_name}+}" } resource "aws_api_gateway_method" "number" { rest_api_id = aws_api_gateway_rest_api.examplepy.id resource_id = aws_api_gateway_resource.number.id http_method = "GET" authorization = "NONE" } resource "aws_api_gateway_integration" "lambdapy" { rest_api_id = aws_api_gateway_rest_api.examplepy.id resource_id = aws_api_gateway_method.number.resource_id http_method = aws_api_gateway_method.number.http_method integration_http_method = "POST" type = "AWS" uri = aws_lambda_function.examplepy.invoke_arn passthrough_behavior = "WHEN_NO_TEMPLATES" request_templates = { "application/json" = <<EOF { "hour" : $input.params('hour') } EOF } } resource "aws_api_gateway_method" "number_rootpy" { rest_api_id = aws_api_gateway_rest_api.examplepy.id resource_id = aws_api_gateway_rest_api.examplepy.root_resource_id http_method = "GET" authorization = "NONE" } resource "aws_api_gateway_integration" "lambda_rootpy" { rest_api_id = aws_api_gateway_rest_api.examplepy.id resource_id = aws_api_gateway_method.number_rootpy.resource_id http_method = aws_api_gateway_method.number_rootpy.http_method integration_http_method = "POST" type = "AWS" uri = aws_lambda_function.examplepy.invoke_arn # passthrough_behavior = "WHEN_NO_TEMPLATES" # request_templates = { # "application/json" = <<EOF #{"hour" : $input.params('hour')} #EOF # } } resource "aws_api_gateway_method_response" "response_200" { rest_api_id = aws_api_gateway_rest_api.examplepy.id resource_id = aws_api_gateway_resource.number.id http_method = aws_api_gateway_method.number.http_method status_code = "200" response_models = { "application/json" = "Empty"} } resource "aws_api_gateway_integration_response" "IntegrationResponse" { depends_on = [ aws_api_gateway_integration.lambdapy, aws_api_gateway_integration.lambda_rootpy, ] rest_api_id = aws_api_gateway_rest_api.examplepy.id resource_id = aws_api_gateway_resource.number.id http_method = aws_api_gateway_method.number.http_method status_code = aws_api_gateway_method_response.response_200.status_code # Transforms the backend JSON response to json. The space is "A must have" response_templates = { "application/json" = <<EOF EOF } } # Model # resource "aws_api_gateway_model" "MyDemoModel" { # rest_api_id = "${aws_api_gateway_rest_api.examplepy.id}" # name = "usermodel" # description = "a JSON schema" # content_type = "application/json" # # #the payload of the POST request # schema = <<EOF # { # "$schema": "http://json-schema.org/draft-04/schema#", # "title": "usermodel", # "type": "object", # "properties": # { # "callerName": { "type": "string" } # } # # } # EOF #} resource "aws_api_gateway_deployment" "examplepy" { depends_on = [ aws_api_gateway_integration.lambdapy, aws_api_gateway_integration_response.IntegrationResponse, ] rest_api_id = aws_api_gateway_rest_api.examplepy.id stage_name = var.stage } output "base_url" { value = "${aws_api_gateway_deployment.examplepy.invoke_url}/${var.resource_name}" }
Here is another manifest file for our lambda, lambda.tf:
terraform { required_providers { aws = { source = "hashicorp/aws" } } } provider "aws" { region = "us-east-1" } resource "aws_lambda_function" "examplepy" { function_name = "Serverlessexamplepy" # The S3 bucket should already exists s3_bucket = "bogo-terraform-serverless-examplepy" s3_key = "v${var.app_version}/examplepy.zip" # "lambda_function" is the filename within the zip file (lambda_function.py) # and "handler" is the name of the property # under which the handler function was exported in that file. handler = "lambda_function.lambda_handler" runtime = "python3.8" role = aws_iam_role.lambda_execpy.arn } # IAM role which dictates what other AWS services the Lambda function may access. resource "aws_iam_role" "lambda_execpy" { name = "serverless_example_lambdapy" assume_role_policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "lambda.amazonaws.com" }, "Effect": "Allow", "Sid": "" } ] } EOF } resource "aws_lambda_permission" "apigw" { statement_id = "AllowAPIGatewayInvoke" action = "lambda:InvokeFunction" function_name = aws_lambda_function.examplepy.function_name principal = "apigateway.amazonaws.com" # The "/*/*" portion grants access from any method on any resource # within the API Gateway REST API. source_arn = "${aws_api_gateway_rest_api.examplepy.execution_arn}/*/*" }
The variables are defined in variables.tf:
variable "app_version" { default = "1.0.0" } variable "stage" { default = "dev" } variable "resource_name" { default = "number" }
Python code, examplepy/lambda_function.py:
def lambda_handler(event, context): h = float(event['hour']) print(h) return { 'past hours': h }
The code takes an input from a query string (for example, url?hour=10) and simply returns it.
To put the code into a S3 bucket, we need create a bucker, zip and upload it:
$ aws s3 mb s3://bogo-terraform-serverless-examplepy make_bucket: bogo-terraform-serverless-examplepy $ zip examplepy.zip examplepy/lambda_function.py adding: examplepy/lambda_function.py (deflated 21%) $ aws s3 cp examplepy.zip s3://bogo-terraform-serverless-examplepy/ upload: ./examplepy.zip to s3://bogo-terraform-serverless-examplepy/v1.0.0/examplepy.zip
The files are available from Einsteinish/Terraform-AWS-API-Gateway-and-Lambda
Now, we are ready to deploy our lambda and API gateway:
$ terraform init $ terraform apply -var="app_version=1.0.0" --auto-approve base_url = "https://sa7lfskwkb.execute-api.us-east-1.amazonaws.com/dev/number"
We can get a reponse from the following query:
$ curl https://sa7lfskwkb.execute-api.us-east-1.amazonaws.com/dev/number?hour=10 {"past hours": 10.0}
API Gateway:
Lambda:
AWS (Amazon Web Services)
- AWS : EKS (Elastic Container Service for Kubernetes)
- AWS : Creating a snapshot (cloning an image)
- AWS : Attaching Amazon EBS volume to an instance
- AWS : Adding swap space to an attached volume via mkswap and swapon
- AWS : Creating an EC2 instance and attaching Amazon EBS volume to the instance using Python boto module with User data
- AWS : Creating an instance to a new region by copying an AMI
- AWS : S3 (Simple Storage Service) 1
- AWS : S3 (Simple Storage Service) 2 - Creating and Deleting a Bucket
- AWS : S3 (Simple Storage Service) 3 - Bucket Versioning
- AWS : S3 (Simple Storage Service) 4 - Uploading a large file
- AWS : S3 (Simple Storage Service) 5 - Uploading folders/files recursively
- AWS : S3 (Simple Storage Service) 6 - Bucket Policy for File/Folder View/Download
- AWS : S3 (Simple Storage Service) 7 - How to Copy or Move Objects from one region to another
- AWS : S3 (Simple Storage Service) 8 - Archiving S3 Data to Glacier
- AWS : Creating a CloudFront distribution with an Amazon S3 origin
- AWS : Creating VPC with CloudFormation
- AWS : WAF (Web Application Firewall) with preconfigured CloudFormation template and Web ACL for CloudFront distribution
- AWS : CloudWatch & Logs with Lambda Function / S3
- AWS : Lambda Serverless Computing with EC2, CloudWatch Alarm, SNS
- AWS : Lambda and SNS - cross account
- AWS : CLI (Command Line Interface)
- AWS : CLI (ECS with ALB & autoscaling)
- AWS : ECS with cloudformation and json task definition
- AWS Application Load Balancer (ALB) and ECS with Flask app
- AWS : Load Balancing with HAProxy (High Availability Proxy)
- AWS : VirtualBox on EC2
- AWS : NTP setup on EC2
- AWS: jq with AWS
- AWS & OpenSSL : Creating / Installing a Server SSL Certificate
- AWS : OpenVPN Access Server 2 Install
- AWS : VPC (Virtual Private Cloud) 1 - netmask, subnets, default gateway, and CIDR
- AWS : VPC (Virtual Private Cloud) 2 - VPC Wizard
- AWS : VPC (Virtual Private Cloud) 3 - VPC Wizard with NAT
- DevOps / Sys Admin Q & A (VI) - AWS VPC setup (public/private subnets with NAT)
- AWS - OpenVPN Protocols : PPTP, L2TP/IPsec, and OpenVPN
- AWS : Autoscaling group (ASG)
- AWS : Setting up Autoscaling Alarms and Notifications via CLI and Cloudformation
- AWS : Adding a SSH User Account on Linux Instance
- AWS : Windows Servers - Remote Desktop Connections using RDP
- AWS : Scheduled stopping and starting an instance - python & cron
- AWS : Detecting stopped instance and sending an alert email using Mandrill smtp
- AWS : Elastic Beanstalk with NodeJS
- AWS : Elastic Beanstalk Inplace/Rolling Blue/Green Deploy
- AWS : Identity and Access Management (IAM) Roles for Amazon EC2
- AWS : Identity and Access Management (IAM) Policies, sts AssumeRole, and delegate access across AWS accounts
- AWS : Identity and Access Management (IAM) sts assume role via aws cli2
- AWS : Creating IAM Roles and associating them with EC2 Instances in CloudFormation
- AWS Identity and Access Management (IAM) Roles, SSO(Single Sign On), SAML(Security Assertion Markup Language), IdP(identity provider), STS(Security Token Service), and ADFS(Active Directory Federation Services)
- AWS : Amazon Route 53
- AWS : Amazon Route 53 - DNS (Domain Name Server) setup
- AWS : Amazon Route 53 - subdomain setup and virtual host on Nginx
- AWS Amazon Route 53 : Private Hosted Zone
- AWS : SNS (Simple Notification Service) example with ELB and CloudWatch
- AWS : Lambda with AWS CloudTrail
- AWS : SQS (Simple Queue Service) with NodeJS and AWS SDK
- AWS : Redshift data warehouse
- AWS : CloudFormation
- AWS : CloudFormation Bootstrap UserData/Metadata
- AWS : CloudFormation - Creating an ASG with rolling update
- AWS : Cloudformation Cross-stack reference
- AWS : OpsWorks
- AWS : Network Load Balancer (NLB) with Autoscaling group (ASG)
- AWS CodeDeploy : Deploy an Application from GitHub
- AWS EC2 Container Service (ECS)
- AWS EC2 Container Service (ECS) II
- AWS Hello World Lambda Function
- AWS Lambda Function Q & A
- AWS Node.js Lambda Function & API Gateway
- AWS API Gateway endpoint invoking Lambda function
- AWS API Gateway invoking Lambda function with Terraform
- AWS API Gateway invoking Lambda function with Terraform - Lambda Container
- Amazon Kinesis Streams
- AWS: Kinesis Data Firehose with Lambda and ElasticSearch
- Amazon DynamoDB
- Amazon DynamoDB with Lambda and CloudWatch
- Loading DynamoDB stream to AWS Elasticsearch service with Lambda
- Amazon ML (Machine Learning)
- Simple Systems Manager (SSM)
- AWS : RDS Connecting to a DB Instance Running the SQL Server Database Engine
- AWS : RDS Importing and Exporting SQL Server Data
- AWS : RDS PostgreSQL & pgAdmin III
- AWS : RDS PostgreSQL 2 - Creating/Deleting a Table
- AWS : MySQL Replication : Master-slave
- AWS : MySQL backup & restore
- AWS RDS : Cross-Region Read Replicas for MySQL and Snapshots for PostgreSQL
- AWS : Restoring Postgres on EC2 instance from S3 backup
- AWS : Q & A
- AWS : Security
- AWS : Security groups vs. network ACLs
- AWS : Scaling-Up
- AWS : Networking
- AWS : Single Sign-on (SSO) with Okta
- AWS : JIT (Just-in-Time) with Okta
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization