Skip to main content

CDK Constructs for Application Load Balancer to AWS Lambda integration

Project description

aws-alb-lambda module

---

Stability: Experimental

All classes are under active development and subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.


Reference Documentation: https://docs.aws.amazon.com/solutions/latest/constructs/
Language Package
Python Logo Python aws_solutions_constructs.aws_alb_lambda
Typescript Logo Typescript @aws-solutions-constructs/aws-alb-lambda
Java Logo Java software.amazon.awsconstructs.services.alblambda

Overview

This AWS Solutions Construct implements an an Application Load Balancer to an AWS Lambda function

Here is a minimal deployable pattern definition:

Typescript

import { Construct } from 'constructs';
import { Stack, StackProps } from 'aws-cdk-lib';
import { AlbToLambda, AlbToLambdaProps } from '@aws-solutions-constructs/aws-alb-lambda';
import * as acm from 'aws-cdk-lib/aws-certificatemanager';
import * as lambda from 'aws-cdk-lib/aws-lambda';

// Obtain a pre-existing certificate from your account
const certificate = acm.Certificate.fromCertificateArn(
    this,
    'existing-cert',
    "arn:aws:acm:us-east-1:123456789012:certificate/11112222-3333-1234-1234-123456789012"
);

const constructProps: AlbToLambdaProps = {
  lambdaFunctionProps: {
    code: lambda.Code.fromAsset(`lambda`),
    runtime: lambda.Runtime.NODEJS_16_X,
    handler: 'index.handler'
  },
  listenerProps: {
    certificates: [certificate]
  },
  publicApi: true
};

// Note - all alb constructs turn on ELB logging by default, so require that an environment including account
// and region be provided when creating the stack
//
// new MyStack(app, 'id', {env: {account: '123456789012', region: 'us-east-1' }});
new AlbToLambda(this, 'new-construct', constructProps);

Python

from aws_solutions_constructs.aws_alb_lambda import AlbToLambda, AlbToLambdaProps
from aws_cdk import (
    aws_certificatemanager as acm,
    aws_lambda as _lambda,
    aws_elasticloadbalancingv2 as alb,
    Stack
)
from constructs import Construct

# Obtain a pre-existing certificate from your account
certificate = acm.Certificate.from_certificate_arn(
  self,
  'existing-cert',
  "arn:aws:acm:us-east-1:123456789012:certificate/11112222-3333-1234-1234-123456789012"
)

# Note - all alb constructs turn on ELB logging by default, so require that an environment including account
# and region be provided when creating the stack
#
# MyStack(app, 'id', env=cdk.Environment(account='123456789012', region='us-east-1'))
AlbToLambda(self, 'new-construct',
            lambda_function_props=_lambda.FunctionProps(
                runtime=_lambda.Runtime.PYTHON_3_7,
                code=_lambda.Code.from_asset('lambda'),
                handler='index.handler',
            ),
            listener_props=alb.BaseApplicationListenerProps(
                certificates=[certificate]
            ),
            public_api=True)

Java

import software.constructs.Construct;
import java.util.List;

import software.amazon.awscdk.Stack;
import software.amazon.awscdk.StackProps;
import software.amazon.awscdk.services.elasticloadbalancingv2.*;
import software.amazon.awscdk.services.lambda.*;
import software.amazon.awscdk.services.lambda.Runtime;
import software.amazon.awsconstructs.services.alblambda.*;

// Obtain a pre-existing certificate from your account
ListenerCertificate listenerCertificate = ListenerCertificate
        .fromArn("arn:aws:acm:us-east-1:123456789012:certificate/11112222-3333-1234-1234-123456789012");

// Note - all alb constructs turn on ELB logging by default, so require that an environment including account
// and region be provided when creating the stack
//
// new MyStack(app, "id", StackProps.builder()
//         .env(Environment.builder()
//                 .account("123456789012")
//                 .region("us-east-1")
//                 .build());
new AlbToLambda(this, "AlbToLambdaPattern", new AlbToLambdaProps.Builder()
        .lambdaFunctionProps(new FunctionProps.Builder()
                .runtime(Runtime.NODEJS_16_X)
                .code(Code.fromAsset("lambda"))
                .handler("index.handler")
                .build())
        .listenerProps(new BaseApplicationListenerProps.Builder()
                .certificates(List.of(listenerCertificate))
                .build())
        .publicApi(true)
        .build());

Pattern Construct Props

