Task - Add

Adds a task to the specified job. The maximum lifetime of a task from addition to completion is 7 days. If a task has not completed within 7 days of being added it will be terminated by the Batch service and left in whatever state it was in at that time.

POST https://batch.core.windows.net/jobs/{jobId}/tasks?api-version=2017-09-01.6.0
POST https://batch.core.windows.net/jobs/{jobId}/tasks?timeout={timeout}&api-version=2017-09-01.6.0

URI Parameters

Name In Required Type Description
jobId
path True
  • string

The ID of the job to which the task is to be added.

timeout
query
  • integer
int32

The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds.

api-version
query True
  • string

Client API Version.

Request Headers

Media Types: "application/json; odata=minimalmetadata"

Name Required Type Description
client-request-id
  • string
uuid

The caller-generated request identity, in the form of a GUID with no decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.

return-client-request-id
  • boolean

Whether the server should return the client-request-id in the response.

ocp-date
  • string
date-time-rfc1123

The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly.

Request Body

Media Types: "application/json; odata=minimalmetadata"

Name Required Type Description
affinityInfo

A locality hint that can be used by the Batch service to select a compute node on which to start the new task.

applicationPackageReferences

A reference to an application package to be deployed to compute nodes.

authenticationTokenSettings

The settings for an authentication token that the task can use to perform Batch service operations.
If this property is set, the Batch service provides the task with an authentication token which can be used to authenticate Batch service operations without requiring an account access key. The token is provided via the AZ_BATCH_AUTHENTICATION_TOKEN environment variable. The operations that the task can carry out using the token depend on the settings. For example, a task can request job permissions in order to add other tasks to the job, or check the status of the job or of other tasks under the job.

commandLine True
  • string

The command line of the task.
For multi-instance tasks, the command line is executed as the primary task, after the primary task and all subtasks have finished executing the coordination command line. The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment variable expansion. If you want to take advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.

constraints

The execution constraints that apply to this task.
If you do not specify constraints, the maxTaskRetryCount is the maxTaskRetryCount specified for the job, and the maxWallClockTime and retentionTime are infinite.

containerSettings

The settings for the container under which the task runs.
If the pool that will run this task has containerConfiguration set, this must be set as well. If the pool that will run this task doesn't have containerConfiguration set, this must not be set. When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories on the node) are mapped into the container, all task environment variables are mapped into the container, and the task command line is executed in the container.

dependsOn

The tasks that this task depends on.
This task will not be scheduled until all tasks that it depends on have completed successfully. If any of those tasks fail and exhaust their retry counts, this task will never be scheduled. If the job does not have usesTaskDependencies set to true, and this element is present, the request fails with error code TaskDependenciesNotSpecifiedOnJob.

displayName
  • string

A display name for the task.
The display name need not be unique and can contain any Unicode characters up to a maximum length of 1024.

environmentSettings

An environment variable to be set on a task process.

exitConditions

Specifies how the Batch service should respond when the task completes.
How the Batch service should respond when the task completes.

id True
  • string

A string that uniquely identifies the task within the job.
The ID can contain any combination of alphanumeric characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and case-insensitive (that is, you may not have two IDs within a job that differ only by case).

multiInstanceSettings

An object that indicates that the task is a multi-instance task, and contains information about how to run the multi-instance task.
Multi-instance tasks are commonly used to support MPI tasks.

outputFiles

A specification for uploading files from an Azure Batch node to another location after the Batch service has finished executing the task process.

resourceFiles

A file to be downloaded from Azure blob storage to a compute node.

userIdentity

The user identity under which the task runs.
If omitted, the task runs as a non-administrative user unique to the task.

Responses

Name Type Description
201 Created

The request to the Batch service was successful.

Headers

  • client-request-id: string
  • request-id: string
  • ETag: string
  • Last-Modified: string
  • DataServiceId: string
Other Status Codes

The error from the Batch service.

Examples

Add a basic task
Add a task with container settings
Add a task with exit conditions

Add a basic task

Sample Request

POST https://batch.core.windows.net/jobs/jobId/tasks?api-version=2017-09-01.6.0
client-request-id: 00000000-0000-0000-0000-000000000000
{
  "id": "task1",
  "commandLine": "cmd /c echo task1"
}

Sample Response

""

Add a task with container settings

Sample Request

