Streamlining AWS API Gateway with Network Load Balancer using CloudFormation
Tags: aws, network, api, devops
Published: 2024-02-03 19:15:23

Introduction:

AWS CloudFormation is a powerful tool that enables users to automate the provisioning and management of AWS infrastructure. In this blog post, we will explore how to set up an AWS API Gateway with a Network Load Balancer (NLB) using CloudFormation. This configuration is particularly useful when you want to distribute incoming API traffic across multiple Amazon EC2 instances for improved availability and fault tolerance.

Prerequisites:

AWS Account: Ensure you have an active AWS account with the necessary permissions to create resources using CloudFormation.

Basic Understanding: Familiarity with AWS services such as API Gateway, EC2, NLB, and CloudFormation is beneficial.

CloudFormation Template:

Let's start by creating a CloudFormation template that defines the resources required for our setup. Save the following code in a file named **'apigateway_nlb_cf_template.yaml'**.

```
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  VPCId:
    Type: String
    Description: VPC ID where resources will be created
Resources:
  NLB:
    Type: 'AWS::ElasticLoadBalancingV2::LoadBalancer'
    Properties:
      Name: MyNLB
      Subnets:
        - SubnetId1
        - SubnetId2
      Scheme: internet-facing
  TargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: MyTargetGroup
      Port: 80
      Protocol: HTTP
      VpcId: !Ref VPCId
  APIGateway:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Name: MyAPIGateway
  Integration:
    Type: 'AWS::ApiGateway::Integration'
    Properties:
      IntegrationHttpMethod: POST
      IntegrationType: HTTP_PROXY
      IntegrationUri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunctionArn}/invocations
      RestApiId: !Ref APIGateway
      ResourceId: !GetAtt APIGateway.RootResourceId
      Credentials: "arn:aws:iam::xxxxxxxxxxxx:role/apigateway-lambda-role"
  ApiMethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      AuthorizationType: NONE
      HttpMethod: POST
      ResourceId: !GetAtt APIGateway.RootResourceId
      RestApiId: !Ref APIGateway
      Integration:
        IntegrationHttpMethod: POST
        Type: AWS_PROXY
        Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunctionArn}/invocations
      MethodResponses:
        - StatusCode: 200
  ApiGatewayNLBIntegration:
    Type: 'AWS::ApiGateway::Integration'
    Properties:
      IntegrationHttpMethod: ANY
      IntegrationType: HTTP
      IntegrationUri: !Sub "http://${NLB.DNSName}"
      RestApiId: !Ref APIGateway
      ResourceId: !GetAtt APIGateway.RootResourceId
Outputs:
  ApiGatewayURL:
    Description: URL of the API Gateway
    Value: !Sub "https://${APIGateway}.execute-api.${AWS::Region}.amazonaws.com"

```
This CloudFormation template defines an NLB, a target group, an API Gateway, and an integration between the API Gateway and the NLB.

Explanation of the template:

**NLB**: Defines the Network Load Balancer.
**TargetGroup**: Specifies the target group for the NLB.
**APIGateway**: Sets up the API Gateway.
**Integration**: Configures the integration between API Gateway and the NLB.
**ApiMethod**: Defines the API Gateway method (POST in this case).
**ApiGatewayNLBIntegration**: Establishes the integration between API Gateway and NLB.
Make sure to replace placeholders like **'SubnetId1'**, **'SubnetId2'**, **'LambdaFunctionArn'**, and **'xxxxxxxxxxxx'** with actual values specific to your setup.

Deploy the CloudFormation Stack:

Now that we have our CloudFormation template, let's deploy it using the AWS Management Console or the AWS Command Line Interface (CLI).

Using AWS CLI:

```
aws cloudformation create-stack --stack-name MyApiGatewayNLBStack --template-body file://apigateway_nlb_cf_template.yaml --parameters ParameterKey=VPCId,ParameterValue=vpc-xxxxxxxx

```
Replace **'vpc-xxxxxxxx'** with your VPC ID.

Conclusion:

By leveraging AWS CloudFormation, you can easily set up an API Gateway integrated with a Network Load Balancer. This architecture ensures a scalable and fault-tolerant solution for handling incoming API traffic. Feel free to customize the template to suit your specific requirements and extend the setup based on your application's needs. Happy coding!