Skip to content

Instantly share code, notes, and snippets.

@simonespa
Created January 15, 2023 15:09
Show Gist options
  • Select an option

  • Save simonespa/b7f0a066f9d153f0587c5f8ee441eda9 to your computer and use it in GitHub Desktop.

Select an option

Save simonespa/b7f0a066f9d153f0587c5f8ee441eda9 to your computer and use it in GitHub Desktop.
CDK Lambda and EC2 with ALB
import autoscaling = require('@aws-cdk/aws-autoscaling');
import ec2 = require('@aws-cdk/aws-ec2');
import elbv2 = require('@aws-cdk/aws-elasticloadbalancingv2');
import cdk = require('@aws-cdk/core');
export default class LoadBalancerStack extends cdk.Stack {
constructor(app: cdk.App, id: string) {
super(app, id);
const vpc = new ec2.Vpc(this, 'VPC');
const asg = new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),
machineImage: new ec2.AmazonLinuxImage(),
});
const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', {
vpc,
internetFacing: true
});
const listener = lb.addListener('Listener', {
port: 80,
});
listener.addTargets('Target', {
port: 80,
targets: [asg]
});
listener.connections.allowDefaultPortFromAnyIpv4('Open to the world');
asg.scaleOnRequestCount('AModestLoad', {
targetRequestsPerSecond: 1
});
}
}
import * as cdk from '@aws-cdk/core';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2';
import * as targets from '@aws-cdk/aws-elasticloadbalancingv2-targets';
import * as lambda from '@aws-cdk/aws-lambda';
export default class MainStack extends cdk.Stack {
constructor(app: cdk.App, id: string, props: cdk.StackProps) {
super(app, id, props);
const vpc = ec2.Vpc.fromLookup(this, 'VirtualPrivateCloud', {
vpcName: 'Core Infra'
});
const lambdaFunction = new lambda.Function(this, 'Function', {
runtime: lambda.Runtime.NODEJS_16_X,
handler: 'index.handler',
code: lambda.Code.fromInline('exports.handler = async function(event, context) {console.log(JSON.stringify(event, null, 2));return context.logStreamName;}')
});
const lambdaTarget = new targets.LambdaTarget(lambdaFunction);
const loadBalancer = new elbv2.ApplicationLoadBalancer(this, 'LoadBalancer', {
vpc,
internetFacing: true
});
const listener = loadBalancer.addListener('Listener', {
port: 80,
});
listener.addTargets('Targets', {
targets: [lambdaTarget],
// For Lambda Targets, you need to explicitly enable health checks if you
// want them.
healthCheck: {
enabled: true,
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment