|
1 | 1 | import {
|
2 |
| - Connections, IConnectable, ISecurityGroup, IVpc, Peer, Port, |
| 2 | + Connections, IConnectable, Instance, ISecurityGroup, IVpc, Peer, Port, |
3 | 3 | SecurityGroup, SelectedSubnets, SubnetSelection, SubnetType,
|
4 | 4 | } from '@aws-cdk/aws-ec2';
|
5 | 5 | import { Duration, Lazy, Resource } from '@aws-cdk/core';
|
@@ -251,20 +251,21 @@ export class LoadBalancer extends Resource implements IConnectable {
|
251 | 251 |
|
252 | 252 | private readonly instancePorts: number[] = [];
|
253 | 253 | private readonly targets: ILoadBalancerTarget[] = [];
|
| 254 | + private readonly instanceIds: string[] = []; |
254 | 255 |
|
255 | 256 | constructor(scope: Construct, id: string, props: LoadBalancerProps) {
|
256 | 257 | super(scope, id);
|
257 | 258 |
|
258 | 259 | this.securityGroup = new SecurityGroup(this, 'SecurityGroup', { vpc: props.vpc, allowAllOutbound: false });
|
259 | 260 | this.connections = new Connections({ securityGroups: [this.securityGroup] });
|
260 |
| - |
261 | 261 | // Depending on whether the ELB has public or internal IPs, pick the right backend subnets
|
262 | 262 | const selectedSubnets: SelectedSubnets = loadBalancerSubnets(props);
|
263 | 263 |
|
264 | 264 | this.elb = new CfnLoadBalancer(this, 'Resource', {
|
265 | 265 | securityGroups: [this.securityGroup.securityGroupId],
|
266 | 266 | subnets: selectedSubnets.subnetIds,
|
267 | 267 | listeners: Lazy.any({ produce: () => this.listeners }),
|
| 268 | + instances: Lazy.list({ produce: () => this.instanceIds }, { omitEmpty: true }), |
268 | 269 | scheme: props.internetFacing ? 'internet-facing' : 'internal',
|
269 | 270 | healthCheck: props.healthCheck && healthCheckToJSON(props.healthCheck),
|
270 | 271 | crossZone: props.crossZone ?? true,
|
@@ -398,6 +399,33 @@ export class LoadBalancer extends Resource implements IConnectable {
|
398 | 399 | Port.tcp(instancePort),
|
399 | 400 | `Port ${instancePort} LB to fleet`);
|
400 | 401 | }
|
| 402 | + |
| 403 | + /** |
| 404 | + * Add instance to the load balancer. |
| 405 | + * @internal |
| 406 | + */ |
| 407 | + public _addInstanceId(instanceId: string) { |
| 408 | + this.instanceIds.push(instanceId); |
| 409 | + } |
| 410 | +} |
| 411 | + |
| 412 | +/** |
| 413 | + * An EC2 instance that is the target for load balancing |
| 414 | + */ |
| 415 | +export class InstanceTarget implements ILoadBalancerTarget { |
| 416 | + readonly connections: Connections; |
| 417 | + /** |
| 418 | + * Create a new Instance target. |
| 419 | + * |
| 420 | + * @param instance Instance to register to. |
| 421 | + */ |
| 422 | + constructor(public readonly instance: Instance) { |
| 423 | + this.connections = instance.connections; |
| 424 | + } |
| 425 | + |
| 426 | + public attachToClassicLB(loadBalancer: LoadBalancer): void { |
| 427 | + loadBalancer._addInstanceId(this.instance.instanceId); |
| 428 | + } |
401 | 429 | }
|
402 | 430 |
|
403 | 431 | /**
|
|
0 commit comments