forked from aws/aws-cdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetwork-load-balanced-service-base.ts
404 lines (352 loc) · 13.1 KB
/
network-load-balanced-service-base.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import { IVpc } from '@aws-cdk/aws-ec2';
import {
AwsLogDriver, BaseService, CloudMapOptions, Cluster, ContainerImage, DeploymentController, DeploymentCircuitBreaker,
ICluster, LogDriver, PropagatedTagSource, Secret,
} from '@aws-cdk/aws-ecs';
import { INetworkLoadBalancer, NetworkListener, NetworkLoadBalancer, NetworkTargetGroup } from '@aws-cdk/aws-elasticloadbalancingv2';
import { IRole } from '@aws-cdk/aws-iam';
import { ARecord, CnameRecord, IHostedZone, RecordTarget } from '@aws-cdk/aws-route53';
import { LoadBalancerTarget } from '@aws-cdk/aws-route53-targets';
import * as cdk from '@aws-cdk/core';
import { Construct } from 'constructs';
// keep this import separate from other imports to reduce chance for merge conflicts with v2-main
// eslint-disable-next-line no-duplicate-imports, import/order
import { Construct as CoreConstruct } from '@aws-cdk/core';
/**
* Describes the type of DNS record the service should create
*/
export enum NetworkLoadBalancedServiceRecordType {
/**
* Create Route53 A Alias record
*/
ALIAS,
/**
* Create a CNAME record
*/
CNAME,
/**
* Do not create any DNS records
*/
NONE
}
/**
* The properties for the base NetworkLoadBalancedEc2Service or NetworkLoadBalancedFargateService service.
*/
export interface NetworkLoadBalancedServiceBaseProps {
/**
* The name of the cluster that hosts the service.
*
* If a cluster is specified, the vpc construct should be omitted. Alternatively, you can omit both cluster and vpc.
* @default - create a new cluster; if both cluster and vpc are omitted, a new VPC will be created for you.
*/
readonly cluster?: ICluster;
/**
* The VPC where the container instances will be launched or the elastic network interfaces (ENIs) will be deployed.
*
* If a vpc is specified, the cluster construct should be omitted. Alternatively, you can omit both vpc and cluster.
* @default - uses the VPC defined in the cluster or creates a new VPC.
*/
readonly vpc?: IVpc;
/**
* The properties required to create a new task definition. One of taskImageOptions or taskDefinition must be specified.
*
* @default - none
*/
readonly taskImageOptions?: NetworkLoadBalancedTaskImageOptions;
/**
* Determines whether the Load Balancer will be internet-facing.
*
* @default true
*/
readonly publicLoadBalancer?: boolean;
/**
* The desired number of instantiations of the task definition to keep running on the service.
* The minimum value is 1
*
* @default - If the feature flag, ECS_REMOVE_DEFAULT_DESIRED_COUNT is false, the default is 1;
* if true, the default is 1 for all new services and uses the existing services desired count
* when updating an existing service.
*/
readonly desiredCount?: number;
/**
* The domain name for the service, e.g. "api.example.com."
*
* @default - No domain name.
*/
readonly domainName?: string;
/**
* The Route53 hosted zone for the domain, e.g. "example.com."
*
* @default - No Route53 hosted domain zone.
*/
readonly domainZone?: IHostedZone;
/**
* The name of the service.
*
* @default - CloudFormation-generated name.
*/
readonly serviceName?: string;
/**
* The period of time, in seconds, that the Amazon ECS service scheduler ignores unhealthy
* Elastic Load Balancing target health checks after a task has first started.
*
* @default - defaults to 60 seconds if at least one load balancer is in-use and it is not already set
*/
readonly healthCheckGracePeriod?: cdk.Duration;
/**
* The maximum number of tasks, specified as a percentage of the Amazon ECS
* service's DesiredCount value, that can run in a service during a
* deployment.
*
* @default - 100 if daemon, otherwise 200
*/
readonly maxHealthyPercent?: number;
/**
* The minimum number of tasks, specified as a percentage of
* the Amazon ECS service's DesiredCount value, that must
* continue to run and remain healthy during a deployment.
*
* @default - 0 if daemon, otherwise 50
*/
readonly minHealthyPercent?: number;
/**
* The network load balancer that will serve traffic to the service.
* If the load balancer has been imported, the vpc attribute must be specified
* in the call to fromNetworkLoadBalancerAttributes().
*
* [disable-awslint:ref-via-interface]
*
* @default - a new load balancer will be created.
*/
readonly loadBalancer?: INetworkLoadBalancer;
/**
* Listener port of the network load balancer that will serve traffic to the service.
*
* @default 80
*/
readonly listenerPort?: number;
/**
* Specifies whether to propagate the tags from the task definition or the service to the tasks in the service.
* Tags can only be propagated to the tasks within the service during service creation.
*
* @default - none
*/
readonly propagateTags?: PropagatedTagSource;
/**
* Specifies whether to enable Amazon ECS managed tags for the tasks within the service. For more information, see
* [Tagging Your Amazon ECS Resources](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html)
*
* @default false
*/
readonly enableECSManagedTags?: boolean;
/**
* The options for configuring an Amazon ECS service to use service discovery.
*
* @default - AWS Cloud Map service discovery is not enabled.
*/
readonly cloudMapOptions?: CloudMapOptions;
/**
* Specifies whether the Route53 record should be a CNAME, an A record using the Alias feature or no record at all.
* This is useful if you need to work with DNS systems that do not support alias records.
*
* @default NetworkLoadBalancedServiceRecordType.ALIAS
*/
readonly recordType?: NetworkLoadBalancedServiceRecordType;
/**
* Specifies which deployment controller to use for the service. For more information, see
* [Amazon ECS Deployment Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html)
*
* @default - Rolling update (ECS)
*/
readonly deploymentController?: DeploymentController;
/**
* Whether to enable the deployment circuit breaker. If this property is defined, circuit breaker will be implicitly
* enabled.
* @default - disabled
*/
readonly circuitBreaker?: DeploymentCircuitBreaker;
}
export interface NetworkLoadBalancedTaskImageOptions {
/**
* The image used to start a container. Image or taskDefinition must be specified, but not both.
*
* @default - none
*/
readonly image: ContainerImage;
/**
* The environment variables to pass to the container.
*
* @default - No environment variables.
*/
readonly environment?: { [key: string]: string };
/**
* The secret to expose to the container as an environment variable.
*
* @default - No secret environment variables.
*/
readonly secrets?: { [key: string]: Secret };
/**
* Flag to indicate whether to enable logging.
*
* @default true
*/
readonly enableLogging?: boolean;
/**
* The log driver to use.
*
* @default - AwsLogDriver if enableLogging is true
*/
readonly logDriver?: LogDriver;
/**
* The name of the task execution IAM role that grants the Amazon ECS container agent permission to call AWS APIs on your behalf.
*
* @default - No value
*/
readonly executionRole?: IRole;
/**
* The name of the task IAM role that grants containers in the task permission to call AWS APIs on your behalf.
*
* @default - A task role is automatically created for you.
*/
readonly taskRole?: IRole;
/**
* The container name value to be specified in the task definition.
*
* @default - none
*/
readonly containerName?: string;
/**
* The port number on the container that is bound to the user-specified or automatically assigned host port.
*
* If you are using containers in a task with the awsvpc or host network mode, exposed ports should be specified using containerPort.
* If you are using containers in a task with the bridge network mode and you specify a container port and not a host port,
* your container automatically receives a host port in the ephemeral port range.
*
* Port mappings that are automatically assigned in this way do not count toward the 100 reserved ports limit of a container instance.
*
* For more information, see
* [hostPort](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PortMapping.html#ECS-Type-PortMapping-hostPort).
*
* @default 80
*/
readonly containerPort?: number;
/**
* The name of a family that this task definition is registered to. A family groups multiple versions of a task definition.
*
* @default - Automatically generated name.
*/
readonly family?: string;
}
/**
* The base class for NetworkLoadBalancedEc2Service and NetworkLoadBalancedFargateService services.
*/
export abstract class NetworkLoadBalancedServiceBase extends CoreConstruct {
/**
* The desired number of instantiations of the task definition to keep running on the service.
* @deprecated - Use `internalDesiredCount` instead.
*/
public readonly desiredCount: number;
/**
* The desired number of instantiations of the task definition to keep running on the service.
* The default is 1 for all new services and uses the existing services desired count
* when updating an existing service, if one is not provided.
*/
public readonly internalDesiredCount?: number;
/**
* The Network Load Balancer for the service.
*/
public get loadBalancer(): NetworkLoadBalancer {
if (!this._networkLoadBalancer) {
throw new Error('.loadBalancer can only be accessed if the class was constructed with an owned, not imported, load balancer');
}
return this._networkLoadBalancer;
}
/**
* The listener for the service.
*/
public readonly listener: NetworkListener;
/**
* The target group for the service.
*/
public readonly targetGroup: NetworkTargetGroup;
/**
* The cluster that hosts the service.
*/
public readonly cluster: ICluster;
private readonly _networkLoadBalancer?: NetworkLoadBalancer;
/**
* Constructs a new instance of the NetworkLoadBalancedServiceBase class.
*/
constructor(scope: Construct, id: string, props: NetworkLoadBalancedServiceBaseProps = {}) {
super(scope, id);
if (props.cluster && props.vpc) {
throw new Error('You can only specify either vpc or cluster. Alternatively, you can leave both blank');
}
this.cluster = props.cluster || this.getDefaultCluster(this, props.vpc);
if (props.desiredCount !== undefined && props.desiredCount < 1) {
throw new Error('You must specify a desiredCount greater than 0');
}
this.desiredCount = props.desiredCount || 1;
this.internalDesiredCount = props.desiredCount;
const internetFacing = props.publicLoadBalancer ?? true;
const lbProps = {
vpc: this.cluster.vpc,
internetFacing,
};
const loadBalancer = props.loadBalancer ?? new NetworkLoadBalancer(this, 'LB', lbProps);
const listenerPort = props.listenerPort ?? 80;
const targetProps = {
port: 80,
};
this.listener = loadBalancer.addListener('PublicListener', { port: listenerPort });
this.targetGroup = this.listener.addTargets('ECS', targetProps);
if (typeof props.domainName !== 'undefined') {
if (typeof props.domainZone === 'undefined') {
throw new Error('A Route53 hosted domain zone name is required to configure the specified domain name');
}
switch (props.recordType ?? NetworkLoadBalancedServiceRecordType.ALIAS) {
case NetworkLoadBalancedServiceRecordType.ALIAS:
new ARecord(this, 'DNS', {
zone: props.domainZone,
recordName: props.domainName,
target: RecordTarget.fromAlias(new LoadBalancerTarget(loadBalancer)),
});
break;
case NetworkLoadBalancedServiceRecordType.CNAME:
new CnameRecord(this, 'DNS', {
zone: props.domainZone,
recordName: props.domainName,
domainName: loadBalancer.loadBalancerDnsName,
});
break;
case NetworkLoadBalancedServiceRecordType.NONE:
// Do not create a DNS record
break;
}
}
if (loadBalancer instanceof NetworkLoadBalancer) {
this._networkLoadBalancer = loadBalancer;
}
if (props.loadBalancer === undefined) {
new cdk.CfnOutput(this, 'LoadBalancerDNS', { value: this.loadBalancer.loadBalancerDnsName });
}
}
/**
* Returns the default cluster.
*/
protected getDefaultCluster(scope: CoreConstruct, vpc?: IVpc): Cluster {
// magic string to avoid collision with user-defined constructs
const DEFAULT_CLUSTER_ID = `EcsDefaultClusterMnL3mNNYN${vpc ? vpc.node.id : ''}`;
const stack = cdk.Stack.of(scope);
return stack.node.tryFindChild(DEFAULT_CLUSTER_ID) as Cluster || new Cluster(stack, DEFAULT_CLUSTER_ID, { vpc });
}
/**
* Adds service as a target of the target group.
*/
protected addServiceAsTarget(service: BaseService) {
this.targetGroup.addTarget(service);
}
protected createAWSLogDriver(prefix: string): AwsLogDriver {
return new AwsLogDriver({ streamPrefix: prefix });
}
}