-
Notifications
You must be signed in to change notification settings - Fork 4k
/
cluster.ts
1358 lines (1185 loc) · 44 KB
/
cluster.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as autoscaling from '@aws-cdk/aws-autoscaling';
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import * as kms from '@aws-cdk/aws-kms';
import * as logs from '@aws-cdk/aws-logs';
import * as s3 from '@aws-cdk/aws-s3';
import * as cloudmap from '@aws-cdk/aws-servicediscovery';
import * as ssm from '@aws-cdk/aws-ssm';
import { Duration, Lazy, IResource, Resource, Stack, Aspects, IAspect, IConstruct } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { InstanceDrainHook } from './drain-hook/instance-drain-hook';
import { ECSMetrics } from './ecs-canned-metrics.generated';
import { CfnCluster, CfnCapacityProvider, CfnClusterCapacityProviderAssociations } from './ecs.generated';
// v2 - keep this import as a separate section to reduce merge conflict when forward merging with the v2 branch.
// eslint-disable-next-line
import { Construct as CoreConstruct } from '@aws-cdk/core';
/**
* The properties used to define an ECS cluster.
*/
export interface ClusterProps {
/**
* The name for the cluster.
*
* @default CloudFormation-generated name
*/
readonly clusterName?: string;
/**
* The VPC where your ECS instances will be running or your ENIs will be deployed
*
* @default - creates a new VPC with two AZs
*/
readonly vpc?: ec2.IVpc;
/**
* The service discovery namespace created in this cluster
*
* @default - no service discovery namespace created, you can use `addDefaultCloudMapNamespace` to add a
* default service discovery namespace later.
*/
readonly defaultCloudMapNamespace?: CloudMapNamespaceOptions;
/**
* The ec2 capacity to add to the cluster
*
* @default - no EC2 capacity will be added, you can use `addCapacity` to add capacity later.
*/
readonly capacity?: AddCapacityOptions;
/**
* The capacity providers to add to the cluster
*
* @default - None. Currently only FARGATE and FARGATE_SPOT are supported.
* @deprecated Use {@link ClusterProps.enableFargateCapacityProviders} instead.
*/
readonly capacityProviders?: string[];
/**
* Whether to enable Fargate Capacity Providers
*
* @default false
*/
readonly enableFargateCapacityProviders?: boolean;
/**
* If true CloudWatch Container Insights will be enabled for the cluster
*
* @default - Container Insights will be disabled for this cluser.
*/
readonly containerInsights?: boolean;
/**
* The execute command configuration for the cluster
*
* @default - no configuration will be provided.
*/
readonly executeCommandConfiguration?: ExecuteCommandConfiguration;
}
/**
* The machine image type
*/
export enum MachineImageType {
/**
* Amazon ECS-optimized Amazon Linux 2 AMI
*/
AMAZON_LINUX_2,
/**
* Bottlerocket AMI
*/
BOTTLEROCKET
}
/**
* A regional grouping of one or more container instances on which you can run tasks and services.
*/
export class Cluster extends Resource implements ICluster {
/**
* Import an existing cluster to the stack from its attributes.
*/
public static fromClusterAttributes(scope: Construct, id: string, attrs: ClusterAttributes): ICluster {
return new ImportedCluster(scope, id, attrs);
}
/**
* Manage the allowed network connections for the cluster with Security Groups.
*/
public readonly connections: ec2.Connections = new ec2.Connections();
/**
* The VPC associated with the cluster.
*/
public readonly vpc: ec2.IVpc;
/**
* The Amazon Resource Name (ARN) that identifies the cluster.
*/
public readonly clusterArn: string;
/**
* The name of the cluster.
*/
public readonly clusterName: string;
/**
* The names of both ASG and Fargate capacity providers associated with the cluster.
*/
private _capacityProviderNames: string[] = [];
/**
* The AWS Cloud Map namespace to associate with the cluster.
*/
private _defaultCloudMapNamespace?: cloudmap.INamespace;
/**
* Specifies whether the cluster has EC2 instance capacity.
*/
private _hasEc2Capacity: boolean = false;
/**
* The autoscaling group for added Ec2 capacity
*/
private _autoscalingGroup?: autoscaling.IAutoScalingGroup;
/**
* The execute command configuration for the cluster
*/
private _executeCommandConfiguration?: ExecuteCommandConfiguration;
/**
* Constructs a new instance of the Cluster class.
*/
constructor(scope: Construct, id: string, props: ClusterProps = {}) {
super(scope, id, {
physicalName: props.clusterName,
});
/**
* clusterSettings needs to be undefined if containerInsights is not explicitly set in order to allow any
* containerInsights settings on the account to apply. See:
* https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-cluster-clustersettings.html#cfn-ecs-cluster-clustersettings-value
*/
let clusterSettings = undefined;
if (props.containerInsights !== undefined) {
clusterSettings = [{ name: 'containerInsights', value: props.containerInsights ? ContainerInsights.ENABLED : ContainerInsights.DISABLED }];
}
this._capacityProviderNames = props.capacityProviders ?? [];
if (props.enableFargateCapacityProviders) {
this.enableFargateCapacityProviders();
}
if (props.executeCommandConfiguration) {
if ((props.executeCommandConfiguration.logging === ExecuteCommandLogging.OVERRIDE) !==
(props.executeCommandConfiguration.logConfiguration !== undefined)) {
throw new Error('Execute command log configuration must only be specified when logging is OVERRIDE.');
}
this._executeCommandConfiguration = props.executeCommandConfiguration;
}
const cluster = new CfnCluster(this, 'Resource', {
clusterName: this.physicalName,
clusterSettings,
configuration: this._executeCommandConfiguration && this.renderExecuteCommandConfiguration(),
});
this.clusterArn = this.getResourceArnAttribute(cluster.attrArn, {
service: 'ecs',
resource: 'cluster',
resourceName: this.physicalName,
});
this.clusterName = this.getResourceNameAttribute(cluster.ref);
this.vpc = props.vpc || new ec2.Vpc(this, 'Vpc', { maxAzs: 2 });
this._defaultCloudMapNamespace = props.defaultCloudMapNamespace !== undefined
? this.addDefaultCloudMapNamespace(props.defaultCloudMapNamespace)
: undefined;
this._autoscalingGroup = props.capacity !== undefined
? this.addCapacity('DefaultAutoScalingGroup', props.capacity)
: undefined;
// Only create cluster capacity provider associations if there are any EC2
// capacity providers. Ordinarily we'd just add the construct to the tree
// since it's harmless, but we'd prefer not to add unexpected new
// resources to the stack which could surprise users working with
// brown-field CDK apps and stacks.
Aspects.of(this).add(new MaybeCreateCapacityProviderAssociations(this, id, this._capacityProviderNames));
}
/**
* Enable the Fargate capacity providers for this cluster.
*/
public enableFargateCapacityProviders() {
for (const provider of ['FARGATE', 'FARGATE_SPOT']) {
if (!this._capacityProviderNames.includes(provider)) {
this._capacityProviderNames.push(provider);
}
}
}
private renderExecuteCommandConfiguration() : CfnCluster.ClusterConfigurationProperty {
return {
executeCommandConfiguration: {
kmsKeyId: this._executeCommandConfiguration?.kmsKey?.keyArn,
logConfiguration: this._executeCommandConfiguration?.logConfiguration && this.renderExecuteCommandLogConfiguration(),
logging: this._executeCommandConfiguration?.logging,
},
};
}
private renderExecuteCommandLogConfiguration(): CfnCluster.ExecuteCommandLogConfigurationProperty {
const logConfiguration = this._executeCommandConfiguration?.logConfiguration;
if (logConfiguration?.s3EncryptionEnabled && !logConfiguration?.s3Bucket) {
throw new Error('You must specify an S3 bucket name in the execute command log configuration to enable S3 encryption.');
}
if (logConfiguration?.cloudWatchEncryptionEnabled && !logConfiguration?.cloudWatchLogGroup) {
throw new Error('You must specify a CloudWatch log group in the execute command log configuration to enable CloudWatch encryption.');
}
return {
cloudWatchEncryptionEnabled: logConfiguration?.cloudWatchEncryptionEnabled,
cloudWatchLogGroupName: logConfiguration?.cloudWatchLogGroup?.logGroupName,
s3BucketName: logConfiguration?.s3Bucket?.bucketName,
s3EncryptionEnabled: logConfiguration?.s3EncryptionEnabled,
s3KeyPrefix: logConfiguration?.s3KeyPrefix,
};
}
/**
* Add an AWS Cloud Map DNS namespace for this cluster.
* NOTE: HttpNamespaces are not supported, as ECS always requires a DNSConfig when registering an instance to a Cloud
* Map service.
*/
public addDefaultCloudMapNamespace(options: CloudMapNamespaceOptions): cloudmap.INamespace {
if (this._defaultCloudMapNamespace !== undefined) {
throw new Error('Can only add default namespace once.');
}
const namespaceType = options.type !== undefined
? options.type
: cloudmap.NamespaceType.DNS_PRIVATE;
const sdNamespace = namespaceType === cloudmap.NamespaceType.DNS_PRIVATE ?
new cloudmap.PrivateDnsNamespace(this, 'DefaultServiceDiscoveryNamespace', {
name: options.name,
vpc: this.vpc,
}) :
new cloudmap.PublicDnsNamespace(this, 'DefaultServiceDiscoveryNamespace', {
name: options.name,
});
this._defaultCloudMapNamespace = sdNamespace;
return sdNamespace;
}
/**
* Getter for namespace added to cluster
*/
public get defaultCloudMapNamespace(): cloudmap.INamespace | undefined {
return this._defaultCloudMapNamespace;
}
/**
* This method adds compute capacity to a cluster by creating an AutoScalingGroup with the specified options.
*
* Returns the AutoScalingGroup so you can add autoscaling settings to it.
*
* @deprecated Use {@link Cluster.addAsgCapacityProvider} instead.
*/
public addCapacity(id: string, options: AddCapacityOptions): autoscaling.AutoScalingGroup {
if (options.machineImage && options.machineImageType) {
throw new Error('You can only specify either machineImage or machineImageType, not both.');
}
const machineImage = options.machineImage ?? options.machineImageType === MachineImageType.BOTTLEROCKET ?
new BottleRocketImage() : new EcsOptimizedAmi();
const autoScalingGroup = new autoscaling.AutoScalingGroup(this, id, {
vpc: this.vpc,
machineImage,
updateType: options.updateType || autoscaling.UpdateType.REPLACING_UPDATE,
...options,
});
this.addAutoScalingGroup(autoScalingGroup, {
machineImageType: options.machineImageType,
...options,
});
return autoScalingGroup;
}
/**
* This method adds an Auto Scaling Group Capacity Provider to a cluster.
*
* @param provider the capacity provider to add to this cluster.
*/
public addAsgCapacityProvider(provider: AsgCapacityProvider, options: AddAutoScalingGroupCapacityOptions = {}) {
// Don't add the same capacity provider more than once.
if (this._capacityProviderNames.includes(provider.capacityProviderName)) {
return;
}
this._hasEc2Capacity = true;
this.configureAutoScalingGroup(provider.autoScalingGroup, {
...options,
// Don't enable the instance-draining lifecycle hook if managed termination protection is enabled
taskDrainTime: provider.enableManagedTerminationProtection ? Duration.seconds(0) : options.taskDrainTime,
});
this._capacityProviderNames.push(provider.capacityProviderName);
}
/**
* This method adds compute capacity to a cluster using the specified AutoScalingGroup.
*
* @deprecated Use {@link Cluster.addAsgCapacityProvider} instead.
* @param autoScalingGroup the ASG to add to this cluster.
* [disable-awslint:ref-via-interface] is needed in order to install the ECS
* agent by updating the ASGs user data.
*/
public addAutoScalingGroup(autoScalingGroup: autoscaling.AutoScalingGroup, options: AddAutoScalingGroupCapacityOptions = {}) {
this._hasEc2Capacity = true;
this.connections.connections.addSecurityGroup(...autoScalingGroup.connections.securityGroups);
this.configureAutoScalingGroup(autoScalingGroup, options);
}
private configureAutoScalingGroup(autoScalingGroup: autoscaling.AutoScalingGroup, options: AddAutoScalingGroupCapacityOptions = {}) {
if (autoScalingGroup.osType === ec2.OperatingSystemType.WINDOWS) {
this.configureWindowsAutoScalingGroup(autoScalingGroup, options);
} else {
// Tie instances to cluster
switch (options.machineImageType) {
// Bottlerocket AMI
case MachineImageType.BOTTLEROCKET: {
autoScalingGroup.addUserData(
// Connect to the cluster
// Source: https://github.com/bottlerocket-os/bottlerocket/blob/develop/QUICKSTART-ECS.md#connecting-to-your-cluster
'[settings.ecs]',
`cluster = "${this.clusterName}"`,
);
// Enabling SSM
// Source: https://github.com/bottlerocket-os/bottlerocket/blob/develop/QUICKSTART-ECS.md#enabling-ssm
autoScalingGroup.role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonSSMManagedInstanceCore'));
// required managed policy
autoScalingGroup.role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonEC2ContainerServiceforEC2Role'));
break;
}
default:
// Amazon ECS-optimized AMI for Amazon Linux 2
autoScalingGroup.addUserData(`echo ECS_CLUSTER=${this.clusterName} >> /etc/ecs/ecs.config`);
if (!options.canContainersAccessInstanceRole) {
// Deny containers access to instance metadata service
// Source: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/instance_IAM_role.html
autoScalingGroup.addUserData('sudo iptables --insert FORWARD 1 --in-interface docker+ --destination 169.254.169.254/32 --jump DROP');
autoScalingGroup.addUserData('sudo service iptables save');
// The following is only for AwsVpc networking mode, but doesn't hurt for the other modes.
autoScalingGroup.addUserData('echo ECS_AWSVPC_BLOCK_IMDS=true >> /etc/ecs/ecs.config');
}
if (autoScalingGroup.spotPrice && options.spotInstanceDraining) {
autoScalingGroup.addUserData('echo ECS_ENABLE_SPOT_INSTANCE_DRAINING=true >> /etc/ecs/ecs.config');
}
}
}
// ECS instances must be able to do these things
// Source: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/instance_IAM_role.html
// But, scoped down to minimal permissions required.
// Notes:
// - 'ecs:CreateCluster' removed. The cluster already exists.
autoScalingGroup.addToRolePolicy(new iam.PolicyStatement({
actions: [
'ecs:DeregisterContainerInstance',
'ecs:RegisterContainerInstance',
'ecs:Submit*',
],
resources: [
this.clusterArn,
],
}));
autoScalingGroup.addToRolePolicy(new iam.PolicyStatement({
actions: [
// These act on a cluster instance, and the instance doesn't exist until the service starts.
// Thus, scope to the cluster using a condition.
// See: https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonelasticcontainerservice.html
'ecs:Poll',
'ecs:StartTelemetrySession',
],
resources: ['*'],
conditions: {
ArnEquals: { 'ecs:cluster': this.clusterArn },
},
}));
autoScalingGroup.addToRolePolicy(new iam.PolicyStatement({
actions: [
// These do not support resource constraints, and must be resource '*'
'ecs:DiscoverPollEndpoint',
'ecr:GetAuthorizationToken',
// Preserved for backwards compatibility.
// Users are able to enable cloudwatch agent using CDK. Existing
// customers might be installing CW agent as part of user-data so if we
// remove these permissions we will break that customer use cases.
'logs:CreateLogStream',
'logs:PutLogEvents',
],
resources: ['*'],
}));
// 0 disables, otherwise forward to underlying implementation which picks the sane default
if (!options.taskDrainTime || options.taskDrainTime.toSeconds() !== 0) {
new InstanceDrainHook(autoScalingGroup, 'DrainECSHook', {
autoScalingGroup,
cluster: this,
drainTime: options.taskDrainTime,
topicEncryptionKey: options.topicEncryptionKey,
});
}
}
/**
* This method enables the Fargate or Fargate Spot capacity providers on the cluster.
*
* @param provider the capacity provider to add to this cluster.
* @deprecated Use {@link enableFargateCapacityProviders} instead.
* @see {@link addAsgCapacityProvider} to add an Auto Scaling Group capacity provider to the cluster.
*/
public addCapacityProvider(provider: string) {
if (!(provider === 'FARGATE' || provider === 'FARGATE_SPOT')) {
throw new Error('CapacityProvider not supported');
}
if (!this._capacityProviderNames.includes(provider)) {
this._capacityProviderNames.push(provider);
}
}
private configureWindowsAutoScalingGroup(autoScalingGroup: autoscaling.AutoScalingGroup, options: AddAutoScalingGroupCapacityOptions = {}) {
// clear the cache of the agent
autoScalingGroup.addUserData('Remove-Item -Recurse C:\\ProgramData\\Amazon\\ECS\\Cache');
// pull the latest ECS Tools
autoScalingGroup.addUserData('Import-Module ECSTools');
// set the cluster name environment variable
autoScalingGroup.addUserData(`[Environment]::SetEnvironmentVariable("ECS_CLUSTER", "${this.clusterName}", "Machine")`);
autoScalingGroup.addUserData('[Environment]::SetEnvironmentVariable("ECS_ENABLE_AWSLOGS_EXECUTIONROLE_OVERRIDE", "true", "Machine")');
// tslint:disable-next-line: max-line-length
autoScalingGroup.addUserData('[Environment]::SetEnvironmentVariable("ECS_AVAILABLE_LOGGING_DRIVERS", \'["json-file","awslogs"]\', "Machine")');
// enable instance draining
if (autoScalingGroup.spotPrice && options.spotInstanceDraining) {
autoScalingGroup.addUserData('[Environment]::SetEnvironmentVariable("ECS_ENABLE_SPOT_INSTANCE_DRAINING", "true", "Machine")');
}
// enable task iam role
if (!options.canContainersAccessInstanceRole) {
autoScalingGroup.addUserData('[Environment]::SetEnvironmentVariable("ECS_ENABLE_TASK_IAM_ROLE", "true", "Machine")');
autoScalingGroup.addUserData(`Initialize-ECSAgent -Cluster '${this.clusterName}' -EnableTaskIAMRole`);
} else {
autoScalingGroup.addUserData(`Initialize-ECSAgent -Cluster '${this.clusterName}'`);
}
}
/**
* Getter for autoscaling group added to cluster
*/
public get autoscalingGroup(): autoscaling.IAutoScalingGroup | undefined {
return this._autoscalingGroup;
}
/**
* Whether the cluster has EC2 capacity associated with it
*/
public get hasEc2Capacity(): boolean {
return this._hasEc2Capacity;
}
/**
* Getter for execute command configuration associated with the cluster.
*/
public get executeCommandConfiguration(): ExecuteCommandConfiguration | undefined {
return this._executeCommandConfiguration;
}
/**
* This method returns the CloudWatch metric for this clusters CPU reservation.
*
* @default average over 5 minutes
*/
public metricCpuReservation(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.cannedMetric(ECSMetrics.cpuReservationAverage, props);
}
/**
* This method returns the CloudWatch metric for this clusters CPU utilization.
*
* @default average over 5 minutes
*/
public metricCpuUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.cannedMetric(ECSMetrics.cpuUtilizationAverage, props);
}
/**
* This method returns the CloudWatch metric for this clusters memory reservation.
*
* @default average over 5 minutes
*/
public metricMemoryReservation(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.cannedMetric(ECSMetrics.memoryReservationAverage, props);
}
/**
* This method returns the CloudWatch metric for this clusters memory utilization.
*
* @default average over 5 minutes
*/
public metricMemoryUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.cannedMetric(ECSMetrics.memoryUtilizationAverage, props);
}
/**
* This method returns the specifed CloudWatch metric for this cluster.
*/
public metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return new cloudwatch.Metric({
namespace: 'AWS/ECS',
metricName,
dimensions: { ClusterName: this.clusterName },
...props,
}).attachTo(this);
}
private cannedMetric(
fn: (dims: { ClusterName: string }) => cloudwatch.MetricProps,
props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return new cloudwatch.Metric({
...fn({ ClusterName: this.clusterName }),
...props,
}).attachTo(this);
}
}
/**
* ECS-optimized Windows version list
*/
export enum WindowsOptimizedVersion {
SERVER_2019 = '2019',
SERVER_2016 = '2016',
}
/*
* TODO:v2.0.0
* * remove `export` keyword
* * remove @deprecated
*/
/**
* The properties that define which ECS-optimized AMI is used.
*
* @deprecated see {@link EcsOptimizedImage}
*/
export interface EcsOptimizedAmiProps {
/**
* The Amazon Linux generation to use.
*
* @default AmazonLinuxGeneration.AmazonLinux2
*/
readonly generation?: ec2.AmazonLinuxGeneration;
/**
* The Windows Server version to use.
*
* @default none, uses Linux generation
*/
readonly windowsVersion?: WindowsOptimizedVersion;
/**
* The ECS-optimized AMI variant to use.
*
* @default AmiHardwareType.Standard
*/
readonly hardwareType?: AmiHardwareType;
}
/*
* TODO:v2.0.0 remove EcsOptimizedAmi
*/
/**
* Construct a Linux or Windows machine image from the latest ECS Optimized AMI published in SSM
*
* @deprecated see {@link EcsOptimizedImage#amazonLinux}, {@link EcsOptimizedImage#amazonLinux} and {@link EcsOptimizedImage#windows}
*/
export class EcsOptimizedAmi implements ec2.IMachineImage {
private readonly generation?: ec2.AmazonLinuxGeneration;
private readonly windowsVersion?: WindowsOptimizedVersion;
private readonly hwType: AmiHardwareType;
private readonly amiParameterName: string;
/**
* Constructs a new instance of the EcsOptimizedAmi class.
*/
constructor(props?: EcsOptimizedAmiProps) {
this.hwType = (props && props.hardwareType) || AmiHardwareType.STANDARD;
if (props && props.generation) { // generation defined in the props object
if (props.generation === ec2.AmazonLinuxGeneration.AMAZON_LINUX && this.hwType !== AmiHardwareType.STANDARD) {
throw new Error('Amazon Linux does not support special hardware type. Use Amazon Linux 2 instead');
} else if (props.windowsVersion) {
throw new Error('"windowsVersion" and Linux image "generation" cannot be both set');
} else {
this.generation = props.generation;
}
} else if (props && props.windowsVersion) {
if (this.hwType !== AmiHardwareType.STANDARD) {
throw new Error('Windows Server does not support special hardware type');
} else {
this.windowsVersion = props.windowsVersion;
}
} else { // generation not defined in props object
// always default to Amazon Linux v2 regardless of HW
this.generation = ec2.AmazonLinuxGeneration.AMAZON_LINUX_2;
}
// set the SSM parameter name
this.amiParameterName = '/aws/service/ecs/optimized-ami/'
+ (this.generation === ec2.AmazonLinuxGeneration.AMAZON_LINUX ? 'amazon-linux/' : '')
+ (this.generation === ec2.AmazonLinuxGeneration.AMAZON_LINUX_2 ? 'amazon-linux-2/' : '')
+ (this.windowsVersion ? `windows_server/${this.windowsVersion}/english/full/` : '')
+ (this.hwType === AmiHardwareType.GPU ? 'gpu/' : '')
+ (this.hwType === AmiHardwareType.ARM ? 'arm64/' : '')
+ 'recommended/image_id';
}
/**
* Return the correct image
*/
public getImage(scope: CoreConstruct): ec2.MachineImageConfig {
const ami = ssm.StringParameter.valueForTypedStringParameter(scope, this.amiParameterName, ssm.ParameterType.AWS_EC2_IMAGE_ID);
const osType = this.windowsVersion ? ec2.OperatingSystemType.WINDOWS : ec2.OperatingSystemType.LINUX;
return {
imageId: ami,
osType,
userData: ec2.UserData.forOperatingSystem(osType),
};
}
}
/**
* Construct a Linux or Windows machine image from the latest ECS Optimized AMI published in SSM
*/
export class EcsOptimizedImage implements ec2.IMachineImage {
/**
* Construct an Amazon Linux 2 image from the latest ECS Optimized AMI published in SSM
*
* @param hardwareType ECS-optimized AMI variant to use
*/
public static amazonLinux2(hardwareType = AmiHardwareType.STANDARD): EcsOptimizedImage {
return new EcsOptimizedImage({ generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2, hardwareType });
}
/**
* Construct an Amazon Linux AMI image from the latest ECS Optimized AMI published in SSM
*/
public static amazonLinux(): EcsOptimizedImage {
return new EcsOptimizedImage({ generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX });
}
/**
* Construct a Windows image from the latest ECS Optimized AMI published in SSM
*
* @param windowsVersion Windows Version to use
*/
public static windows(windowsVersion: WindowsOptimizedVersion): EcsOptimizedImage {
return new EcsOptimizedImage({ windowsVersion });
}
private readonly generation?: ec2.AmazonLinuxGeneration;
private readonly windowsVersion?: WindowsOptimizedVersion;
private readonly hwType?: AmiHardwareType;
private readonly amiParameterName: string;
/**
* Constructs a new instance of the EcsOptimizedAmi class.
*/
private constructor(props: EcsOptimizedAmiProps) {
this.hwType = props && props.hardwareType;
if (props.windowsVersion) {
this.windowsVersion = props.windowsVersion;
} else if (props.generation) {
this.generation = props.generation;
} else {
throw new Error('This error should never be thrown');
}
// set the SSM parameter name
this.amiParameterName = '/aws/service/ecs/optimized-ami/'
+ (this.generation === ec2.AmazonLinuxGeneration.AMAZON_LINUX ? 'amazon-linux/' : '')
+ (this.generation === ec2.AmazonLinuxGeneration.AMAZON_LINUX_2 ? 'amazon-linux-2/' : '')
+ (this.windowsVersion ? `windows_server/${this.windowsVersion}/english/full/` : '')
+ (this.hwType === AmiHardwareType.GPU ? 'gpu/' : '')
+ (this.hwType === AmiHardwareType.ARM ? 'arm64/' : '')
+ 'recommended/image_id';
}
/**
* Return the correct image
*/
public getImage(scope: CoreConstruct): ec2.MachineImageConfig {
const ami = ssm.StringParameter.valueForTypedStringParameter(scope, this.amiParameterName, ssm.ParameterType.AWS_EC2_IMAGE_ID);
const osType = this.windowsVersion ? ec2.OperatingSystemType.WINDOWS : ec2.OperatingSystemType.LINUX;
return {
imageId: ami,
osType,
userData: ec2.UserData.forOperatingSystem(osType),
};
}
}
/**
* Amazon ECS variant
*/
export enum BottlerocketEcsVariant {
/**
* aws-ecs-1 variant
*/
AWS_ECS_1 = 'aws-ecs-1'
}
/**
* Properties for BottleRocketImage
*/
export interface BottleRocketImageProps {
/**
* The Amazon ECS variant to use.
* Only `aws-ecs-1` is currently available
*
* @default - BottlerocketEcsVariant.AWS_ECS_1
*/
readonly variant?: BottlerocketEcsVariant;
}
/**
* Construct an Bottlerocket image from the latest AMI published in SSM
*/
export class BottleRocketImage implements ec2.IMachineImage {
private readonly amiParameterName: string;
/**
* Amazon ECS variant for Bottlerocket AMI
*/
private readonly variant: string;
/**
* Constructs a new instance of the BottleRocketImage class.
*/
public constructor(props: BottleRocketImageProps = {}) {
this.variant = props.variant ?? BottlerocketEcsVariant.AWS_ECS_1;
// set the SSM parameter name
this.amiParameterName = `/aws/service/bottlerocket/${this.variant}/x86_64/latest/image_id`;
}
/**
* Return the correct image
*/
public getImage(scope: CoreConstruct): ec2.MachineImageConfig {
const ami = ssm.StringParameter.valueForStringParameter(scope, this.amiParameterName);
return {
imageId: ami,
osType: ec2.OperatingSystemType.LINUX,
userData: ec2.UserData.custom(''),
};
}
}
/**
* A regional grouping of one or more container instances on which you can run tasks and services.
*/
export interface ICluster extends IResource {
/**
* The name of the cluster.
* @attribute
*/
readonly clusterName: string;
/**
* The Amazon Resource Name (ARN) that identifies the cluster.
* @attribute
*/
readonly clusterArn: string;
/**
* The VPC associated with the cluster.
*/
readonly vpc: ec2.IVpc;
/**
* Manage the allowed network connections for the cluster with Security Groups.
*/
readonly connections: ec2.Connections;
/**
* Specifies whether the cluster has EC2 instance capacity.
*/
readonly hasEc2Capacity: boolean;
/**
* The AWS Cloud Map namespace to associate with the cluster.
*/
readonly defaultCloudMapNamespace?: cloudmap.INamespace;
/**
* The autoscaling group added to the cluster if capacity is associated to the cluster
*/
readonly autoscalingGroup?: autoscaling.IAutoScalingGroup;
/**
* The execute command configuration for the cluster
*/
readonly executeCommandConfiguration?: ExecuteCommandConfiguration;
}
/**
* The properties to import from the ECS cluster.
*/
export interface ClusterAttributes {
/**
* The name of the cluster.
*/
readonly clusterName: string;
/**
* The Amazon Resource Name (ARN) that identifies the cluster.
*
* @default Derived from clusterName
*/
readonly clusterArn?: string;
/**
* The VPC associated with the cluster.
*/
readonly vpc: ec2.IVpc;
/**
* The security groups associated with the container instances registered to the cluster.
*/
readonly securityGroups: ec2.ISecurityGroup[];
/**
* Specifies whether the cluster has EC2 instance capacity.
*
* @default true
*/
readonly hasEc2Capacity?: boolean;
/**
* The AWS Cloud Map namespace to associate with the cluster.
*
* @default - No default namespace
*/
readonly defaultCloudMapNamespace?: cloudmap.INamespace;
/**
* Autoscaling group added to the cluster if capacity is added
*
* @default - No default autoscaling group
*/
readonly autoscalingGroup?: autoscaling.IAutoScalingGroup;
/**
* The execute command configuration for the cluster
*
* @default - none.
*/
readonly executeCommandConfiguration?: ExecuteCommandConfiguration;
}
/**
* An Cluster that has been imported
*/
class ImportedCluster extends Resource implements ICluster {
/**
* Name of the cluster
*/
public readonly clusterName: string;
/**
* ARN of the cluster
*/
public readonly clusterArn: string;
/**
* VPC that the cluster instances are running in
*/
public readonly vpc: ec2.IVpc;
/**
* Security group of the cluster instances
*/
public readonly connections = new ec2.Connections();
/**
* Whether the cluster has EC2 capacity
*/
public readonly hasEc2Capacity: boolean;
/**
* Cloudmap namespace created in the cluster
*/
private _defaultCloudMapNamespace?: cloudmap.INamespace;
/**
* The execute command configuration for the cluster
*/
private _executeCommandConfiguration?: ExecuteCommandConfiguration;
/**
* Constructs a new instance of the ImportedCluster class.
*/
constructor(scope: Construct, id: string, props: ClusterAttributes) {
super(scope, id);
this.clusterName = props.clusterName;
this.vpc = props.vpc;
this.hasEc2Capacity = props.hasEc2Capacity !== false;
this._defaultCloudMapNamespace = props.defaultCloudMapNamespace;
this._executeCommandConfiguration = props.executeCommandConfiguration;
this.clusterArn = props.clusterArn ?? Stack.of(this).formatArn({
service: 'ecs',
resource: 'cluster',
resourceName: props.clusterName,
});
this.connections = new ec2.Connections({
securityGroups: props.securityGroups,
});
}
public get defaultCloudMapNamespace(): cloudmap.INamespace | undefined {
return this._defaultCloudMapNamespace;
}
public get executeCommandConfiguration(): ExecuteCommandConfiguration | undefined {
return this._executeCommandConfiguration;
}
}
/**
* The properties for adding an AutoScalingGroup.
*/
export interface AddAutoScalingGroupCapacityOptions {
/**
* Specifies whether the containers can access the container instance role.
*
* @default false
*/
readonly canContainersAccessInstanceRole?: boolean;
/**
* The time period to wait before force terminating an instance that is draining.
*
* This creates a Lambda function that is used by a lifecycle hook for the
* AutoScalingGroup that will delay instance termination until all ECS tasks
* have drained from the instance. Set to 0 to disable task draining.
*
* Set to 0 to disable task draining.
*
* @deprecated The lifecycle draining hook is not configured if using the EC2 Capacity Provider. Enable managed termination protection instead.
* @default Duration.minutes(5)
*/
readonly taskDrainTime?: Duration;