-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathtask-definition.ts
1130 lines (997 loc) · 37.7 KB
/
task-definition.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 ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import { IResource, Lazy, Names, PhysicalName, Resource } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { ContainerDefinition, ContainerDefinitionOptions, PortMapping, Protocol } from '../container-definition';
import { CfnTaskDefinition } from '../ecs.generated';
import { FirelensLogRouter, FirelensLogRouterDefinitionOptions, FirelensLogRouterType, obtainDefaultFluentBitECRImage } from '../firelens-log-router';
import { AwsLogDriver } from '../log-drivers/aws-log-driver';
import { PlacementConstraint } from '../placement';
import { ProxyConfiguration } from '../proxy-configuration/proxy-configuration';
import { RuntimePlatform } from '../runtime-platform';
import { ImportedTaskDefinition } from './_imported-task-definition';
/**
* The interface for all task definitions.
*/
export interface ITaskDefinition extends IResource {
/**
* ARN of this task definition
* @attribute
*/
readonly taskDefinitionArn: string;
/**
* Execution role for this task definition
*/
readonly executionRole?: iam.IRole;
/**
* What launch types this task definition should be compatible with.
*/
readonly compatibility: Compatibility;
/**
* Return true if the task definition can be run on an EC2 cluster
*/
readonly isEc2Compatible: boolean;
/**
* Return true if the task definition can be run on a Fargate cluster
*/
readonly isFargateCompatible: boolean;
/**
* Return true if the task definition can be run on a ECS Anywhere cluster
*/
readonly isExternalCompatible: boolean;
/**
* The networking mode to use for the containers in the task.
*/
readonly networkMode: NetworkMode;
/**
* The name of the IAM role that grants containers in the task permission to call AWS APIs on your behalf.
*/
readonly taskRole: iam.IRole;
}
/**
* The common properties for all task definitions. For more information, see
* [Task Definition Parameters](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html).
*/
export interface CommonTaskDefinitionProps {
/**
* 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 name of the IAM task execution role that grants the ECS agent permission to call AWS APIs on your behalf.
*
* The role will be used to retrieve container images from ECR and create CloudWatch log groups.
*
* @default - An execution role will be automatically created if you use ECR images in your task definition.
*/
readonly executionRole?: iam.IRole;
/**
* The name of the 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?: iam.IRole;
/**
* The configuration details for the App Mesh proxy.
*
* @default - No proxy configuration.
*/
readonly proxyConfiguration?: ProxyConfiguration;
/**
* The list of volume definitions for the task. For more information, see
* [Task Definition Parameter Volumes](https://docs.aws.amazon.com/AmazonECS/latest/developerguide//task_definition_parameters.html#volumes).
*
* @default - No volumes are passed to the Docker daemon on a container instance.
*/
readonly volumes?: Volume[];
}
/**
* The properties for task definitions.
*/
export interface TaskDefinitionProps extends CommonTaskDefinitionProps {
/**
* The networking mode to use for the containers in the task.
*
* On Fargate, the only supported networking mode is AwsVpc.
*
* @default - NetworkMode.Bridge for EC2 & External tasks, AwsVpc for Fargate tasks.
*/
readonly networkMode?: NetworkMode;
/**
* The placement constraints to use for tasks in the service.
*
* You can specify a maximum of 10 constraints per task (this limit includes
* constraints in the task definition and those specified at run time).
*
* Not supported in Fargate.
*
* @default - No placement constraints.
*/
readonly placementConstraints?: PlacementConstraint[];
/**
* The task launch type compatiblity requirement.
*/
readonly compatibility: Compatibility;
/**
* The number of cpu units used by the task.
*
* If you are using the EC2 launch type, this field is optional and any value can be used.
* If you are using the Fargate launch type, this field is required and you must use one of the following values,
* which determines your range of valid values for the memory parameter:
*
* 256 (.25 vCPU) - Available memory values: 512 (0.5 GB), 1024 (1 GB), 2048 (2 GB)
*
* 512 (.5 vCPU) - Available memory values: 1024 (1 GB), 2048 (2 GB), 3072 (3 GB), 4096 (4 GB)
*
* 1024 (1 vCPU) - Available memory values: 2048 (2 GB), 3072 (3 GB), 4096 (4 GB), 5120 (5 GB), 6144 (6 GB), 7168 (7 GB), 8192 (8 GB)
*
* 2048 (2 vCPU) - Available memory values: Between 4096 (4 GB) and 16384 (16 GB) in increments of 1024 (1 GB)
*
* 4096 (4 vCPU) - Available memory values: Between 8192 (8 GB) and 30720 (30 GB) in increments of 1024 (1 GB)
*
* @default - CPU units are not specified.
*/
readonly cpu?: string;
/**
* The amount (in MiB) of memory used by the task.
*
* If using the EC2 launch type, this field is optional and any value can be used.
* If using the Fargate launch type, this field is required and you must use one of the following values,
* which determines your range of valid values for the cpu parameter:
*
* 512 (0.5 GB), 1024 (1 GB), 2048 (2 GB) - Available cpu values: 256 (.25 vCPU)
*
* 1024 (1 GB), 2048 (2 GB), 3072 (3 GB), 4096 (4 GB) - Available cpu values: 512 (.5 vCPU)
*
* 2048 (2 GB), 3072 (3 GB), 4096 (4 GB), 5120 (5 GB), 6144 (6 GB), 7168 (7 GB), 8192 (8 GB) - Available cpu values: 1024 (1 vCPU)
*
* Between 4096 (4 GB) and 16384 (16 GB) in increments of 1024 (1 GB) - Available cpu values: 2048 (2 vCPU)
*
* Between 8192 (8 GB) and 30720 (30 GB) in increments of 1024 (1 GB) - Available cpu values: 4096 (4 vCPU)
*
* @default - Memory used by task is not specified.
*/
readonly memoryMiB?: string;
/**
* The IPC resource namespace to use for the containers in the task.
*
* Not supported in Fargate and Windows containers.
*
* @default - IpcMode used by the task is not specified
*/
readonly ipcMode?: IpcMode;
/**
* The process namespace to use for the containers in the task.
*
* Not supported in Fargate and Windows containers.
*
* @default - PidMode used by the task is not specified
*/
readonly pidMode?: PidMode;
/**
* The inference accelerators to use for the containers in the task.
*
* Not supported in Fargate.
*
* @default - No inference accelerators.
*/
readonly inferenceAccelerators?: InferenceAccelerator[];
/**
* The amount (in GiB) of ephemeral storage to be allocated to the task.
*
* Only supported in Fargate platform version 1.4.0 or later.
*
* @default - Undefined, in which case, the task will receive 20GiB ephemeral storage.
*/
readonly ephemeralStorageGiB?: number;
/**
* The operating system that your task definitions are running on.
* A runtimePlatform is supported only for tasks using the Fargate launch type.
*
*
* @default - Undefined.
*/
readonly runtimePlatform?: RuntimePlatform;
}
/**
* The common task definition attributes used across all types of task definitions.
*/
export interface CommonTaskDefinitionAttributes {
/**
* The arn of the task definition
*/
readonly taskDefinitionArn: string;
/**
* The networking mode to use for the containers in the task.
*
* @default Network mode cannot be provided to the imported task.
*/
readonly networkMode?: NetworkMode;
/**
* The name of the IAM role that grants containers in the task permission to call AWS APIs on your behalf.
*
* @default Permissions cannot be granted to the imported task.
*/
readonly taskRole?: iam.IRole;
}
/**
* A reference to an existing task definition
*/
export interface TaskDefinitionAttributes extends CommonTaskDefinitionAttributes {
/**
* What launch types this task definition should be compatible with.
*
* @default Compatibility.EC2_AND_FARGATE
*/
readonly compatibility?: Compatibility;
}
abstract class TaskDefinitionBase extends Resource implements ITaskDefinition {
public abstract readonly compatibility: Compatibility;
public abstract readonly networkMode: NetworkMode;
public abstract readonly taskDefinitionArn: string;
public abstract readonly taskRole: iam.IRole;
public abstract readonly executionRole?: iam.IRole;
/**
* Return true if the task definition can be run on an EC2 cluster
*/
public get isEc2Compatible(): boolean {
return isEc2Compatible(this.compatibility);
}
/**
* Return true if the task definition can be run on a Fargate cluster
*/
public get isFargateCompatible(): boolean {
return isFargateCompatible(this.compatibility);
}
/**
* Return true if the task definition can be run on a ECS anywhere cluster
*/
public get isExternalCompatible(): boolean {
return isExternalCompatible(this.compatibility);
}
}
/**
* The base class for all task definitions.
*/
export class TaskDefinition extends TaskDefinitionBase {
/**
* Imports a task definition from the specified task definition ARN.
*
* The task will have a compatibility of EC2+Fargate.
*/
public static fromTaskDefinitionArn(scope: Construct, id: string, taskDefinitionArn: string): ITaskDefinition {
return new ImportedTaskDefinition(scope, id, { taskDefinitionArn: taskDefinitionArn });
}
/**
* Create a task definition from a task definition reference
*/
public static fromTaskDefinitionAttributes(scope: Construct, id: string, attrs: TaskDefinitionAttributes): ITaskDefinition {
return new ImportedTaskDefinition(scope, id, {
taskDefinitionArn: attrs.taskDefinitionArn,
compatibility: attrs.compatibility,
networkMode: attrs.networkMode,
taskRole: attrs.taskRole,
});
}
/**
* The name of a family that this task definition is registered to.
* A family groups multiple versions of a task definition.
*/
public readonly family: string;
/**
* The full Amazon Resource Name (ARN) of the task definition.
* @attribute
*/
public readonly taskDefinitionArn: string;
/**
* The name of the IAM role that grants containers in the task permission to call AWS APIs on your behalf.
*/
public readonly taskRole: iam.IRole;
/**
* The networking mode to use for the containers in the task.
*/
public readonly networkMode: NetworkMode;
/**
* Default container for this task
*
* Load balancers will send traffic to this container. The first
* essential container that is added to this task will become the default
* container.
*/
public defaultContainer?: ContainerDefinition;
/**
* The task launch type compatibility requirement.
*/
public readonly compatibility: Compatibility;
/**
* The amount (in GiB) of ephemeral storage to be allocated to the task.
*
* Only supported in Fargate platform version 1.4.0 or later.
*/
public readonly ephemeralStorageGiB?: number;
/**
* The container definitions.
*/
protected readonly containers = new Array<ContainerDefinition>();
/**
* All volumes
*/
private readonly volumes: Volume[] = [];
/**
* Placement constraints for task instances
*/
private readonly placementConstraints = new Array<CfnTaskDefinition.TaskDefinitionPlacementConstraintProperty>();
/**
* Inference accelerators for task instances
*/
private readonly _inferenceAccelerators: InferenceAccelerator[] = [];
private _executionRole?: iam.IRole;
private _referencesSecretJsonField?: boolean;
private runtimePlatform?: RuntimePlatform;
/**
* Constructs a new instance of the TaskDefinition class.
*/
constructor(scope: Construct, id: string, props: TaskDefinitionProps) {
super(scope, id);
this.family = props.family || Names.uniqueId(this);
this.compatibility = props.compatibility;
if (props.volumes) {
props.volumes.forEach(v => this.addVolume(v));
}
this.networkMode = props.networkMode ?? (this.isFargateCompatible ? NetworkMode.AWS_VPC : NetworkMode.BRIDGE);
if (this.isFargateCompatible && this.networkMode !== NetworkMode.AWS_VPC) {
throw new Error(`Fargate tasks can only have AwsVpc network mode, got: ${this.networkMode}`);
}
if (props.proxyConfiguration && this.networkMode !== NetworkMode.AWS_VPC) {
throw new Error(`ProxyConfiguration can only be used with AwsVpc network mode, got: ${this.networkMode}`);
}
if (props.placementConstraints && props.placementConstraints.length > 0 && this.isFargateCompatible) {
throw new Error('Cannot set placement constraints on tasks that run on Fargate');
}
if (this.isFargateCompatible && (!props.cpu || !props.memoryMiB)) {
throw new Error(`Fargate-compatible tasks require both CPU (${props.cpu}) and memory (${props.memoryMiB}) specifications`);
}
if (props.inferenceAccelerators && props.inferenceAccelerators.length > 0 && this.isFargateCompatible) {
throw new Error('Cannot use inference accelerators on tasks that run on Fargate');
}
if (this.isExternalCompatible && this.networkMode !== NetworkMode.BRIDGE) {
throw new Error(`External tasks can only have Bridge network mode, got: ${this.networkMode}`);
}
if (!this.isFargateCompatible && props.runtimePlatform) {
throw new Error('Cannot specify runtimePlatform in non-Fargate compatible tasks');
}
this._executionRole = props.executionRole;
this.taskRole = props.taskRole || new iam.Role(this, 'TaskRole', {
assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
});
if (props.inferenceAccelerators) {
props.inferenceAccelerators.forEach(ia => this.addInferenceAccelerator(ia));
}
this.ephemeralStorageGiB = props.ephemeralStorageGiB;
// validate the cpu and memory size for the Windows operation system family.
if (props.runtimePlatform?.operatingSystemFamily?._operatingSystemFamily.includes('WINDOWS')) {
// We know that props.cpu and props.memoryMiB are defined because an error would have been thrown previously if they were not.
// But, typescript is not able to figure this out, so using the `!` operator here to let the type-checker know they are defined.
this.checkFargateWindowsBasedTasksSize(props.cpu!, props.memoryMiB!, props.runtimePlatform!);
}
this.runtimePlatform = props.runtimePlatform;
const taskDef = new CfnTaskDefinition(this, 'Resource', {
containerDefinitions: Lazy.any({ produce: () => this.renderContainers() }, { omitEmptyArray: true }),
volumes: Lazy.any({ produce: () => this.renderVolumes() }, { omitEmptyArray: true }),
executionRoleArn: Lazy.string({ produce: () => this.executionRole && this.executionRole.roleArn }),
family: this.family,
taskRoleArn: this.taskRole.roleArn,
requiresCompatibilities: [
...(isEc2Compatible(props.compatibility) ? ['EC2'] : []),
...(isFargateCompatible(props.compatibility) ? ['FARGATE'] : []),
...(isExternalCompatible(props.compatibility) ? ['EXTERNAL'] : []),
],
networkMode: this.renderNetworkMode(this.networkMode),
placementConstraints: Lazy.any({
produce: () =>
!isFargateCompatible(this.compatibility) ? this.placementConstraints : undefined,
}, { omitEmptyArray: true }),
proxyConfiguration: props.proxyConfiguration ? props.proxyConfiguration.bind(this.stack, this) : undefined,
cpu: props.cpu,
memory: props.memoryMiB,
ipcMode: props.ipcMode,
pidMode: props.pidMode,
inferenceAccelerators: Lazy.any({
produce: () =>
!isFargateCompatible(this.compatibility) ? this.renderInferenceAccelerators() : undefined,
}, { omitEmptyArray: true }),
ephemeralStorage: this.ephemeralStorageGiB ? {
sizeInGiB: this.ephemeralStorageGiB,
} : undefined,
runtimePlatform: this.isFargateCompatible && this.runtimePlatform ? {
cpuArchitecture: this.runtimePlatform?.cpuArchitecture?._cpuArchitecture,
operatingSystemFamily: this.runtimePlatform?.operatingSystemFamily?._operatingSystemFamily,
} : undefined,
});
if (props.placementConstraints) {
props.placementConstraints.forEach(pc => this.addPlacementConstraint(pc));
}
this.taskDefinitionArn = taskDef.ref;
this.node.addValidation({ validate: () => this.validateTaskDefinition() });
}
public get executionRole(): iam.IRole | undefined {
return this._executionRole;
}
/**
* Public getter method to access list of inference accelerators attached to the instance.
*/
public get inferenceAccelerators(): InferenceAccelerator[] {
return this._inferenceAccelerators;
}
private renderVolumes(): CfnTaskDefinition.VolumeProperty[] {
return this.volumes.map(renderVolume);
function renderVolume(spec: Volume): CfnTaskDefinition.VolumeProperty {
return {
host: spec.host,
name: spec.name,
dockerVolumeConfiguration: spec.dockerVolumeConfiguration && {
autoprovision: spec.dockerVolumeConfiguration.autoprovision,
driver: spec.dockerVolumeConfiguration.driver,
driverOpts: spec.dockerVolumeConfiguration.driverOpts,
labels: spec.dockerVolumeConfiguration.labels,
scope: spec.dockerVolumeConfiguration.scope,
},
efsVolumeConfiguration: spec.efsVolumeConfiguration && {
filesystemId: spec.efsVolumeConfiguration.fileSystemId,
authorizationConfig: spec.efsVolumeConfiguration.authorizationConfig,
rootDirectory: spec.efsVolumeConfiguration.rootDirectory,
transitEncryption: spec.efsVolumeConfiguration.transitEncryption,
transitEncryptionPort: spec.efsVolumeConfiguration.transitEncryptionPort,
},
};
}
}
private renderInferenceAccelerators(): CfnTaskDefinition.InferenceAcceleratorProperty[] {
return this._inferenceAccelerators.map(renderInferenceAccelerator);
function renderInferenceAccelerator(inferenceAccelerator: InferenceAccelerator) : CfnTaskDefinition.InferenceAcceleratorProperty {
return {
deviceName: inferenceAccelerator.deviceName,
deviceType: inferenceAccelerator.deviceType,
};
}
}
/**
* Validate the existence of the input target and set default values.
*
* @internal
*/
public _validateTarget(options: LoadBalancerTargetOptions): LoadBalancerTarget {
const targetContainer = this.findContainer(options.containerName);
if (targetContainer === undefined) {
throw new Error(`No container named '${options.containerName}'. Did you call "addContainer()"?`);
}
const targetProtocol = options.protocol || Protocol.TCP;
const targetContainerPort = options.containerPort || targetContainer.containerPort;
const portMapping = targetContainer.findPortMapping(targetContainerPort, targetProtocol);
if (portMapping === undefined) {
// eslint-disable-next-line max-len
throw new Error(`Container '${targetContainer}' has no mapping for port ${options.containerPort} and protocol ${targetProtocol}. Did you call "container.addPortMappings()"?`);
}
return {
containerName: options.containerName,
portMapping,
};
}
/**
* Returns the port range to be opened that match the provided container name and container port.
*
* @internal
*/
public _portRangeFromPortMapping(portMapping: PortMapping): ec2.Port {
if (portMapping.hostPort !== undefined && portMapping.hostPort !== 0) {
return portMapping.protocol === Protocol.UDP ? ec2.Port.udp(portMapping.hostPort) : ec2.Port.tcp(portMapping.hostPort);
}
if (this.networkMode === NetworkMode.BRIDGE || this.networkMode === NetworkMode.NAT) {
return EPHEMERAL_PORT_RANGE;
}
return portMapping.protocol === Protocol.UDP ? ec2.Port.udp(portMapping.containerPort) : ec2.Port.tcp(portMapping.containerPort);
}
/**
* Adds a policy statement to the task IAM role.
*/
public addToTaskRolePolicy(statement: iam.PolicyStatement) {
this.taskRole.addToPrincipalPolicy(statement);
}
/**
* Adds a policy statement to the task execution IAM role.
*/
public addToExecutionRolePolicy(statement: iam.PolicyStatement) {
this.obtainExecutionRole().addToPrincipalPolicy(statement);
}
/**
* Adds a new container to the task definition.
*/
public addContainer(id: string, props: ContainerDefinitionOptions) {
return new ContainerDefinition(this, id, { taskDefinition: this, ...props });
}
/**
* Adds a firelens log router to the task definition.
*/
public addFirelensLogRouter(id: string, props: FirelensLogRouterDefinitionOptions) {
// only one firelens log router is allowed in each task.
if (this.containers.find(x => x instanceof FirelensLogRouter)) {
throw new Error('Firelens log router is already added in this task.');
}
return new FirelensLogRouter(this, id, { taskDefinition: this, ...props });
}
/**
* Links a container to this task definition.
* @internal
*/
public _linkContainer(container: ContainerDefinition) {
this.containers.push(container);
if (this.defaultContainer === undefined && container.essential) {
this.defaultContainer = container;
}
if (container.referencesSecretJsonField) {
this._referencesSecretJsonField = true;
}
}
/**
* Adds a volume to the task definition.
*/
public addVolume(volume: Volume) {
this.volumes.push(volume);
}
/**
* Adds the specified placement constraint to the task definition.
*/
public addPlacementConstraint(constraint: PlacementConstraint) {
if (isFargateCompatible(this.compatibility)) {
throw new Error('Cannot set placement constraints on tasks that run on Fargate');
}
this.placementConstraints.push(...constraint.toJson());
}
/**
* Adds the specified extension to the task definition.
*
* Extension can be used to apply a packaged modification to
* a task definition.
*/
public addExtension(extension: ITaskDefinitionExtension) {
extension.extend(this);
}
/**
* Adds an inference accelerator to the task definition.
*/
public addInferenceAccelerator(inferenceAccelerator: InferenceAccelerator) {
if (isFargateCompatible(this.compatibility)) {
throw new Error('Cannot use inference accelerators on tasks that run on Fargate');
}
this._inferenceAccelerators.push(inferenceAccelerator);
}
/**
* Creates the task execution IAM role if it doesn't already exist.
*/
public obtainExecutionRole(): iam.IRole {
if (!this._executionRole) {
this._executionRole = new iam.Role(this, 'ExecutionRole', {
assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
// needed for cross-account access with TagParameterContainerImage
roleName: PhysicalName.GENERATE_IF_NEEDED,
});
}
return this._executionRole;
}
/**
* Whether this task definition has at least a container that references a
* specific JSON field of a secret stored in Secrets Manager.
*/
public get referencesSecretJsonField(): boolean | undefined {
return this._referencesSecretJsonField;
}
/**
* Validates the task definition.
*/
private validateTaskDefinition(): string[] {
const ret = new Array<string>();
if (isEc2Compatible(this.compatibility)) {
// EC2 mode validations
// Container sizes
for (const container of this.containers) {
if (!container.memoryLimitSpecified) {
ret.push(`ECS Container ${container.containerName} must have at least one of 'memoryLimitMiB' or 'memoryReservationMiB' specified`);
}
}
}
return ret;
}
/**
* Returns the container that match the provided containerName.
*/
public findContainer(containerName: string): ContainerDefinition | undefined {
return this.containers.find(c => c.containerName === containerName);
}
private renderNetworkMode(networkMode: NetworkMode): string | undefined {
return (networkMode === NetworkMode.NAT) ? undefined : networkMode;
}
private renderContainers() {
// add firelens log router container if any application container is using firelens log driver,
// also check if already created log router container
for (const container of this.containers) {
if (container.logDriverConfig && container.logDriverConfig.logDriver === 'awsfirelens'
&& !this.containers.find(x => x instanceof FirelensLogRouter)) {
this.addFirelensLogRouter('log-router', {
image: obtainDefaultFluentBitECRImage(this, container.logDriverConfig),
firelensConfig: {
type: FirelensLogRouterType.FLUENTBIT,
},
logging: new AwsLogDriver({ streamPrefix: 'firelens' }),
memoryReservationMiB: 50,
});
break;
}
}
return this.containers.map(x => x.renderContainerDefinition());
}
private checkFargateWindowsBasedTasksSize(cpu: string, memory: string, runtimePlatform: RuntimePlatform) {
if (Number(cpu) === 1024) {
if (Number(memory) < 1024 || Number(memory) > 8192 || (Number(memory)% 1024 !== 0)) {
throw new Error(`If provided cpu is ${cpu}, then memoryMiB must have a min of 1024 and a max of 8192, in 1024 increments. Provided memoryMiB was ${Number(memory)}.`);
}
} else if (Number(cpu) === 2048) {
if (Number(memory) < 4096 || Number(memory) > 16384 || (Number(memory) % 1024 !== 0)) {
throw new Error(`If provided cpu is ${cpu}, then memoryMiB must have a min of 4096 and max of 16384, in 1024 increments. Provided memoryMiB ${Number(memory)}.`);
}
} else if (Number(cpu) === 4096) {
if (Number(memory) < 8192 || Number(memory) > 30720 || (Number(memory) % 1024 !== 0)) {
throw new Error(`If provided cpu is ${ cpu }, then memoryMiB must have a min of 8192 and a max of 30720, in 1024 increments.Provided memoryMiB was ${ Number(memory) }.`);
}
} else {
throw new Error(`If operatingSystemFamily is ${runtimePlatform.operatingSystemFamily!._operatingSystemFamily}, then cpu must be in 1024 (1 vCPU), 2048 (2 vCPU), or 4096 (4 vCPU). Provided value was: ${cpu}`);
}
};
}
/**
* The port range to open up for dynamic port mapping
*/
const EPHEMERAL_PORT_RANGE = ec2.Port.tcpRange(32768, 65535);
/**
* The networking mode to use for the containers in the task.
*/
export enum NetworkMode {
/**
* The task's containers do not have external connectivity and port mappings can't be specified in the container definition.
*/
NONE = 'none',
/**
* The task utilizes Docker's built-in virtual network which runs inside each container instance.
*/
BRIDGE = 'bridge',
/**
* The task is allocated an elastic network interface.
*/
AWS_VPC = 'awsvpc',
/**
* The task bypasses Docker's built-in virtual network and maps container ports directly to the EC2 instance's network interface directly.
*
* In this mode, you can't run multiple instantiations of the same task on a
* single container instance when port mappings are used.
*/
HOST = 'host',
/**
* The task utilizes NAT network mode required by Windows containers.
*
* This is the only supported network mode for Windows containers. For more information, see
* [Task Definition Parameters](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#network_mode).
*/
NAT = 'nat'
}
/**
* The IPC resource namespace to use for the containers in the task.
*/
export enum IpcMode {
/**
* If none is specified, then IPC resources within the containers of a task are private and not
* shared with other containers in a task or on the container instance
*/
NONE = 'none',
/**
* If host is specified, then all containers within the tasks that specified the host IPC mode on
* the same container instance share the same IPC resources with the host Amazon EC2 instance.
*/
HOST = 'host',
/**
* If task is specified, all containers within the specified task share the same IPC resources.
*/
TASK = 'task',
}
/**
* The process namespace to use for the containers in the task.
*/
export enum PidMode {
/**
* If host is specified, then all containers within the tasks that specified the host PID mode
* on the same container instance share the same process namespace with the host Amazon EC2 instance.
*/
HOST = 'host',
/**
* If task is specified, all containers within the specified task share the same process namespace.
*/
TASK = 'task',
}
/**
* Elastic Inference Accelerator.
* For more information, see [Elastic Inference Basics](https://docs.aws.amazon.com/elastic-inference/latest/developerguide/basics.html)
*/
export interface InferenceAccelerator {
/**
* The Elastic Inference accelerator device name.
* @default - empty
*/
readonly deviceName?: string;
/**
* The Elastic Inference accelerator type to use. The allowed values are: eia2.medium, eia2.large and eia2.xlarge.
* @default - empty
*/
readonly deviceType?: string;
}
/**
* A data volume used in a task definition.
*
* For tasks that use a Docker volume, specify a DockerVolumeConfiguration.
* For tasks that use a bind mount host volume, specify a host and optional sourcePath.
*
* For more information, see [Using Data Volumes in Tasks](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_data_volumes.html).
*/
export interface Volume {
/**
* This property is specified when you are using bind mount host volumes.
*
* Bind mount host volumes are supported when you are using either the EC2 or Fargate launch types.
* The contents of the host parameter determine whether your bind mount host volume persists on the
* host container instance and where it is stored. If the host parameter is empty, then the Docker
* daemon assigns a host path for your data volume. However, the data is not guaranteed to persist
* after the containers associated with it stop running.
*/
readonly host?: Host;
/**
* The name of the volume.
*
* Up to 255 letters (uppercase and lowercase), numbers, and hyphens are allowed.
* This name is referenced in the sourceVolume parameter of container definition mountPoints.
*/
readonly name: string;
/**
* This property is specified when you are using Docker volumes.
*
* Docker volumes are only supported when you are using the EC2 launch type.
* Windows containers only support the use of the local driver.
* To use bind mounts, specify a host instead.
*/
readonly dockerVolumeConfiguration?: DockerVolumeConfiguration;
/**
* This property is specified when you are using Amazon EFS.
*
* When specifying Amazon EFS volumes in tasks using the Fargate launch type,
* Fargate creates a supervisor container that is responsible for managing the Amazon EFS volume.
* The supervisor container uses a small amount of the task's memory.
* The supervisor container is visible when querying the task metadata version 4 endpoint,
* but is not visible in CloudWatch Container Insights.
*
* @default No Elastic FileSystem is setup
*/
readonly efsVolumeConfiguration?: EfsVolumeConfiguration;
}
/**
* The details on a container instance bind mount host volume.
*/
export interface Host {
/**
* Specifies the path on the host container instance that is presented to the container.
* If the sourcePath value does not exist on the host container instance, the Docker daemon creates it.
* If the location does exist, the contents of the source path folder are exported.
*
* This property is not supported for tasks that use the Fargate launch type.
*/
readonly sourcePath?: string;
}
/**
* Properties for an ECS target.
*
* @internal
*/
export interface LoadBalancerTarget {
/**
* The name of the container.
*/
readonly containerName: string;
/**
* The port mapping of the target.
*/
readonly portMapping: PortMapping
}
/**
* Properties for defining an ECS target. The port mapping for it must already have been created through addPortMapping().
*/
export interface LoadBalancerTargetOptions {
/**
* The name of the container.
*/
readonly containerName: string;
/**
* The port number of the container. Only applicable when using application/network load balancers.
*
* @default - Container port of the first added port mapping.
*/
readonly containerPort?: number;
/**
* The protocol used for the port mapping. Only applicable when using application load balancers.
*
* @default Protocol.TCP
*/
readonly protocol?: Protocol;
}
/**
* The configuration for a Docker volume. Docker volumes are only supported when you are using the EC2 launch type.
*/
export interface DockerVolumeConfiguration {
/**
* Specifies whether the Docker volume should be created if it does not already exist.
* If true is specified, the Docker volume will be created for you.
*
* @default false
*/
readonly autoprovision?: boolean;
/**
* The Docker volume driver to use.
*/
readonly driver: string;
/**
* A map of Docker driver-specific options passed through.
*
* @default No options
*/
readonly driverOpts?: {[key: string]: string};
/**
* Custom metadata to add to your Docker volume.
*
* @default No labels
*/
readonly labels?: { [key: string]: string; }
/**
* The scope for the Docker volume that determines its lifecycle.
*/
readonly scope: Scope;
}
/**
* The authorization configuration details for the Amazon EFS file system.
*/
export interface AuthorizationConfig {
/**
* The access point ID to use.
* If an access point is specified, the root directory value will be
* relative to the directory set for the access point.
* If specified, transit encryption must be enabled in the EFSVolumeConfiguration.
*
* @default No id
*/
readonly accessPointId?: string;
/**
* Whether or not to use the Amazon ECS task IAM role defined