- Navigation GuideYou are on a Command (operation) page with structural examples. Use the navigation breadcrumb if you would like to return to the Client landing page.
RunTaskCommand
Starts a new task using the specified task definition.
On March 21, 2024, a change was made to resolve the task definition revision before authorization. When a task definition revision is not specified, authorization will occur using the latest revision of a task definition.
Amazon Elastic Inference (EI) is no longer available to customers.
You can allow Amazon ECS to place tasks for you, or you can customize how Amazon ECS places tasks using placement constraints and placement strategies. For more information, see Scheduling Tasks in the Amazon Elastic Container Service Developer Guide.
Alternatively, you can use StartTask
to use your own scheduler or place tasks manually on specific container instances.
You can attach Amazon EBS volumes to Amazon ECS tasks by configuring the volume when creating or updating a service. For more infomation, see Amazon EBS volumes in the Amazon Elastic Container Service Developer Guide.
The Amazon ECS API follows an eventual consistency model. This is because of the distributed nature of the system supporting the API. This means that the result of an API command you run that affects your Amazon ECS resources might not be immediately visible to all subsequent commands you run. Keep this in mind when you carry out an API command that immediately follows a previous API command.
To manage eventual consistency, you can do the following:
-
Confirm the state of the resource before you run a command to modify it. Run the DescribeTasks command using an exponential backoff algorithm to ensure that you allow enough time for the previous command to propagate through the system. To do this, run the DescribeTasks command repeatedly, starting with a couple of seconds of wait time and increasing gradually up to five minutes of wait time.
-
Add wait time between subsequent commands, even if the DescribeTasks command returns an accurate response. Apply an exponential backoff algorithm starting with a couple of seconds of wait time, and increase gradually up to about five minutes of wait time.
Example Syntax
Use a bare-bones client and the command you need to make an API call.
import { ECSClient, RunTaskCommand } from "@aws-sdk/client-ecs"; // ES Modules import
// const { ECSClient, RunTaskCommand } = require("@aws-sdk/client-ecs"); // CommonJS import
const client = new ECSClient(config);
const input = { // RunTaskRequest
capacityProviderStrategy: [ // CapacityProviderStrategy
{ // CapacityProviderStrategyItem
capacityProvider: "STRING_VALUE", // required
weight: Number("int"),
base: Number("int"),
},
],
cluster: "STRING_VALUE",
count: Number("int"),
enableECSManagedTags: true || false,
enableExecuteCommand: true || false,
group: "STRING_VALUE",
launchType: "EC2" || "FARGATE" || "EXTERNAL",
networkConfiguration: { // NetworkConfiguration
awsvpcConfiguration: { // AwsVpcConfiguration
subnets: [ // StringList // required
"STRING_VALUE",
],
securityGroups: [
"STRING_VALUE",
],
assignPublicIp: "ENABLED" || "DISABLED",
},
},
overrides: { // TaskOverride
containerOverrides: [ // ContainerOverrides
{ // ContainerOverride
name: "STRING_VALUE",
command: [
"STRING_VALUE",
],
environment: [ // EnvironmentVariables
{ // KeyValuePair
name: "STRING_VALUE",
value: "STRING_VALUE",
},
],
environmentFiles: [ // EnvironmentFiles
{ // EnvironmentFile
value: "STRING_VALUE", // required
type: "s3", // required
},
],
cpu: Number("int"),
memory: Number("int"),
memoryReservation: Number("int"),
resourceRequirements: [ // ResourceRequirements
{ // ResourceRequirement
value: "STRING_VALUE", // required
type: "GPU" || "InferenceAccelerator", // required
},
],
},
],
cpu: "STRING_VALUE",
inferenceAcceleratorOverrides: [ // InferenceAcceleratorOverrides
{ // InferenceAcceleratorOverride
deviceName: "STRING_VALUE",
deviceType: "STRING_VALUE",
},
],
executionRoleArn: "STRING_VALUE",
memory: "STRING_VALUE",
taskRoleArn: "STRING_VALUE",
ephemeralStorage: { // EphemeralStorage
sizeInGiB: Number("int"), // required
},
},
placementConstraints: [ // PlacementConstraints
{ // PlacementConstraint
type: "distinctInstance" || "memberOf",
expression: "STRING_VALUE",
},
],
placementStrategy: [ // PlacementStrategies
{ // PlacementStrategy
type: "random" || "spread" || "binpack",
field: "STRING_VALUE",
},
],
platformVersion: "STRING_VALUE",
propagateTags: "TASK_DEFINITION" || "SERVICE" || "NONE",
referenceId: "STRING_VALUE",
startedBy: "STRING_VALUE",
tags: [ // Tags
{ // Tag
key: "STRING_VALUE",
value: "STRING_VALUE",
},
],
taskDefinition: "STRING_VALUE", // required
clientToken: "STRING_VALUE",
volumeConfigurations: [ // TaskVolumeConfigurations
{ // TaskVolumeConfiguration
name: "STRING_VALUE", // required
managedEBSVolume: { // TaskManagedEBSVolumeConfiguration
encrypted: true || false,
kmsKeyId: "STRING_VALUE",
volumeType: "STRING_VALUE",
sizeInGiB: Number("int"),
snapshotId: "STRING_VALUE",
iops: Number("int"),
throughput: Number("int"),
tagSpecifications: [ // EBSTagSpecifications
{ // EBSTagSpecification
resourceType: "volume", // required
tags: [
{
key: "STRING_VALUE",
value: "STRING_VALUE",
},
],
propagateTags: "TASK_DEFINITION" || "SERVICE" || "NONE",
},
],
roleArn: "STRING_VALUE", // required
terminationPolicy: { // TaskManagedEBSVolumeTerminationPolicy
deleteOnTermination: true || false, // required
},
filesystemType: "ext3" || "ext4" || "xfs" || "ntfs",
},
},
],
};
const command = new RunTaskCommand(input);
const response = await client.send(command);
// { // RunTaskResponse
// tasks: [ // Tasks
// { // Task
// attachments: [ // Attachments
// { // Attachment
// id: "STRING_VALUE",
// type: "STRING_VALUE",
// status: "STRING_VALUE",
// details: [ // AttachmentDetails
// { // KeyValuePair
// name: "STRING_VALUE",
// value: "STRING_VALUE",
// },
// ],
// },
// ],
// attributes: [ // Attributes
// { // Attribute
// name: "STRING_VALUE", // required
// value: "STRING_VALUE",
// targetType: "container-instance",
// targetId: "STRING_VALUE",
// },
// ],
// availabilityZone: "STRING_VALUE",
// capacityProviderName: "STRING_VALUE",
// clusterArn: "STRING_VALUE",
// connectivity: "CONNECTED" || "DISCONNECTED",
// connectivityAt: new Date("TIMESTAMP"),
// containerInstanceArn: "STRING_VALUE",
// containers: [ // Containers
// { // Container
// containerArn: "STRING_VALUE",
// taskArn: "STRING_VALUE",
// name: "STRING_VALUE",
// image: "STRING_VALUE",
// imageDigest: "STRING_VALUE",
// runtimeId: "STRING_VALUE",
// lastStatus: "STRING_VALUE",
// exitCode: Number("int"),
// reason: "STRING_VALUE",
// networkBindings: [ // NetworkBindings
// { // NetworkBinding
// bindIP: "STRING_VALUE",
// containerPort: Number("int"),
// hostPort: Number("int"),
// protocol: "tcp" || "udp",
// containerPortRange: "STRING_VALUE",
// hostPortRange: "STRING_VALUE",
// },
// ],
// networkInterfaces: [ // NetworkInterfaces
// { // NetworkInterface
// attachmentId: "STRING_VALUE",
// privateIpv4Address: "STRING_VALUE",
// ipv6Address: "STRING_VALUE",
// },
// ],
// healthStatus: "HEALTHY" || "UNHEALTHY" || "UNKNOWN",
// managedAgents: [ // ManagedAgents
// { // ManagedAgent
// lastStartedAt: new Date("TIMESTAMP"),
// name: "ExecuteCommandAgent",
// reason: "STRING_VALUE",
// lastStatus: "STRING_VALUE",
// },
// ],
// cpu: "STRING_VALUE",
// memory: "STRING_VALUE",
// memoryReservation: "STRING_VALUE",
// gpuIds: [ // GpuIds
// "STRING_VALUE",
// ],
// },
// ],
// cpu: "STRING_VALUE",
// createdAt: new Date("TIMESTAMP"),
// desiredStatus: "STRING_VALUE",
// enableExecuteCommand: true || false,
// executionStoppedAt: new Date("TIMESTAMP"),
// group: "STRING_VALUE",
// healthStatus: "HEALTHY" || "UNHEALTHY" || "UNKNOWN",
// inferenceAccelerators: [ // InferenceAccelerators
// { // InferenceAccelerator
// deviceName: "STRING_VALUE", // required
// deviceType: "STRING_VALUE", // required
// },
// ],
// lastStatus: "STRING_VALUE",
// launchType: "EC2" || "FARGATE" || "EXTERNAL",
// memory: "STRING_VALUE",
// overrides: { // TaskOverride
// containerOverrides: [ // ContainerOverrides
// { // ContainerOverride
// name: "STRING_VALUE",
// command: [ // StringList
// "STRING_VALUE",
// ],
// environment: [ // EnvironmentVariables
// {
// name: "STRING_VALUE",
// value: "STRING_VALUE",
// },
// ],
// environmentFiles: [ // EnvironmentFiles
// { // EnvironmentFile
// value: "STRING_VALUE", // required
// type: "s3", // required
// },
// ],
// cpu: Number("int"),
// memory: Number("int"),
// memoryReservation: Number("int"),
// resourceRequirements: [ // ResourceRequirements
// { // ResourceRequirement
// value: "STRING_VALUE", // required
// type: "GPU" || "InferenceAccelerator", // required
// },
// ],
// },
// ],
// cpu: "STRING_VALUE",
// inferenceAcceleratorOverrides: [ // InferenceAcceleratorOverrides
// { // InferenceAcceleratorOverride
// deviceName: "STRING_VALUE",
// deviceType: "STRING_VALUE",
// },
// ],
// executionRoleArn: "STRING_VALUE",
// memory: "STRING_VALUE",
// taskRoleArn: "STRING_VALUE",
// ephemeralStorage: { // EphemeralStorage
// sizeInGiB: Number("int"), // required
// },
// },
// platformVersion: "STRING_VALUE",
// platformFamily: "STRING_VALUE",
// pullStartedAt: new Date("TIMESTAMP"),
// pullStoppedAt: new Date("TIMESTAMP"),
// startedAt: new Date("TIMESTAMP"),
// startedBy: "STRING_VALUE",
// stopCode: "TaskFailedToStart" || "EssentialContainerExited" || "UserInitiated" || "ServiceSchedulerInitiated" || "SpotInterruption" || "TerminationNotice",
// stoppedAt: new Date("TIMESTAMP"),
// stoppedReason: "STRING_VALUE",
// stoppingAt: new Date("TIMESTAMP"),
// tags: [ // Tags
// { // Tag
// key: "STRING_VALUE",
// value: "STRING_VALUE",
// },
// ],
// taskArn: "STRING_VALUE",
// taskDefinitionArn: "STRING_VALUE",
// version: Number("long"),
// ephemeralStorage: {
// sizeInGiB: Number("int"), // required
// },
// fargateEphemeralStorage: { // TaskEphemeralStorage
// sizeInGiB: Number("int"),
// kmsKeyId: "STRING_VALUE",
// },
// },
// ],
// failures: [ // Failures
// { // Failure
// arn: "STRING_VALUE",
// reason: "STRING_VALUE",
// detail: "STRING_VALUE",
// },
// ],
// };
Example Usage
RunTaskCommand Input
Parameter | Type | Description |
---|
Parameter | Type | Description |
---|---|---|
taskDefinition Required | string | undefined | The The full ARN value must match the value that you specified as the When you specify a task definition, you must either specify a specific revision, or all revisions in the ARN. To specify a specific revision, include the revision number in the ARN. For example, to specify revision 2, use To specify all revisions, use the wildcard (*) in the ARN. For example, to specify all revisions, use For more information, see Policy Resources for Amazon ECS in the Amazon Elastic Container Service Developer Guide. |
capacityProviderStrategy | CapacityProviderStrategyItem[] | undefined | The capacity provider strategy to use for the task. If a When you use cluster auto scaling, you must specify A capacity provider strategy can contain a maximum of 20 capacity providers. |
clientToken | string | undefined | An identifier that you provide to ensure the idempotency of the request. It must be unique and is case sensitive. Up to 64 characters are allowed. The valid characters are characters in the range of 33-126, inclusive. For more information, see Ensuring idempotency . |
cluster | string | undefined | The short name or full Amazon Resource Name (ARN) of the cluster to run your task on. If you do not specify a cluster, the default cluster is assumed. |
count | number | undefined | The number of instantiations of the specified task to place on your cluster. You can specify up to 10 tasks for each call. |
enableECSManagedTags | boolean | undefined | Specifies whether to use Amazon ECS managed tags for the task. For more information, see Tagging Your Amazon ECS Resources in the Amazon Elastic Container Service Developer Guide. |
enableExecuteCommand | boolean | undefined | Determines whether to use the execute command functionality for the containers in this task. If If |
group | string | undefined | The name of the task group to associate with the task. The default value is the family name of the task definition (for example, |
launchType | LaunchType | undefined | The infrastructure to run your standalone task on. For more information, see Amazon ECS launch types in the Amazon Elastic Container Service Developer Guide. The Fargate Spot infrastructure is available for use but a capacity provider strategy must be used. For more information, see Fargate capacity providers in the Amazon ECS Developer Guide. The The A task can use either a launch type or a capacity provider strategy. If a When you use cluster auto scaling, you must specify |
networkConfiguration | NetworkConfiguration | undefined | The network configuration for the task. This parameter is required for task definitions that use the |
overrides | TaskOverride | undefined | A list of container overrides in JSON format that specify the name of a container in the specified task definition and the overrides it should receive. You can override the default command for a container (that's specified in the task definition or Docker image) with a A total of 8192 characters are allowed for overrides. This limit includes the JSON formatting characters of the override structure. |
placementConstraints | PlacementConstraint[] | undefined | An array of placement constraint objects to use for the task. You can specify up to 10 constraints for each task (including constraints in the task definition and those specified at runtime). |
placementStrategy | PlacementStrategy[] | undefined | The placement strategy objects to use for the task. You can specify a maximum of 5 strategy rules for each task. |
platformVersion | string | undefined | The platform version the task uses. A platform version is only specified for tasks hosted on Fargate. If one isn't specified, the |
propagateTags | PropagateTags | undefined | Specifies whether to propagate the tags from the task definition to the task. If no value is specified, the tags aren't propagated. Tags can only be propagated to the task during task creation. To add tags to a task after task creation, use theTagResource API action. An error will be received if you specify the |
referenceId | string | undefined | This parameter is only used by Amazon ECS. It is not intended for use by customers. |
startedBy | string | undefined | An optional tag specified when a task is started. For example, if you automatically trigger a task to run a batch process job, you could apply a unique identifier for that job to your task with the If a task is started by an Amazon ECS service, then the |
tags | Tag[] | undefined | The metadata that you apply to the task to help you categorize and organize them. Each tag consists of a key and an optional value, both of which you define. The following basic restrictions apply to tags:
|
volumeConfigurations | TaskVolumeConfiguration[] | undefined | The details of the volume that was |
RunTaskCommand Output
Parameter | Type | Description |
---|
Parameter | Type | Description |
---|---|---|
$metadata Required | ResponseMetadata | Metadata pertaining to this request. |
failures | Failure[] | undefined | Any failures associated with the call. For information about how to address failures, see Service event messages and API failure reasons in the Amazon Elastic Container Service Developer Guide. |
tasks | Task[] | undefined | A full description of the tasks that were run. The tasks that were successfully placed on your cluster are described here. |
Throws
Name | Fault | Details |
---|
Name | Fault | Details |
---|---|---|
AccessDeniedException | client | You don't have authorization to perform the requested action. |
BlockedException | client | Your Amazon Web Services account was blocked. For more information, contact Amazon Web ServicesSupport . |
ClientException | client | These errors are usually caused by a client action. This client action might be using an action or resource on behalf of a user that doesn't have permissions to use the action or resource. Or, it might be specifying an identifier that isn't valid. The following list includes additional causes for the error:
|
ClusterNotFoundException | client | The specified cluster wasn't found. You can view your available clusters with ListClusters . Amazon ECS clusters are Region specific. |
ConflictException | client | The To fix this issue:
|
InvalidParameterException | client | The specified parameter isn't valid. Review the available parameters for the API request. For more information about service event errors, see Amazon ECS service event messages . |
PlatformTaskDefinitionIncompatibilityException | client | The specified platform version doesn't satisfy the required capabilities of the task definition. |
PlatformUnknownException | client | The specified platform version doesn't exist. |
ServerException | server | These errors are usually caused by a server issue. |
UnsupportedFeatureException | client | The specified task isn't supported in this Region. |
ECSServiceException | Base exception class for all service exceptions from ECS service. |