diff --git a/rest-api-alb-integration-workaround/README.md b/rest-api-alb-integration-workaround/README.md new file mode 100644 index 000000000..62e8d18aa --- /dev/null +++ b/rest-api-alb-integration-workaround/README.md @@ -0,0 +1,78 @@ +# REST API Integration with Private ALB - Workaround + +This pattern explains how to integrate an API Gateway REST API with an Application Load Balancer. + +Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. + +## Requirements + +* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. +* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured +* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) +* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed + +## Deployment Instructions + +1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: + ``` + git clone https://github.com/aws-samples/serverless-patterns + ``` +1. Change directory to the pattern directory: + ``` + cd rest-api-alb-integration-workaround + ``` +1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file: + ``` + sam deploy --guided + ``` +1. During the prompts: + * Enter a stack name + * Enter the desired AWS Region + * Allow SAM CLI to create IAM roles with the required permissions. + + Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults. + +1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing. + +## Background + +Currently, integration between REST APIs and Application Load Balancers (ALBs) has some limitations. Direct integration is only possible with public ALBs using API Gateway's HTTP integration feature. Private ALBs cannot be directly integrated with API Gateway. + +To work around this limitation for private ALBs, a multi-step approach is necessary. First, create an API Gateway VPC link. Then, connect the VPC link to a private Network Load Balancer (NLB). Finally, configure the NLB to forward incoming requests from API Gateway to the private ALB. This setup allows API Gateway to communicate with private ALBs indirectly, enabling the use of private ALBs in API architectures while maintaining the benefits of API Gateway management. + +## Prerequisites + +1. Active Route 53 Hosted Zone for your domain. +2. Valid ACM (AWS Certificate Manager) certificate that covers the domain managed by your Route 53 Hosted Zone. + +## Workaround + +1. Use an API Gateway VPC to integrate your API with a private Network Load Balancer. + +2. Use the Network Load Balancer to forward the API request to the private Application Load Balancer. + +3. Application Load Balancer will forward the traffic to Lambda Function configured on HTTPS listener. + + +``` +Workflow: REST API >> VPC Link >> NLB (TCP listener) >> ALB (HTTPS listener) >> Lambda +``` + +## Testing + +Once the application is deployed, retrieve the API URL provided as output and open it in a browser page. + +## Cleanup + +1. Delete the stack + ```bash + sam delete --stack-name STACK_NAME + ``` +1. Confirm the stack has been deleted + ```bash + aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus" + ``` +---- +Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/rest-api-alb-integration-workaround/example-pattern.json b/rest-api-alb-integration-workaround/example-pattern.json new file mode 100644 index 000000000..59a2869ae --- /dev/null +++ b/rest-api-alb-integration-workaround/example-pattern.json @@ -0,0 +1,54 @@ +{ + "title": "REST API Integration with Private ALB integration", + "description": "This pattern explains workaround on how to integrate an API Gateway REST API with an Application Load Balancer.", + "language": "Python", + "level": "200", + "framework": "YAML", + "introBox": { + "headline": "How it works", + "text": [ + "To work around this limitation for private ALBs, a multi-step approach is necessary", + "1. Use an API Gateway VPC to integrate your API with a private Network Load Balancer.", + "2. Use the Network Load Balancer to forward the API request to the private Application Load Balancer", + "3. Application Load Balancer will forward the traffic to Lambda Function configured on HTTPS listener." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/rest-api-alb-integration-workaround", + "templateURL": "serverless-patterns/rest-api-alb-integration-workaround", + "projectFolder": "rest-api-alb-integration-workaround", + "templateFile": "template.yaml" + } + }, + "resources": { + "bullets": [ + { + "text": "How do I integrate an API Gateway REST API with an Application Load Balancer", + "link": "https://repost.aws/knowledge-center/api-gateway-application-load-balancers" + } + ] + }, + "deploy": { + "text": [ + "sam deploy" + ] + }, + "testing": { + "text": [ + "Once the application is deployed, retrieve the API URL provided as output and open it in a browser page." + ] + }, + "cleanup": { + "text": [ + "Delete the stack: sam delete." + ] + }, + "authors": [ + { + "name": "Vamsi Pulikonda", + "image": "https://raw.githubusercontent.com/vamsipulikonda/my-photo/main/vamsi-photo.jpg", + "linkedin": "https://www.linkedin.com/in/vamsipulikonda/" + } + ] +} diff --git a/rest-api-alb-integration-workaround/src/app.js b/rest-api-alb-integration-workaround/src/app.js new file mode 100644 index 000000000..cb3c4d9c1 --- /dev/null +++ b/rest-api-alb-integration-workaround/src/app.js @@ -0,0 +1,10 @@ +/*! Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: MIT-0 + */ + +'use strict' + +exports.handler = async (event) => { + // Lambda handler code + console.log(JSON.stringify(event, 0, null)) +} \ No newline at end of file diff --git a/rest-api-alb-integration-workaround/template.yaml b/rest-api-alb-integration-workaround/template.yaml new file mode 100644 index 000000000..f9d0f4e61 --- /dev/null +++ b/rest-api-alb-integration-workaround/template.yaml @@ -0,0 +1,254 @@ +AWSTemplateFormatVersion: 2010-09-09 +Description: Amazon API Gateway REST API with VPC Link integration with NLB -> ALB Integration +Parameters: + VPCCIDR: + Description: Enter CIDR for new VPC + Type: String + Default: '10.0.0.0/16' + Subnet1CIRD: + Description: Enter CIDR for new Private subnet 1 + Type: String + Default: '10.0.0.0/24' + Subnet2CIRD: + Description: Enter CIDR for new Private subnet 2 + Type: String + Default: '10.0.1.0/24' + AlbCertificateArn: + Description: ARN of the ACM certificate for ABL HTTPS listener + Type: String + AlbInternalCertificateDns: + Description: DNS name for the certificate + Type: String + +Resources: + EC2VPC: + Type: 'AWS::EC2::VPC' + Properties: + EnableDnsSupport: true + EnableDnsHostnames: true + CidrBlock: !Ref VPCCIDR + InstanceTenancy: "default" + + PrivateSubnet1: + Type: "AWS::EC2::Subnet" + Properties: + AvailabilityZone: !Sub "${AWS::Region}a" + CidrBlock: !Ref Subnet1CIRD + VpcId: !Ref EC2VPC + MapPublicIpOnLaunch: false + Tags: + - + Key: "Name" + Value: "Private-new-availability-1" + + PrivateSubnet2: + Type: "AWS::EC2::Subnet" + Properties: + AvailabilityZone: !Sub "${AWS::Region}b" + CidrBlock: !Ref Subnet2CIRD + VpcId: !Ref EC2VPC + MapPublicIpOnLaunch: false + Tags: + - + Key: "Name" + Value: "Private-new-availability-2" + + EC2SecurityGroup: + Type: "AWS::EC2::SecurityGroup" + Properties: + GroupDescription: "Allow VPC CIDR" + GroupName: "PrivateLoadBalancerSG" + VpcId: !Ref EC2VPC + SecurityGroupIngress: + - + CidrIp: !Ref VPCCIDR + FromPort: 443 + IpProtocol: "tcp" + ToPort: 443 + - + CidrIp: !Ref VPCCIDR + FromPort: 80 + IpProtocol: "tcp" + ToPort: 80 + SecurityGroupEgress: + - + CidrIp: !Ref VPCCIDR + FromPort: 443 + IpProtocol: "tcp" + ToPort: 443 + - + CidrIp: !Ref VPCCIDR + FromPort: 80 + IpProtocol: "tcp" + ToPort: 80 + + IAMRole: + Type: "AWS::IAM::Role" + Properties: + Path: "/" + RoleName: "LambdaRole" + AssumeRolePolicyDocument: "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}" + MaxSessionDuration: 3600 + ManagedPolicyArns: + - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + Description: "Allows Lambda functions to call AWS services on your behalf." + + LambdaFunction: + Type: "AWS::Lambda::Function" + Properties: + Description: "AWS Lambda target for ALB" + FunctionName: "ALBTargetLambda" + Handler: "index.lambda_handler" + Architectures: + - "x86_64" + Code: + ZipFile: | + import json + + def lambda_handler(event, context): + return { + 'statusCode': 200, + 'body': json.dumps('Hello from Lambda behind NLB -> ALB Integration!') + } + MemorySize: 128 + Role: !GetAtt IAMRole.Arn + Runtime: "python3.11" + Timeout: 15 + TracingConfig: + Mode: "PassThrough" + EphemeralStorage: + Size: 512 + + LambdaALBPermission: + Type: AWS::Lambda::Permission + Properties: + FunctionName: !GetAtt LambdaFunction.Arn + Action: lambda:InvokeFunction + Principal: elasticloadbalancing.amazonaws.com + + PrivateALB: + Type: AWS::ElasticLoadBalancingV2::LoadBalancer + Properties: + Type: application + Scheme: internal + Name: PrivateALB + Subnets: + - !Ref PrivateSubnet1 + - !Ref PrivateSubnet2 + SecurityGroups: [!Ref EC2SecurityGroup] + + ALBTargetGroup: + Type: AWS::ElasticLoadBalancingV2::TargetGroup + DependsOn: LambdaALBPermission + Properties: + TargetType: lambda + Targets: + - Id: !GetAtt LambdaFunction.Arn + + ALBHttpListener: + Type: AWS::ElasticLoadBalancingV2::Listener + Properties: + LoadBalancerArn: !Ref PrivateALB + Port: 443 + Protocol: HTTPS + Certificates: + - CertificateArn: !Ref AlbCertificateArn + DefaultActions: + - TargetGroupArn: !Ref ALBTargetGroup + Type: forward + + PrivateNLB: + Type: AWS::ElasticLoadBalancingV2::LoadBalancer + Properties: + Type: network + Scheme: internal + Name: PrivateNLB + Subnets: + - !Ref PrivateSubnet1 + - !Ref PrivateSubnet2 + + NLBTargetGroup: + Type: AWS::ElasticLoadBalancingV2::TargetGroup + Properties: + TargetType: alb + Protocol: TCP + Port: 443 + VpcId: !Ref EC2VPC + Targets: + - Id: !GetAtt PrivateALB.LoadBalancerArn + + NLBHttpListener: + Type: AWS::ElasticLoadBalancingV2::Listener + Properties: + LoadBalancerArn: !Ref PrivateNLB + Port: 443 + Protocol: TCP + DefaultActions: + - TargetGroupArn: !Ref NLBTargetGroup + Type: forward + +# REST API Part + PrivateIntApi: + Type: AWS::ApiGateway::RestApi + Properties: + Name: apigw-with-alb + Description: VPC Link integration REST API with NLB ALB as backend + + RootMethodGet: + Type: AWS::ApiGateway::Method + Properties: + RestApiId: !Ref PrivateIntApi + ResourceId: !GetAtt PrivateIntApi.RootResourceId + HttpMethod: GET + AuthorizationType: NONE + Integration: + Type: HTTP + ConnectionType: VPC_LINK + ConnectionId: !Ref VPCLinkRest + IntegrationHttpMethod: ANY + Uri: !Sub "https://${AlbInternalCertificateDns}" + PassthroughBehavior: WHEN_NO_MATCH + TimeoutInMillis: 29000 + IntegrationResponses: + - StatusCode: 200 + ResponseParameters: + method.response.header.Access-Control-Allow-Origin: "'*'" + method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'" + method.response.header.Access-Control-Allow-Methods: "'GET'" + MethodResponses: + - StatusCode: 200 + ResponseParameters: + method.response.header.Access-Control-Allow-Origin: true + method.response.header.Access-Control-Allow-Headers: true + method.response.header.Access-Control-Allow-Methods: true + ResponseModels: + application/json: 'Empty' + OperationName: 'RootOperation' + + + + Deployment: + Type: AWS::ApiGateway::Deployment + DependsOn: + - RootMethodGet + Properties: + RestApiId: !Ref PrivateIntApi + + Stage: + Type: AWS::ApiGateway::Stage + Properties: + StageName: Prod + RestApiId: !Ref PrivateIntApi + DeploymentId: !Ref Deployment + + VPCLinkRest: + Type: AWS::ApiGateway::VpcLink + Properties: + Name: VPCLinkRest + TargetArns: + - !Ref PrivateNLB + +Outputs: + PrivateIntApiEndpoint: + Description: API Endpoint + Value: !Sub "https://${PrivateIntApi}.execute-api.${AWS::Region}.amazonaws.com/Prod" \ No newline at end of file