POST https://batch.core.windows.net/jobs/jobId/tasks?api-version=2017-09-01.6.0
client-request-id: 00000000-0000-0000-0000-000000000000
{
  "id": "taskId",
  "commandLine": "bash -c 'echo hello'",
  "containerSettings": {
    "imageName": "ubuntu",
    "containerRunOptions": "--rm"
  },
  "userIdentity": {
    "autoUser": {
      "scope": "task",
      "elevationLevel": "nonadmin"
    }
  }
}

Sample Response

""

Add a task with exit conditions

Sample Request

POST https://batch.core.windows.net/jobs/jobId/tasks?api-version=2017-09-01.6.0
client-request-id: 00000000-0000-0000-0000-000000000000
{
  "id": "taskId",
  "commandLine": "cmd /c exit 3",
  "exitConditions": {
    "exitCodeRanges": [
      {
        "start": 2,
        "end": 4,
        "exitOptions": {
          "jobAction": "terminate"
        }
      }
    ]
  },
  "userIdentity": {
    "autoUser": {
      "scope": "task",
      "elevationLevel": "nonadmin"
    }
  }
}

Sample Response

""

Definitions

AffinityInformation

A locality hint that can be used by the Batch service to select a compute node on which to start a task.

ApplicationPackageReference

A reference to an application package to be deployed to compute nodes.

AuthenticationTokenSettings

The settings for an authentication token that the task can use to perform Batch service operations.

AutoUserScope

The scope for the auto user

AutoUserSpecification

Specifies the parameters for the auto user that runs a task on the Batch service.

BatchError

The error encountered while attempting to add the task.

BatchErrorDetail

A collection of key-value pairs containing additional details about the error.

ContainerRegistry

The private registry which contains the container image.

DependencyAction

An action that the Batch service performs on tasks that depend on this task.

ElevationLevel

The elevation level of the auto user.

EnvironmentSetting

An environment variable to be set on a task process.

ErrorMessage

A message describing the error, intended to be suitable for display in a user interface.

ExitCodeMapping

A list of individual task exit codes and how the Batch service should respond to them.

ExitCodeRangeMapping

A list of task exit code ranges and how the Batch service should respond to them.

ExitConditions

Specifies how the Batch service should respond when the task completes.

ExitOptions

How the Batch service should respond if the task exits with this exit code.

JobAction

An action to take on the job containing the task, if the task completes with the given exit condition and the job's onTaskFailed property is 'performExitOptionsJobAction'.

MultiInstanceSettings

Settings which specify how to run a multi-instance task.

OutputFile

A list of files that the Batch service will upload from the compute node after running the command line.

OutputFileBlobContainerDestination

A location in Azure blob storage to which files are uploaded.

OutputFileDestination

The destination for the output file(s).

OutputFileUploadCondition

The conditions under which the task output file or set of files should be uploaded.

OutputFileUploadOptions

Additional options for the upload operation, including under what conditions to perform the upload.

ResourceFile

A file to be downloaded from Azure blob storage to a compute node.

TaskAddParameter

An Azure Batch task to add.

TaskConstraints

Execution constraints to apply to a task.

TaskContainerSettings

The container settings for a task.

TaskDependencies

Specifies any dependencies of a task. Any task that is explicitly specified or within a dependency range must complete before the dependant task will be scheduled.

TaskIdRange

The list of task ID ranges that this task depends on. All tasks in all ranges must complete successfully before the dependent task can be scheduled.

UserIdentity

The definition of the user identity under which the task is run.

AffinityInformation

A locality hint that can be used by the Batch service to select a compute node on which to start a task.

Name Type Description
affinityId
  • string

An opaque string representing the location of a compute node or a task that has run previously.
You can pass the affinityId of a compute node to indicate that this task needs to run on that compute node. Note that this is just a soft affinity. If the target node is busy or unavailable at the time the task is scheduled, then the task will be scheduled elsewhere.

ApplicationPackageReference

A reference to an application package to be deployed to compute nodes.

Name Type Description
applicationId
  • string

The ID of the application to deploy.

version
  • string

The version of the application to deploy. If omitted, the default version is deployed.
If this is omitted on a pool, and no default version is specified for this application, the request fails with the error code InvalidApplicationPackageReferences and HTTP status code 409. If this is omitted on a task, and no default version is specified for this application, the task fails with a pre-processing error.

AuthenticationTokenSettings

The settings for an authentication token that the task can use to perform Batch service operations.

Name Type Description
access
  • string[]

AutoUserScope

The scope for the auto user

Name Type Description
pool
  • string

