TaskDefinition L2 construct
The base class for all task definitions.
Example
import * as cw from 'aws-cdk-lib/aws-cloudwatch';
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const elbAlarm: cw.Alarm;
const service = new ecs.FargateService(this, 'Service', {
cluster,
taskDefinition,
minHealthyPercent: 100,
deploymentAlarms: {
alarmNames: [elbAlarm.alarmName],
behavior: ecs.AlarmBehavior.ROLLBACK_ON_ALARM,
},
});
// Defining a deployment alarm after the service has been created
const cpuAlarmName = 'MyCpuMetricAlarm';
new cw.Alarm(this, 'CPUAlarm', {
alarmName: cpuAlarmName,
metric: service.metricCpuUtilization(),
evaluationPeriods: 2,
threshold: 80,
});
service.enableDeploymentAlarms([cpuAlarmName], {
behavior: ecs.AlarmBehavior.FAIL_ON_ALARM,
});
import aws_cdk.aws_cloudwatch as cw
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# elb_alarm: cw.Alarm
service = ecs.FargateService(self, "Service",
cluster=cluster,
task_definition=task_definition,
min_healthy_percent=100,
deployment_alarms=ecs.DeploymentAlarmConfig(
alarm_names=[elb_alarm.alarm_name],
behavior=ecs.AlarmBehavior.ROLLBACK_ON_ALARM
)
)
# Defining a deployment alarm after the service has been created
cpu_alarm_name = "MyCpuMetricAlarm"
cw.Alarm(self, "CPUAlarm",
alarm_name=cpu_alarm_name,
metric=service.metric_cpu_utilization(),
evaluation_periods=2,
threshold=80
)
service.enable_deployment_alarms([cpu_alarm_name],
behavior=ecs.AlarmBehavior.FAIL_ON_ALARM
)
import software.amazon.awscdk.services.cloudwatch.*;
Cluster cluster;
TaskDefinition taskDefinition;
Alarm elbAlarm;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.deploymentAlarms(DeploymentAlarmConfig.builder()
.alarmNames(List.of(elbAlarm.getAlarmName()))
.behavior(AlarmBehavior.ROLLBACK_ON_ALARM)
.build())
.build();
// Defining a deployment alarm after the service has been created
String cpuAlarmName = "MyCpuMetricAlarm";
Alarm.Builder.create(this, "CPUAlarm")
.alarmName(cpuAlarmName)
.metric(service.metricCpuUtilization())
.evaluationPeriods(2)
.threshold(80)
.build();
service.enableDeploymentAlarms(List.of(cpuAlarmName), DeploymentAlarmOptions.builder()
.behavior(AlarmBehavior.FAIL_ON_ALARM)
.build());
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AWS.CloudWatch;
Cluster cluster;
TaskDefinition taskDefinition;
Alarm elbAlarm;
var service = new FargateService(this, "Service", new FargateServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
MinHealthyPercent = 100,
DeploymentAlarms = new DeploymentAlarmConfig {
AlarmNames = new [] { elbAlarm.AlarmName },
Behavior = AlarmBehavior.ROLLBACK_ON_ALARM
}
});
// Defining a deployment alarm after the service has been created
var cpuAlarmName = "MyCpuMetricAlarm";
new Alarm(this, "CPUAlarm", new AlarmProps {
AlarmName = cpuAlarmName,
Metric = service.MetricCpuUtilization(),
EvaluationPeriods = 2,
Threshold = 80
});
service.EnableDeploymentAlarms(new [] { cpuAlarmName }, new DeploymentAlarmOptions {
Behavior = AlarmBehavior.FAIL_ON_ALARM
});
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import cw "github.com/aws/aws-cdk-go/awscdk"
var cluster Cluster
var taskDefinition TaskDefinition
var elbAlarm Alarm
service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
Cluster: Cluster,
TaskDefinition: TaskDefinition,
MinHealthyPercent: jsii.Number(100),
DeploymentAlarms: &DeploymentAlarmConfig{
AlarmNames: []*string{
elbAlarm.alarmName,
},
Behavior: ecs.AlarmBehavior_ROLLBACK_ON_ALARM,
},
})
// Defining a deployment alarm after the service has been created
cpuAlarmName := "MyCpuMetricAlarm"
cw.NewAlarm(this, jsii.String("CPUAlarm"), &AlarmProps{
AlarmName: cpuAlarmName,
Metric: service.MetricCpuUtilization(),
EvaluationPeriods: jsii.Number(2),
Threshold: jsii.Number(80),
})
service.EnableDeploymentAlarms([]*string{
cpuAlarmName,
}, &DeploymentAlarmOptions{
Behavior: ecs.AlarmBehavior_FAIL_ON_ALARM,
})
Initializer
new TaskDefinition(scope: Construct, id: string, props: TaskDefinitionProps)
TaskDefinition(scope: Construct, id: str, props: TaskDefinitionProps)
new TaskDefinition(Construct scope, String id, TaskDefinitionProps props)
new TaskDefinition(Construct scope, string id, TaskDefinitionProps props)
NewTaskDefinition(Scope Construct, Id *string, Props TaskDefinitionProps)
Construct Props
compatibilityCompatibilitycompatibilityCompatibilitycompatibilityCompatibilityCompatibilityCompatibilityCompatibilityCompatibilityrequired#notes
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)
8192 (8 vCPU) - Available memory values: Between 16384 (16 GB) and 61440 (60 GB) in increments of 4096 (4 GB)
16384 (16 vCPU) - Available memory values: Between 32768 (32 GB) and 122880 (120 GB) in increments of 8192 (8 GB)
enableFaultInjectionbooleanenable_fault_injectionboolenableFaultInjectionBooleanEnableFaultInjectionboolEnableFaultInjection*bool= undefined - ECS default setting …#Fault injection only works with tasks using the {@link NetworkMode.AWS_VPC} or {@link NetworkMode.HOST} network modes.
default
Default: undefined - ECS default setting is false
ephemeralStorageGiBnumberephemeral_storage_gi_bint | floatephemeralStorageGiBNumberEphemeralStorageGiBdoubleEphemeralStorageGiB*float64= Undefined, in which case, the ta…#Only supported in Fargate platform version 1.4.0 or later for Linux tasks, and platform version 1.0.0 or later for Windows tasks.
default
Default: Undefined, in which case, the task will receive 20GiB ephemeral storage.
executionRoleIRoleexecution_roleIRoleexecutionRoleIRoleExecutionRoleIRoleExecutionRoleIRole= An execution role will be automa…#The role will be used to retrieve container images from ECR and create CloudWatch log groups.
default
Default: An execution role will be automatically created if you use ECR images in your task definition.
A family groups multiple versions of a task definition.
inferenceAcceleratorsInferenceAccelerator[]inference_acceleratorstyping.List[InferenceAccelerator]inferenceAcceleratorsList<InferenceAccelerator>InferenceAcceleratorsInferenceAccelerator[]InferenceAccelerators*[]InferenceAccelerator= No inference accelerators.deprecated#Not supported in Fargate.
ipcModeIpcModeipc_modeIpcModeipcModeIpcModeIpcModeIpcModeIpcModeIpcMode= IpcMode used by the task is not …#Not supported in Fargate and Windows containers.
default
Default: IpcMode used by the task is not specified
memoryMiBstringmemory_mi_bstrmemoryMiBStringMemoryMiBstringMemoryMiB*string= Memory used by task is not speci…#notes · default
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)
Between 16384 (16 GB) and 61440 (60 GB) in increments of 4096 (4 GB) - Available cpu values: 8192 (8 vCPU)
Between 32768 (32 GB) and 122880 (120 GB) in increments of 8192 (8 GB) - Available cpu values: 16384 (16 vCPU)
Default: Memory used by task is not specified.
networkModeNetworkModenetwork_modeNetworkModenetworkModeNetworkModeNetworkModeNetworkModeNetworkModeNetworkMode= NetworkMode.Bridge for EC2 & Ext…#On Fargate, the only supported networking mode is AwsVpc.
default
Default: NetworkMode.Bridge for EC2 & External tasks, AwsVpc for Fargate tasks.
pidModePidModepid_modePidModepidModePidModePidModePidModePidModePidMode= PidMode used by the task is not …#notes · default
Only supported for tasks that are hosted on AWS Fargate if the tasks are using platform version 1.4.0 or later (Linux). Only the TASK option is supported for Linux-based Fargate containers. Not supported in Windows containers. If pidMode is specified for a Fargate task, then runtimePlatform.operatingSystemFamily must also be specified. For more information, see Task Definition Parameters.
Default: PidMode used by the task is not specified
placementConstraintsPlacementConstraint[]placement_constraintstyping.List[PlacementConstraint]placementConstraintsList<PlacementConstraint>PlacementConstraintsPlacementConstraint[]PlacementConstraints*[]PlacementConstraint= No placement constraints.#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.
proxyConfigurationProxyConfigurationproxy_configurationProxyConfigurationproxyConfigurationProxyConfigurationProxyConfigurationProxyConfigurationProxyConfigurationProxyConfiguration= No proxy configuration.#runtimePlatformRuntimePlatformruntime_platformRuntimePlatformruntimePlatformRuntimePlatformRuntimePlatformRuntimePlatformRuntimePlatformRuntimePlatform= Undefined.#A runtimePlatform is supported only for tasks using the Fargate launch type.
taskRoleIRoletask_roleIRoletaskRoleIRoleTaskRoleIRoleTaskRoleIRole= A task role is automatically cre…#default
Default: A task role is automatically created for you.
volumesVolume[]volumestyping.List[Volume]volumesList<Volume>VolumesVolume[]Volumes*[]Volume= No volumes are passed to the Doc…#For more information, see Task Definition Parameter Volumes.
default
Default: No volumes are passed to the Docker daemon on a container instance.
Properties
compatibilityCompatibilitycompatibilityCompatibilitycompatibilityCompatibilityCompatibilityCompatibilityCompatibilityCompatibilityrequired#defaultContainerContainerDefinitiondefault_containerContainerDefinitiondefaultContainerContainerDefinitionDefaultContainerContainerDefinitionDefaultContainerContainerDefinition#Load balancers will send traffic to this container. The first essential container that is added to this task will become the default container.
envResourceEnvironmentenvResourceEnvironmentenvResourceEnvironmentEnvResourceEnvironmentEnvResourceEnvironmentrequired#notes
For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.
For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.
ephemeralStorageGiBnumberephemeral_storage_gi_bint | floatephemeralStorageGiBNumberEphemeralStorageGiBdoubleEphemeralStorageGiB*float64#Only supported in Fargate platform version 1.4.0 or later for Linux tasks, and platform version 1.0.0 or later for Windows tasks.
A family groups multiple versions of a task definition.
inferenceAcceleratorsInferenceAccelerator[]inference_acceleratorstyping.List[InferenceAccelerator]inferenceAcceleratorsList<InferenceAccelerator>InferenceAcceleratorsInferenceAccelerator[]InferenceAccelerators*[]InferenceAcceleratorrequired#isEc2Compatiblebooleanis_ec2_compatibleboolisEc2CompatibleBooleanIsEc2CompatibleboolIsEc2Compatible*boolrequired#isExternalCompatiblebooleanis_external_compatibleboolisExternalCompatibleBooleanIsExternalCompatibleboolIsExternalCompatible*boolrequired#isFargateCompatiblebooleanis_fargate_compatibleboolisFargateCompatibleBooleanIsFargateCompatibleboolIsFargateCompatible*boolrequired#isManagedInstancesCompatiblebooleanis_managed_instances_compatibleboolisManagedInstancesCompatibleBooleanIsManagedInstancesCompatibleboolIsManagedInstancesCompatible*boolrequired#networkModeNetworkModenetwork_modeNetworkModenetworkModeNetworkModeNetworkModeNetworkModeNetworkModeNetworkModerequired#notes
Only supported for tasks that are hosted on AWS Fargate if the tasks are using platform version 1.4.0 or later (Linux). Not supported in Windows containers. If pidMode is specified for a Fargate task, then runtimePlatform.operatingSystemFamily must also be specified. For more information, see Task Definition Parameters.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#referencesSecretJsonFieldbooleanreferences_secret_json_fieldboolreferencesSecretJsonFieldBooleanReferencesSecretJsonFieldboolReferencesSecretJsonField*bool#runtimePlatformRuntimePlatformruntime_platformRuntimePlatformruntimePlatformRuntimePlatformRuntimePlatformRuntimePlatformRuntimePlatformRuntimePlatform#Intentionally public: runtimePlatform is already public API as an input prop and on the underlying L1 CfnTaskDefinition, so reading it back from the L2 is deliberate read-parity.
taskDefinitionArnstringtask_definition_arnstrtaskDefinitionArnStringTaskDefinitionArnstringTaskDefinitionArn*stringrequired#taskDefinitionRefTaskDefinitionReferencetask_definition_refTaskDefinitionReferencetaskDefinitionRefTaskDefinitionReferenceTaskDefinitionRefTaskDefinitionReferenceTaskDefinitionRefTaskDefinitionReferencerequired#Methods
addContainer(id: string, props: ContainerDefinitionOptions): ContainerDefinitiondef add_container(self, id: str, props: ContainerDefinitionOptions) -> ContainerDefinitionpublic ContainerDefinition addContainer(String id, ContainerDefinitionOptions props)public ContainerDefinition AddContainer(string id, ContainerDefinitionOptions props)func AddContainer(Id *string, Props ContainerDefinitionOptions) ContainerDefinition#addExtension(extension: ITaskDefinitionExtension): voiddef add_extension(self, extension: ITaskDefinitionExtension) -> Nonepublic void addExtension(ITaskDefinitionExtension extension)public void AddExtension(ITaskDefinitionExtension extension)func AddExtension(Extension ITaskDefinitionExtension)#Extension can be used to apply a packaged modification to a task definition.
addFirelensLogRouter(id: string, props: FirelensLogRouterDefinitionOptions): FirelensLogRouterdef add_firelens_log_router(self, id: str, props: FirelensLogRouterDefinitionOptions) -> FirelensLogRouterpublic FirelensLogRouter addFirelensLogRouter(String id, FirelensLogRouterDefinitionOptions props)public FirelensLogRouter AddFirelensLogRouter(string id, FirelensLogRouterDefinitionOptions props)func AddFirelensLogRouter(Id *string, Props FirelensLogRouterDefinitionOptions) FirelensLogRouter#addInferenceAccelerator(inferenceAccelerator: InferenceAccelerator): voiddef add_inference_accelerator(self, inference_accelerator: InferenceAccelerator) -> Nonepublic void addInferenceAccelerator(InferenceAccelerator inferenceAccelerator)public void AddInferenceAccelerator(InferenceAccelerator inferenceAccelerator)func AddInferenceAccelerator(InferenceAccelerator InferenceAccelerator)deprecated#addPlacementConstraint(constraint: PlacementConstraint): voiddef add_placement_constraint(self, constraint: PlacementConstraint) -> Nonepublic void addPlacementConstraint(PlacementConstraint constraint)public void AddPlacementConstraint(PlacementConstraint constraint)func AddPlacementConstraint(Constraint PlacementConstraint)#addToExecutionRolePolicy(statement: PolicyStatement): voiddef add_to_execution_role_policy(self, statement: PolicyStatement) -> Nonepublic void addToExecutionRolePolicy(PolicyStatement statement)public void AddToExecutionRolePolicy(PolicyStatement statement)func AddToExecutionRolePolicy(Statement PolicyStatement)#addToTaskRolePolicy(statement: PolicyStatement): voiddef add_to_task_role_policy(self, statement: PolicyStatement) -> Nonepublic void addToTaskRolePolicy(PolicyStatement statement)public void AddToTaskRolePolicy(PolicyStatement statement)func AddToTaskRolePolicy(Statement PolicyStatement)#addVolume(volume: Volume): voiddef add_volume(self, volume: Volume) -> Nonepublic void addVolume(Volume volume)public void AddVolume(Volume volume)func AddVolume(Volume Volume)#applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#notes · 1 parameter
When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.
Parameters
strengthstrengthstrengthstrengthStrength— - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#notes
The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.
The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).
findContainer(containerName: string): ContainerDefinitiondef find_container(self, container_name: str) -> ContainerDefinitionpublic ContainerDefinition findContainer(String containerName)public ContainerDefinition FindContainer(string containerName)func FindContainer(ContainerName *string) ContainerDefinition#findPortMappingByName(name: string): PortMappingdef find_port_mapping_by_name(self, name: str) -> PortMappingpublic PortMapping findPortMappingByName(String name)public PortMapping FindPortMappingByName(string name)func FindPortMappingByName(Name *string) PortMapping#1 parameter · returns
Parameters
namenamenamenameName— : port mapping name.
Returns: PortMapping for the provided name, if it exists.
fromTaskDefinitionArn(scope: Construct, id: string, taskDefinitionArn: string): ITaskDefinition@staticmethod def from_task_definition_arn(scope: Construct, id: str, task_definition_arn: str) -> ITaskDefinitionpublic static ITaskDefinition fromTaskDefinitionArn(Construct scope, String id, String taskDefinitionArn)public static ITaskDefinition FromTaskDefinitionArn(Construct scope, string id, string taskDefinitionArn)func FromTaskDefinitionArn(Scope Construct, Id *string, TaskDefinitionArn *string) ITaskDefinitionstatic#The task will have a compatibility of EC2+Fargate.
fromTaskDefinitionAttributes(scope: Construct, id: string, attrs: TaskDefinitionAttributes): ITaskDefinition@staticmethod def from_task_definition_attributes(scope: Construct, id: str, attrs: TaskDefinitionAttributes) -> ITaskDefinitionpublic static ITaskDefinition fromTaskDefinitionAttributes(Construct scope, String id, TaskDefinitionAttributes attrs)public static ITaskDefinition FromTaskDefinitionAttributes(Construct scope, string id, TaskDefinitionAttributes attrs)func FromTaskDefinitionAttributes(Scope Construct, Id *string, Attrs TaskDefinitionAttributes) ITaskDefinitionstatic#grantRun(grantee: IGrantable): Grantdef grant_run(self, grantee: IGrantable) -> Grantpublic Grant grantRun(IGrantable grantee)public Grant GrantRun(IGrantable grantee)func GrantRun(Grantee IGrantable) Grant#This will grant the following permissions:
- ecs:RunTask
- iam:PassRole
[disable-awslint:no-grants]
1 parameter
Parameters
granteegranteegranteegranteeGrantee— Principal to grant consume rights to.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#notes · 1 parameter · returns
Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.
Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.
Parameters
xxxxX— Any object.
Returns: true if x is an object created from a class which extends Construct.
isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#obtainExecutionRole(): IRoledef obtain_execution_role(self, ) -> IRolepublic IRole obtainExecutionRole()public IRole ObtainExecutionRole()func ObtainExecutionRole() IRole#toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.