Name Type Description
loadBalancerProps? elasticloadbalancingv2.ApplicationLoadBalancerProps Optional custom properties for a new loadBalancer. Providing both this and existingLoadBalancer is an error. This cannot specify a VPC, it will use the VPC in existingVpc or the VPC created by the construct.
existingLoadBalancerObj? elasticloadbalancingv2.ApplicationLoadBalancer Existing Application Load Balancer to incorporate into the construct architecture. Providing both this and loadBalancerProps is an error. The VPC containing this loadBalancer must match the VPC provided in existingVpc.
listenerProps? ApplicationListenerProps Props to define the listener. Must be provided when adding the listener to an ALB (eg - when creating the alb), may not be provided when adding a second target to an already established listener. When provided, must include either a certificate or protocol: HTTP
targetProps? ApplicationTargetGroupProps Optional custom properties for a new target group. While this is a standard attribute of props for ALB constructs, there are few pertinent properties for a Lambda target.
ruleProps? AddRuleProps Rules for directing traffic to the target being created. May not be specified for the first listener added to an ALB, and must be specified for the second target added to a listener. Add a second target by instantiating this construct a second time and providing the existingAlb from the first instantiation.
vpcProps? ec2.VpcProps Optional custom properties for a VPC the construct will create. This VPC will be used by the new ALB and any Private Hosted Zone the construct creates (that's why loadBalancerProps and privateHostedZoneProps can't include a VPC). Providing both this and existingVpc is an error.
existingLambdaObj? lambda.Function Existing instance of Lambda Function object, providing both this and lambdaFunctionProps will cause an error.
lambdaFunctionProps? lambda.FunctionProps Optional user provided props to override the default props for the Lambda function.
existingVpc? ec2.IVpc An existing VPC in which to deploy the construct. Providing both this and vpcProps is an error. If the client provides an existing load balancer and/or existing Private Hosted Zone, those constructs must exist in this VPC.
logAlbAccessLogs? boolean Whether to turn on Access Logs for the Application Load Balancer. Uses an S3 bucket with associated storage costs.Enabling Access Logging is a best practice. default - true
albLoggingBucketProps? s3.BucketProps Optional properties to customize the bucket used to store the ALB Access Logs. Supplying this and setting logAccessLogs to false is an error. @default - none
publicApi boolean Whether the construct is deploying a private or public API. This has implications for the VPC and ALB.

Pattern Properties

Name Type Description
vpc ec2.IVpc The VPC used by the construct (whether created by the construct or providedb by the client)
loadBalancer elasticloadbalancingv2.ApplicationLoadBalancer The Load Balancer used by the construct (whether created by the construct or provided by the client)
lambdaFunction lambda.Function Returns an instance of the Lambda function used in the pattern.
listener elb.ApplicationListener The listener used by this pattern.

Default settings

Out of the box implementation of the Construct without any override will set the following defaults:

Application Load Balancer

  • Creates or configures an Application Load Balancer with:

    • Required listeners
    • New target group with routing rules if appropriate

AWS Lambda Function

  • Configure limited privilege access IAM role for Lambda function

  • Enable reusing connections with Keep-Alive for NodeJs Lambda function

  • Enable X-Ray Tracing

  • Set Environment Variables

    • AWS_NODEJS_CONNECTION_REUSE_ENABLED (for Node 10.x and higher functions)

Architecture

Architecture Diagram


© Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Built Distribution

File details

Details for the file aws_solutions_constructs_aws_alb_lambda-2.70.0.tar.gz.

File metadata

File hashes

Hashes for aws_solutions_constructs_aws_alb_lambda-2.70.0.tar.gz
Algorithm Hash digest
SHA256 4fa41e2880363ffa9dac463a673c5d808a73d71a968e6dc10b2e57b8b08ff077
MD5 bea80744ff06bc198f96e99f8690bad1
BLAKE2b-256 68f9f56d0eee1ff6ed15d38549644cb6776979e86f244a13ed8a6b7c48f40af6

See more details on using hashes here.

File details

Details for the file aws_solutions_constructs.aws_alb_lambda-2.70.0-py3-none-any.whl.

File metadata

File hashes

Hashes for aws_solutions_constructs.aws_alb_lambda-2.70.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3c5a922f28f6b4e5565252507602470e8f45e3a6f5a3919096ffcafcdf8c4945
MD5 df5debb31e7c5f97b9bfc7b1ccaefd65
BLAKE2b-256 34328c691f8b6a2139d649e3e654344fe0f8666acfd02f795e5fb7a6f3d52125

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page