Skip to content
v2.274.0

ExternalTaskDefinition L2 construct ​

The details of a task definition run on an External cluster.

Example ​

ts
const externalTaskDefinition = new ecs.ExternalTaskDefinition(this, 'TaskDef');

const container = externalTaskDefinition.addContainer("WebContainer", {
  // Use an image from DockerHub
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  // ... other options here ...
});
python
external_task_definition = ecs.ExternalTaskDefinition(self, "TaskDef")

container = external_task_definition.add_container("WebContainer",
    # Use an image from DockerHub
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b=1024
)
java
ExternalTaskDefinition externalTaskDefinition = new ExternalTaskDefinition(this, "TaskDef");

ContainerDefinition container = externalTaskDefinition.addContainer("WebContainer", ContainerDefinitionOptions.builder()
        // Use an image from DockerHub
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryLimitMiB(1024)
        .build());
csharp
// Install: dotnet add package Amazon.CDK.Lib
var externalTaskDefinition = new ExternalTaskDefinition(this, "TaskDef");

var container = externalTaskDefinition.AddContainer("WebContainer", new ContainerDefinitionOptions {
    // Use an image from DockerHub
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryLimitMiB = 1024
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
externalTaskDefinition := ecs.NewExternalTaskDefinition(this, jsii.String("TaskDef"))

container := externalTaskDefinition.AddContainer(jsii.String("WebContainer"), &ContainerDefinitionOptions{
	// Use an image from DockerHub
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryLimitMiB: jsii.Number(1024),
})

Initializer ​

ts
new ExternalTaskDefinition(scope: Construct, id: string, props?: ExternalTaskDefinitionProps)
python
ExternalTaskDefinition(scope: Construct, id: str, props: typing.Optional[ExternalTaskDefinitionProps] = None)
java
new ExternalTaskDefinition(Construct scope, String id, ExternalTaskDefinitionProps props)
csharp
new ExternalTaskDefinition(Construct scope, string id, ExternalTaskDefinitionProps? props = null)
go
NewExternalTaskDefinition(Scope Construct, Id *string, Props ExternalTaskDefinitionProps)

Construct Props ​

enableFaultInjectionoptionalbooleanenable_fault_injectionoptionalboolenableFaultInjectionoptionalBooleanEnableFaultInjectionoptionalboolEnableFaultInjectionoptional*bool#
Enables fault injection and allows for fault injection requests to be accepted from the task's containers.

Default: undefined - ECS default setting is false

Fault injection only works with tasks using the {@link NetworkMode.AWS_VPC} or {@link NetworkMode.HOST} network modes.

executionRoleoptionalIRoleexecution_roleoptionalIRoleexecutionRoleoptionalIRoleExecutionRoleoptionalIRoleExecutionRoleoptionalIRole#
The name of the IAM task execution role that grants the ECS agent permission to call AWS APIs on your behalf.

Default: An execution role will be automatically created if you use ECR images in your task definition.

The role will be used to retrieve container images from ECR and create CloudWatch log groups.

familyoptionalstringfamilyoptionalstrfamilyoptionalStringFamilyoptionalstringFamilyoptional*string#
The name of a family that this task definition is registered to.

Default: Automatically generated name.

A family groups multiple versions of a task definition.

networkModeoptionalNetworkModenetwork_modeoptionalNetworkModenetworkModeoptionalNetworkModeNetworkModeoptionalNetworkModeNetworkModeoptionalNetworkMode= NetworkMode.BRIDGE#
The networking mode to use for the containers in the task.

With ECS Anywhere, supported modes are bridge, host and none.

proxyConfigurationoptionalProxyConfigurationproxy_configurationoptionalProxyConfigurationproxyConfigurationoptionalProxyConfigurationProxyConfigurationoptionalProxyConfigurationProxyConfigurationoptionalProxyConfiguration#
The configuration details for the App Mesh proxy.

Default: No proxy configuration.

taskRoleoptionalIRoletask_roleoptionalIRoletaskRoleoptionalIRoleTaskRoleoptionalIRoleTaskRoleoptionalIRole#
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.

volumesoptionalVolume[]volumesoptionaltyping.List[Volume]volumesoptionalList<Volume>VolumesoptionalVolume[]Volumesoptional*[]Volume#
The list of volume definitions for the task.

Default: No volumes are passed to the Docker daemon on a container instance.

For more information, see Task Definition Parameter Volumes.

Properties ​

compatibilityCompatibilitycompatibilityCompatibilitycompatibilityCompatibilityCompatibilityCompatibilityCompatibilityCompatibilityrequired#
The task launch type compatibility requirement.
defaultContainermay be undefinedContainerDefinitiondefault_containermay be undefinedContainerDefinitiondefaultContainermay be undefinedContainerDefinitionDefaultContainermay be undefinedContainerDefinitionDefaultContainermay be undefinedContainerDefinition#
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.

The environment this resource belongs to.
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.

ephemeralStorageGiBmay be undefinednumberephemeral_storage_gi_bmay be undefinedint | floatephemeralStorageGiBmay be undefinedNumberEphemeralStorageGiBmay be undefineddoubleEphemeralStorageGiBmay be undefined*float64#
The amount (in GiB) of ephemeral storage to be allocated to the task.

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.

executionRolemay be undefinedIRoleexecution_rolemay be undefinedIRoleexecutionRolemay be undefinedIRoleExecutionRolemay be undefinedIRoleExecutionRolemay be undefinedIRole#
Execution role for this task definition.
familystringfamilystrfamilyStringFamilystringFamily*stringrequired#
The name of a family that this task definition is registered to.

A family groups multiple versions of a task definition.

inferenceAcceleratorsInferenceAccelerator[]inference_acceleratorstyping.List[InferenceAccelerator]inferenceAcceleratorsList<InferenceAccelerator>InferenceAcceleratorsInferenceAccelerator[]InferenceAccelerators*[]InferenceAcceleratorrequired#
Public getter method to access list of inference accelerators attached to the instance.
isEc2Compatiblebooleanis_ec2_compatibleboolisEc2CompatibleBooleanIsEc2CompatibleboolIsEc2Compatible*boolrequired#
Return true if the task definition can be run on an EC2 cluster.
isExternalCompatiblebooleanis_external_compatibleboolisExternalCompatibleBooleanIsExternalCompatibleboolIsExternalCompatible*boolrequired#
Return true if the task definition can be run on a ECS anywhere cluster.
isFargateCompatiblebooleanis_fargate_compatibleboolisFargateCompatibleBooleanIsFargateCompatibleboolIsFargateCompatible*boolrequired#
Return true if the task definition can be run on a Fargate cluster.
isManagedInstancesCompatiblebooleanis_managed_instances_compatibleboolisManagedInstancesCompatibleBooleanIsManagedInstancesCompatibleboolIsManagedInstancesCompatible*boolrequired#
Return true if the task definition can be run on Managed Instances.
networkModeNetworkModenetwork_modeNetworkModenetworkModeNetworkModeNetworkModeNetworkModeNetworkModeNetworkModerequired#
The networking mode to use for the containers in the task.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
pidModemay be undefinedPidModepid_modemay be undefinedPidModepidModemay be undefinedPidModePidModemay be undefinedPidModePidModemay be undefinedPidMode#
The process namespace to use for the containers in the task.
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#
Uniquely identifies this class.
referencesSecretJsonFieldmay be undefinedbooleanreferences_secret_json_fieldmay be undefinedboolreferencesSecretJsonFieldmay be undefinedBooleanReferencesSecretJsonFieldmay be undefinedboolReferencesSecretJsonFieldmay be undefined*bool#
Whether this task definition has at least a container that references a specific JSON field of a secret stored in Secrets Manager.
runtimePlatformmay be undefinedRuntimePlatformruntime_platformmay be undefinedRuntimePlatformruntimePlatformmay be undefinedRuntimePlatformRuntimePlatformmay be undefinedRuntimePlatformRuntimePlatformmay be undefinedRuntimePlatform#
The runtime platform (operating system family and CPU architecture) for the task definition, or `undefined` if none was configured.

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.

stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
taskDefinitionArnstringtask_definition_arnstrtaskDefinitionArnStringTaskDefinitionArnstringTaskDefinitionArn*stringrequired#
The full Amazon Resource Name (ARN) of the task definition.
taskDefinitionRefTaskDefinitionReferencetask_definition_refTaskDefinitionReferencetaskDefinitionRefTaskDefinitionReferenceTaskDefinitionRefTaskDefinitionReferenceTaskDefinitionRefTaskDefinitionReferencerequired#
A reference to this task definition.
taskRoleIRoletask_roleIRoletaskRoleIRoleTaskRoleIRoleTaskRoleIRolerequired#
The name of the IAM role that grants containers in the task permission to call AWS APIs on your behalf.

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#
Adds a new container to the task definition.
addExtension(extension: ITaskDefinitionExtension): voiddef add_extension(self, extension: ITaskDefinitionExtension) -> Nonepublic void addExtension(ITaskDefinitionExtension extension)public void AddExtension(ITaskDefinitionExtension extension)func AddExtension(Extension ITaskDefinitionExtension)#
Adds the specified extension to the task definition.

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#
Adds a firelens log router to the task definition.
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)#
Overridden method to throw error as interface accelerators are not supported for external tasks.
addPlacementConstraint(constraint: PlacementConstraint): voiddef add_placement_constraint(self, constraint: PlacementConstraint) -> Nonepublic void addPlacementConstraint(PlacementConstraint constraint)public void AddPlacementConstraint(PlacementConstraint constraint)func AddPlacementConstraint(Constraint PlacementConstraint)#
Adds the specified placement constraint to the task definition.
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)#
Adds a policy statement to the task execution IAM role.
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)#
Adds a policy statement to the task IAM role.
addVolume(volume: Volume): voiddef add_volume(self, volume: Volume) -> Nonepublic void addVolume(Volume volume)public void AddVolume(Volume volume)func AddVolume(Volume Volume)#
Adds a volume to the task definition.
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)#
Override the cross-stack reference strength for this resource.
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)#
Apply the given removal policy to this resource.
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#
Returns the container that match the provided containerName.
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#
Determine the existing port mapping for the provided name.
1 parameter · returns