Specifies that the task runs as the common auto user account which is created on every node in a pool.

task
  • string

Specifies that the service should create a new user for the task.

AutoUserSpecification

Specifies the parameters for the auto user that runs a task on the Batch service.

Name Type Description
elevationLevel

The elevation level of the auto user.
nonAdmin - The auto user is a standard user without elevated access. admin - The auto user is a user with elevated access and operates with full Administrator permissions. The default value is nonAdmin.

scope

The scope for the auto user
The default value is task.

BatchError

The error encountered while attempting to add the task.

Name Type Description
code
  • string

An identifier for the error. Codes are invariant and are intended to be consumed programmatically.

message

A message describing the error, intended to be suitable for display in a user interface.

values

An item of additional information included in an Azure Batch error response.

BatchErrorDetail

A collection of key-value pairs containing additional details about the error.

Name Type Description
key
  • string

An identifier specifying the meaning of the Value property.

value
  • string

The additional information included with the error response.

ContainerRegistry

The private registry which contains the container image.

Name Type Description
password
  • string

The password to log into the registry server.

registryServer
  • string

The registry URL.
If omitted, the default is "docker.io".

username
  • string

The user name to log into the registry server.

DependencyAction

An action that the Batch service performs on tasks that depend on this task.

Name Type Description
block
  • string

Block the task's dependencies.

satisfy
  • string

Satisfy the task's dependencies.

ElevationLevel

The elevation level of the auto user.

Name Type Description
admin
  • string

The user is a user with elevated access and operates with full Administrator permissions.

nonadmin
  • string

The user is a standard user without elevated access.

EnvironmentSetting

An environment variable to be set on a task process.

Name Type Description
name
  • string

The name of the environment variable.

value
  • string

The value of the environment variable.

ErrorMessage

A message describing the error, intended to be suitable for display in a user interface.

Name Type Description
lang
  • string

The language code of the error message

value
  • string

The text of the message.

ExitCodeMapping

A list of individual task exit codes and how the Batch service should respond to them.

Name Type Description
code
  • integer

A process exit code.

exitOptions

How the Batch service should respond if the task exits with this exit code.

ExitCodeRangeMapping

A list of task exit code ranges and how the Batch service should respond to them.

Name Type Description
end
  • integer

The last exit code in the range.

exitOptions

How the Batch service should respond if the task exits with an exit code in the range start to end (inclusive).

start
  • integer

The first exit code in the range.

ExitConditions

Specifies how the Batch service should respond when the task completes.

Name Type Description
default

How the Batch service should respond if the task fails with an exit condition not covered by any of the other properties.
This value is used if the task exits with any nonzero exit code not listed in the exitCodes or exitCodeRanges collection, with a pre-processing error if the preProcessingError property is not present, or with a file upload error if the fileUploadError property is not present. If you want non-default behaviour on exit code 0, you must list it explicitly using the exitCodes or exitCodeRanges collection.

exitCodeRanges

A range of exit codes and how the Batch service should respond to exit codes within that range.

exitCodes

How the Batch service should respond if a task exits with a particular exit code.

fileUploadError

How the Batch service should respond if a file upload error occurs.
If the task exited with an exit code that was specified via exitCodes or exitCodeRanges, and then encountered a file upload error, then the action specified by the exit code takes precedence.

preProcessingError

How the Batch service should respond if the task fails to start due to an error.

ExitOptions

How the Batch service should respond if the task exits with this exit code.

Name Type Description
dependencyAction

An action that the Batch service performs on tasks that depend on this task.
The default is 'satisfy' for exit code 0, and 'block' for all other exit conditions. If the job's usesTaskDependencies property is set to false, then specifying the dependencyAction property returns an error and the add task request fails with an invalid property value error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request).

jobAction

An action to take on the job containing the task, if the task completes with the given exit condition and the job's onTaskFailed property is 'performExitOptionsJobAction'.
The default is none for exit code 0 and terminate for all other exit conditions. If the job's onTaskFailed property is noaction, then specifying this property returns an error and the add task request fails with an invalid property value error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request).

JobAction

An action to take on the job containing the task, if the task completes with the given exit condition and the job's onTaskFailed property is 'performExitOptionsJobAction'.

Name Type Description
disable
  • string

Disable the job. This is equivalent to calling the disable job API, with a disableTasks value of requeue.

none
  • string

Take no action.

terminate
  • string

Terminate the job. The terminateReason in the job's executionInfo is set to "TaskFailed".

MultiInstanceSettings

Settings which specify how to run a multi-instance task.

Name Type Description
commonResourceFiles

A file to be downloaded from Azure blob storage to a compute node.

coordinationCommandLine
  • string

The command line to run on all the compute nodes to enable them to coordinate when the primary runs the main task command.
A typical coordination command line launches a background service and verifies that the service is ready to process inter-node messages.

numberOfInstances
  • integer

The number of compute nodes required by the task.
If omitted, the default is 1.

OutputFile

A list of files that the Batch service will upload from the compute node after running the command line.

Name Type Description
destination

The destination for the output file(s).

filePattern
  • string

A pattern indicating which file(s) to upload.
Both relative and absolute paths are supported. Relative paths are relative to the task working directory. The following wildcards are supported: * matches 0 or more characters (for example pattern abc* would match abc or abcdef), ** matches any directory, ? matches any single character, [abc] matches one character in the brackets, and [a-c] matches one character in the range. Brackets can include a negation to match any character not specified (for example [!abc] matches any character but a, b, or c). If a file name starts with "." it is ignored by default but may be matched by specifying it explicitly (for example .gif will not match .a.gif, but ..gif will). A simple example: **.txt matches any file that does not start in '.' and ends with .txt in the task working directory or any subdirectory. If the filename contains a wildcard character it can be escaped using brackets (for example abc[] would match a file named abc*). Note that both \ and / are treated as directory separators on Windows, but only / is on Linux. Environment variables (%var% on Windows or $var on Linux) are expanded prior to the pattern being applied.

uploadOptions

Additional options for the upload operation, including under what conditions to perform the upload.

OutputFileBlobContainerDestination

A location in Azure blob storage to which files are uploaded.

Name Type Description
containerUrl
  • string

The URL of the container within Azure Blob Storage to which to upload the file(s).
The URL must include a Shared Access Signature (SAS) granting write permissions to the container.

path
  • string

The destination blob or virtual directory within the Azure Storage container.
If filePattern refers to a specific file (i.e. contains no wildcards), then path is the name of the blob to which to upload that file. If filePattern contains one or more wildcards (and therefore may match multiple files), then path is the name of the blob virtual directory (which is prepended to each blob name) to which to upload the file(s). If omitted, file(s) are uploaded to the root of the container with a blob name matching their file name.

OutputFileDestination

The destination for the output file(s).

Name Type Description
container

A location in Azure blob storage to which files are uploaded.

OutputFileUploadCondition

The conditions under which the task output file or set of files should be uploaded.

Name Type Description
taskcompletion
  • string

Upload the file(s) after the task process exits, no matter what the exit code was.

taskfailure
  • string

Upload the file(s) only after the task process exits with a nonzero exit code.

tasksuccess
  • string

Upload the file(s) only after the task process exits with an exit code of 0.

OutputFileUploadOptions

Additional options for the upload operation, including under what conditions to perform the upload.

Name Type Description
uploadCondition

The conditions under which the task output file or set of files should be uploaded.
The default is taskcompletion.

ResourceFile

A file to be downloaded from Azure blob storage to a compute node.

Name Type Description
blobSource
  • string

The URL of the file within Azure Blob Storage.
This URL must be readable using anonymous access; that is, the Batch service does not present any credentials when downloading the blob. There are two ways to get such a URL for a blob in Azure storage: include a Shared Access Signature (SAS) granting read permissions on the blob, or set the ACL for the blob or its container to allow public access.

fileMode
  • string

The file permission mode attribute in octal format.
This property applies only to files being downloaded to Linux compute nodes. It will be ignored if it is specified for a resourceFile which will be downloaded to a Windows node. If this property is not specified for a Linux node, then a default value of 0770 is applied to the file.

filePath
  • string

The location on the compute node to which to download the file, relative to the task's working directory.

TaskAddParameter

An Azure Batch task to add.

Name Type Description
affinityInfo

A locality hint that can be used by the Batch service to select a compute node on which to start the new task.

applicationPackageReferences

A reference to an application package to be deployed to compute nodes.

authenticationTokenSettings

The settings for an authentication token that the task can use to perform Batch service operations.
If this property is set, the Batch service provides the task with an authentication token which can be used to authenticate Batch service operations without requiring an account access key. The token is provided via the AZ_BATCH_AUTHENTICATION_TOKEN environment variable. The operations that the task can carry out using the token depend on the settings. For example, a task can request job permissions in order to add other tasks to the job, or check the status of the job or of other tasks under the job.