Parameters

  • namenamenamenameName — : port mapping name.

Returns: PortMapping for the provided name, if it exists.

fromEc2TaskDefinitionArn(scope: Construct, id: string, externalTaskDefinitionArn: string): IExternalTaskDefinition@staticmethod def from_ec2_task_definition_arn(scope: Construct, id: str, external_task_definition_arn: str) -> IExternalTaskDefinitionpublic static IExternalTaskDefinition fromEc2TaskDefinitionArn(Construct scope, String id, String externalTaskDefinitionArn)public static IExternalTaskDefinition FromEc2TaskDefinitionArn(Construct scope, string id, string externalTaskDefinitionArn)func FromEc2TaskDefinitionArn(Scope Construct, Id *string, ExternalTaskDefinitionArn *string) IExternalTaskDefinitionstatic#
Imports a task definition from the specified task definition ARN.
fromExternalTaskDefinitionAttributes(scope: Construct, id: string, attrs: ExternalTaskDefinitionAttributes): IExternalTaskDefinition@staticmethod def from_external_task_definition_attributes(scope: Construct, id: str, attrs: ExternalTaskDefinitionAttributes) -> IExternalTaskDefinitionpublic static IExternalTaskDefinition fromExternalTaskDefinitionAttributes(Construct scope, String id, ExternalTaskDefinitionAttributes attrs)public static IExternalTaskDefinition FromExternalTaskDefinitionAttributes(Construct scope, string id, ExternalTaskDefinitionAttributes attrs)func FromExternalTaskDefinitionAttributes(Scope Construct, Id *string, Attrs ExternalTaskDefinitionAttributes) IExternalTaskDefinitionstatic#
Imports an existing External task definition from its attributes.
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#
Imports a task definition from the specified task definition ARN.

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#
Create a task definition from a task definition reference.
grantRun(grantee: IGrantable): Grantdef grant_run(self, grantee: IGrantable) -> Grantpublic Grant grantRun(IGrantable grantee)public Grant GrantRun(IGrantable grantee)func GrantRun(Grantee IGrantable) Grant#
Grants permissions to run this task definition.

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#
Checks if `x` is a construct.
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#
Returns true if the construct was created by CDK, and false otherwise.
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#
Check whether the given construct is a Resource.
obtainExecutionRole(): IRoledef obtain_execution_role(self, ) -> IRolepublic IRole obtainExecutionRole()public IRole ObtainExecutionRole()func ObtainExecutionRole() IRole#
Creates the task execution IAM role if it doesn't already exist.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

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.