commandLine
  • string

The command line of the task.
For multi-instance tasks, the command line is executed as the primary task, after the primary task and all subtasks have finished executing the coordination command line. The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment variable expansion. If you want to take advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.

constraints

The execution constraints that apply to this task.
If you do not specify constraints, the maxTaskRetryCount is the maxTaskRetryCount specified for the job, and the maxWallClockTime and retentionTime are infinite.

containerSettings

The settings for the container under which the task runs.
If the pool that will run this task has containerConfiguration set, this must be set as well. If the pool that will run this task doesn't have containerConfiguration set, this must not be set. When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories on the node) are mapped into the container, all task environment variables are mapped into the container, and the task command line is executed in the container.

dependsOn

The tasks that this task depends on.
This task will not be scheduled until all tasks that it depends on have completed successfully. If any of those tasks fail and exhaust their retry counts, this task will never be scheduled. If the job does not have usesTaskDependencies set to true, and this element is present, the request fails with error code TaskDependenciesNotSpecifiedOnJob.

displayName
  • string

A display name for the task.
The display name need not be unique and can contain any Unicode characters up to a maximum length of 1024.

environmentSettings

An environment variable to be set on a task process.

exitConditions

Specifies how the Batch service should respond when the task completes.
How the Batch service should respond when the task completes.

id
  • string

A string that uniquely identifies the task within the job.
The ID can contain any combination of alphanumeric characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and case-insensitive (that is, you may not have two IDs within a job that differ only by case).

multiInstanceSettings

An object that indicates that the task is a multi-instance task, and contains information about how to run the multi-instance task.
Multi-instance tasks are commonly used to support MPI tasks.

outputFiles

A specification for uploading files from an Azure Batch node to another location after the Batch service has finished executing the task process.

resourceFiles

A file to be downloaded from Azure blob storage to a compute node.

userIdentity

The user identity under which the task runs.
If omitted, the task runs as a non-administrative user unique to the task.

TaskConstraints

Execution constraints to apply to a task.

Name Type Description
maxTaskRetryCount
  • integer

The maximum number of times the task may be retried. The Batch service retries a task if its exit code is nonzero.
Note that this value specifically controls the number of retries. The Batch service will try the task once, and may then retry up to this limit. For example, if the maximum retry count is 3, Batch tries the task up to 4 times (one initial try and 3 retries). If the maximum retry count is 0, the Batch service does not retry the task. If the maximum retry count is -1, the Batch service retries the task without limit.

maxWallClockTime
  • string

The maximum elapsed time that the task may run, measured from the time the task starts. If the task does not complete within the time limit, the Batch service terminates it.
If this is not specified, there is no time limit on how long the task may run.

retentionTime
  • string

The minimum time to retain the task directory on the compute node where it ran, from the time it completes execution. After this time, the Batch service may delete the task directory and all its contents.
The default is infinite, i.e. the task directory will be retained until the compute node is removed or reimaged.

TaskContainerSettings

The container settings for a task.

Name Type Description
containerRunOptions
  • string

Additional options to the container create command.
These additional options are supplied as arguments to the "docker create" command, in addition to those controlled by the Batch Service.

imageName
  • string

The image to use to create the container in which the task will run.
This is the full image reference, as would be specified to "docker pull". If no tag is provided as part of the image name, the tag ":latest" is used as a default.

registry

The private registry which contains the container image.
This setting can be omitted if was already provided at pool creation.

TaskDependencies

Specifies any dependencies of a task. Any task that is explicitly specified or within a dependency range must complete before the dependant task will be scheduled.

Name Type Description
taskIdRanges

A range of task IDs that a task can depend on. All tasks with IDs in the range must complete successfully before the dependent task can be scheduled.
The start and end of the range are inclusive. For example, if a range has start 9 and end 12, then it represents tasks '9', '10', '11' and '12'.

taskIds
  • string[]

TaskIdRange

The list of task ID ranges that this task depends on. All tasks in all ranges must complete successfully before the dependent task can be scheduled.

Name Type Description
end
  • integer

The last task ID in the range.

start
  • integer

The first task ID in the range.

UserIdentity

The definition of the user identity under which the task is run.

Name Type Description
autoUser

The auto user under which the task is run.
The userName and autoUser properties are mutually exclusive; you must specify one but not both.

username
  • string

The name of the user identity under which the task is run.
The userName and autoUser properties are mutually exclusive; you must specify one but not both.