All Products
Search
Document Center

Elastic Compute Service:InvokeCommand

Last Updated:Sep 20, 2026

Triggers a Cloud Assistant command on one or more ECS instances by specifying parameters such as CommandId, InstanceId, and ResourceGroupId.

Operation description

Operation description

  • The following limits apply to the target ECS instances. If you select multiple ECS instances and one of them does not meet the execution conditions, you must call the operation again.

    • Target instance must be in the Running state. You can call DescribeInstances to query target instance status.

    • Cloud Assistant Agent must be installed on target instance in advance.

    • To run a PowerShell command, target instance must have the PowerShell module configured.

  • One-time execution: The command is executed only once.

  • Scheduled execution:

    • The command is executed at the frequency specified by the Frequency parameter. The result of the previous execution does not affect the next execution.

    • If you specify a time zone when you run a scheduled task based on a Cron expression, the scheduled execution time is based on the specified time zone. If you do not specify a time zone, the scheduled execution time is based on the system time zone of the ECS instance. Make sure that the time or time zone of the ECS instance is consistent with your expected time. For more information about time zones, see Manage time synchronization services.

    The Cloud Assistant Agent version must be at least the following versions to support the new features of scheduled tasks (execution at fixed intervals, one-time execution at a specified time, and specifying a year or time zone for Cron expression-based scheduled execution). If the ClientNeedUpgrade error code is returned, see Upgrade or disable upgrades for Cloud Assistant Agent to update the agent to the latest version.

    • Linux: 2.2.3.282

    • Windows: 2.1.3.282

  • A command may fail to be executed because of abnormal instance status, network exceptions, or Cloud Assistant Agent exceptions. No execution information is generated when a command fails to be executed. For more information, see Common errors and solutions for execution failures.

  • If you enabled the custom parameter feature when you created the command, you must pass in custom parameters (Parameters) when you execute the command.

  • Call DescribeCloudAssistantStatus to query the Cloud Assistant status of target instance first. Execute the command only when CloudAssistantStatus is true, especially for newly purchased instances.

Try it now

Try this API in OpenAPI Explorer, no manual signing needed. Successful calls auto-generate SDK code matching your parameters. Download it with built-in credential security for local usage.

Test

RAM authorization

The table below describes the authorization required to call this API. You can define it in a Resource Access Management (RAM) policy. The table's columns are detailed below:

  • Action: The actions can be used in the Action element of RAM permission policy statements to grant permissions to perform the operation.

  • API: The API that you can call to perform the action.

  • Access level: The predefined level of access granted for each API. Valid values: create, list, get, update, and delete.

  • Resource type: The type of the resource that supports authorization to perform the action. It indicates if the action supports resource-level permission. The specified resource must be compatible with the action. Otherwise, the policy will be ineffective.

    • For APIs with resource-level permissions, required resource types are marked with an asterisk (*). Specify the corresponding Alibaba Cloud Resource Name (ARN) in the Resource element of the policy.

    • For APIs without resource-level permissions, it is shown as All Resources. Use an asterisk (*) in the Resource element of the policy.

  • Condition key: The condition keys defined by the service. The key allows for granular control, applying to either actions alone or actions associated with specific resources. In addition to service-specific condition keys, Alibaba Cloud provides a set of common condition keys applicable across all RAM-supported services.

  • Dependent action: The dependent actions required to run the action. To complete the action, the RAM user or the RAM role must have the permissions to perform all dependent actions.

Action

Access level

Resource type

Condition key

Dependent action

ecs:InvokeCommand

update

*Command

acs:ecs:{#regionId}:{#accountId}:command/{#commandId}

*Instance

acs:ecs:{#regionId}:{#accountId}:instance/{#instanceId}

  • ecs:CommandRunAs
None

Request parameters

Parameter

Type

Required

Description

Example

RegionId

string

Yes

The region ID. You can call DescribeRegions to query the most recent region list.

cn-hangzhou

ResourceGroupId

string

No

The ID of the resource group for the command execution. When you specify this parameter:

  • The ECS instance specified by InstanceId must belong to this resource group if the instance is not in the default resource group.

  • You can filter command execution results by specifying this parameter (by calling DescribeInvocations or DescribeInvocationResults).

rg-bp67acfmxazb4p****

CommandId

string

Yes

The command ID. You can call DescribeCommands to query all available command IDs.

Note

You can run public commands by specifying the command name. For more information, see View and run Cloud Assistant public commands.

c-e996287206324975b5fbe1d****

RepeatMode

string

No

Specifies how the command is executed. Valid values:

  • Once: immediately executes the command.

  • Period: executes the command on a schedule. If you set this parameter to Period, you must also specify the Frequency parameter.

  • NextRebootOnly: automatically executes the command the next time the instance starts.

  • EveryReboot: automatically executes the command every time the instance starts.

  • DryRun: performs a dry run of the request without actually executing the command. The dry run checks request parameters, the instance execution environment, and the Cloud Assistant Agent status.

Default value:

  • If you do not specify the Frequency parameter, the default value is Once.

  • If you specify the Frequency parameter, the command is executed as Period regardless of whether you set this parameter.

Precautions:

  • You can call StopInvocation to stop a pending or scheduled command execution.

  • If you set this parameter to Period or EveryReboot, you can call DescribeInvocationResults and specify IncludeHistory=true to view the execution history of the scheduled command.

Once

Timed

boolean

No

Note

This parameter is deprecated and has no effect if specified.

true

Frequency

string

No

The schedule on which the command is executed. Three types of scheduled execution are supported: fixed interval (based on a Rate expression), one-time execution at a specified time, and clock-based scheduling (based on a Cron expression).

  • Fixed interval execution: Based on a Rate expression, the command is executed at a set interval. The interval can be specified in seconds (s), minutes (m), hours (h), or days (d). This is suitable for scenarios that require execution at fixed intervals. Format: rate(<interval value><interval unit>). For example, to execute every 5 minutes, use rate(5m). Fixed interval execution has the following limits:

    • The interval must not exceed 7 days or be less than 60 seconds, and must be greater than the timeout period of the scheduled task.

    • The execution interval is based on a fixed frequency and is independent of the actual execution time of the task. For example, if the command is set to execute every 5 minutes and the task takes 2 minutes to complete, the next execution starts 3 minutes after the task completes.

    • The command is not executed immediately when the task is created. For example, if the command is set to execute every 5 minutes, the first execution starts 5 minutes after the task is created.

  • One-time execution at a specified time: The command is executed once at the specified time zone and time. Format: at(yyyy-MM-dd HH:mm:ss <time zone>). If no time zone is specified, UTC is used by default. The time zone supports the following three formats:

    • Full time zone name: For example, Asia/Shanghai (China/Shanghai time) or America/Los_Angeles (US/Los Angeles time).

    • Time zone offset from Greenwich Mean Time: For example, GMT+8:00 (UTC+8) or GMT-7:00 (UTC-7). When using the GMT format, leading zeros are not supported for the hour value.

    • Time zone abbreviation: Only UTC (Coordinated Universal Time) is supported.

    For example, to execute once at 13:15:30 on June 6, 2022 in China/Shanghai time, use: at(2022-06-06 13:15:30 Asia/Shanghai). To execute once at 13:15:30 on June 6, 2022 in UTC-7, use: at(2022-06-06 13:15:30 GMT-7:00).

  • Clock-based scheduling (based on a Cron expression): Based on a Cron expression, the command is executed on a set schedule. Format: <seconds> <minutes> <hours> <day of month> <month> <day of week> <year (optional)> <time zone>. The scheduled execution time is calculated based on the Cron expression in the specified time zone. If no time zone is specified, the system time zone of the instance is used by default. For more information about Cron expressions, see Cron expressions. The time zone supports the following three formats:

    • Full time zone name: For example, Asia/Shanghai (China/Shanghai time) or America/Los_Angeles (US/Los Angeles time).

    • Time zone offset from Greenwich Mean Time: For example, GMT+8:00 (UTC+8) or GMT-7:00 (UTC-7). When using the GMT format, leading zeros are not supported for the hour value.

    • Time zone abbreviation: Only UTC (Coordinated Universal Time) is supported. For example, to execute once at 10:15 every day in 2022 in China/Shanghai time, use 0 15 10 ? * * 2022 Asia/Shanghai. To execute every 30 minutes from 10:00 to 11:30 every day in 2022 in UTC+8, use 0 0/30 10-11 * * ? 2022 GMT+8:00. To execute every 5 minutes from 14:00 to 14:55 every day in October every two years starting from 2022 in UTC, use 0 0/5 14 * 10 ? 2022/2 UTC.

    Note

    The minimum interval must be greater than or equal to the timeout period of the scheduled task and no less than 10 seconds.

0 */20 * * * ?

Parameters

object

No

The key-value pairs of custom parameters to pass in when the custom parameter feature is enabled. The number of custom parameters ranges from 0 to 10.

  • Map keys cannot be empty strings and can contain up to 64 characters.

  • Map values can be empty strings.

  • After Base64 encoding, the total length of the custom parameters and the original command content cannot exceed 24 KB.

  • The set of custom parameter names must be a subset of the parameter set defined when the command was created. For parameters that are not passed in, you can use empty strings as substitutes.

You can unset this parameter to disable custom parameters.

{"name":"Jack", "accessKey":"LTAI************"}

Username

string

No

The username used to execute the command on the ECS instance. The value can be up to 255 characters in length.

  • For Linux instances, the command is executed as the root user by default.

  • For Windows instances, the command is executed as the System user by default.

You can also specify another existing user on the instance to execute the command. Executing Cloud Assistant commands as a regular user is more secure. For more information, see Configure a regular user to run Cloud Assistant commands.

test

WindowsPasswordName

string

No

The name of the password used by the user to execute the command on a Windows instance. The value can be up to 255 characters in length.

If you want to execute a command as a non-default user (System) on a Windows instance, you must specify both Username and this parameter. To reduce the risk of password leaks, store the plaintext password in the parameter repository of operations management, and pass in only the password name here. For more information, see Encryption parameters and Configure a regular user to run Cloud Assistant commands.

Note

This parameter is not required when you execute a command as the root user on a Linux instance or the System user on a Windows instance.

axtSecretPassword

InstanceId

array

No

The list of instances on which to execute the command. You can specify up to 100 instance IDs. Valid values of N: 1 to 100.

You can also apply for a quota increase in Quota Center (quota name: Maximum number of instances supported for command execution).

i-bp185dy2o3o6n****

string

No

The instance ID of the instance on which to execute the command.

i-bp185dy2o3o6n****

ContainerId

string

No

The container ID. Only 64-bit hexadecimal strings are supported. You can use the docker://, containerd://, or cri-o:// prefix to specify the container runtime.

Precautions:

  • If you specify this parameter, Cloud Assistant executes the script in the specified container of the instance.

  • If you specify this parameter, the command can run only on Linux instances with Cloud Assistant Agent version 2.2.3.344 or later.

  • If you specify this parameter, the Username parameter specified in this operation and the WorkingDir parameter specified in CreateCommand do not take effect. The command is executed only by the default user in the default working directory of the container. For more information, see Use Cloud Assistant to run commands in containers.

  • If you specify this parameter, only Shell scripts can be executed in Linux containers. You cannot use a format such as #!/usr/bin/python at the beginning of the script to specify an interpreter. For more information, see Use Cloud Assistant to run commands in containers.

ab141ddfbacfe02d9dbc25966ed971536124527097398d419a6746873fea****

ContainerName

string

No

The container name.

Precautions:

  • If you specify this parameter, Cloud Assistant executes the script in the specified container of the instance.

  • If you specify this parameter, the command can run only on Linux instances with Cloud Assistant Agent version 2.2.3.344 or later.

  • If you specify this parameter, the Username parameter specified in this operation and the WorkingDir parameter specified in CreateCommand do not take effect. The command is executed only by the default user in the default working directory of the container. For more information, see Use Cloud Assistant to run commands in containers.

  • If you specify this parameter, only Shell scripts can be executed in Linux containers. You cannot use a format such as #!/usr/bin/python at the beginning of the script to specify an interpreter. For more information, see Use Cloud Assistant to run commands in containers.

test-container

Timeout

integer

No

The timeout period for the command execution. Unit: seconds.

  • The value must be at least 10 seconds.

  • If the command cannot run because of process issues, missing modules, or missing Cloud Assistant Agent, a timeout occurs. When a timeout occurs, the command process is forcefully terminated.

  • If you do not set this value, the timeout period specified when the command was created is used.

  • This value applies only to the current command execution and does not change the timeout period of the command itself.

60

Tag

array<object>

No

The tags.

object

No

The tags.

Key

string

No

The tag key for the command execution. Valid values of N: 1 to 20. The tag key cannot be an empty string.

If you use a single tag to filter resources, the number of resources with this tag cannot exceed 1,000. If you use multiple tags to filter resources, the number of resources with all specified tags attached cannot exceed 1,000. If the number of resources exceeds 1,000, execute the ListTagResources operation to query resources.

The tag key can be up to 64 characters in length and cannot start with aliyun or acs:. It cannot contain http:// or https://.

TestKey

Value

string

No

The tag value for the command execution. Valid values of N: 1 to 20. The tag value can be an empty string.

The tag value can be up to 128 characters in length and cannot contain http:// or https://.

TestValue

ClientToken

string

No

The client token that is used to ensure the idempotence of the request. You can use the client to generate the token, but make sure that the token is unique among different requests. The ClientToken value can contain only ASCII characters and cannot exceed 64 characters in length. For more information, see How to ensure idempotence.

123e4567-e89b-12d3-a456-42665544****

ResourceTag

array<object>

No

The tags used to filter instances. You can use tags to run commands in batches on instances with the same tag without specifying InstanceId.

object

No

The tag used to filter instances. You can use tags to run commands in batches on instances with the same tag without specifying InstanceId.

Key

string

No

The tag key used to filter instances.

Precautions:

  • This parameter conflicts with the InstanceId parameter. You cannot specify both parameters at the same time.

  • Valid values of N: 1 to 10. The tag key cannot be an empty string.

  • The number of instances with the specified tag cannot exceed the limit of InstanceId.N. If the number of instances exceeds the limit, control the number of instances by adding batch tags, such as batch: b1.

  • The tag key can be up to 64 characters in length and cannot start with aliyun or acs:. It cannot contain http:// or https://.

TestKey

Value

string

No

The tag value used to filter instances.

Precautions:

  • Valid values of N: 1 to 10.

  • The tag value can be an empty string.

  • The tag value can be up to 128 characters in length and cannot contain http:// or https://.

TestValue

TerminationMode

string

No

The mode in which the task is stopped (manually stopped or interrupted due to timeout). Valid values:

  • Process: stops the current script process.

  • ProcessTree: stops the current process tree (the script process and all child processes it created).

ProcessTree

Launcher

string

No

The bootstrap program for script execution. The value cannot exceed 1 KB in length.

python3 -u {{ACS::ScriptFileName|Ext(".py")}}

WorkingDir

string

No

The directory in which the command is executed on the ECS instance. The value can be up to 200 characters in length.

  • If you do not set this value, the working directory specified when the command was created is used.

  • This value applies only to the current command execution and does not change the working directory of the command itself.

/home/user

OssOutputDelivery

string

No

The OSS delivery configuration for the command execution output.

  • Format: oss://${BucketName}/${Prefix}, where ${BucketName} is the name of the destination OSS bucket and ${Prefix} is the directory prefix for delivery.

oss://testBucket/testPrefix

Response elements

Element

Type

Description

Example

object

InvokeId

string

The command execution ID.

t-7d2a745b412b4601b2d47f6a768d****

RequestId

string

The request ID.

473469C7-AA6F-4DC5-B3DB-A3DC0DE3****

Examples

Success response

JSON format

{
  "InvokeId": "t-7d2a745b412b4601b2d47f6a768d****",
  "RequestId": "473469C7-AA6F-4DC5-B3DB-A3DC0DE3****"
}

Error codes

HTTP status code

Error code

Error message

Description

400 ResourceBusy.SlrCreation The ServiceLinkedRole is still being created or has not taken effect yet. Please try again later.
400 RegionId.ApiNotSupported The api is not supported in this region. The API operation cannot be called in the specified region. Check whether the specified RegionId parameter is valid.
400 InvalidParameter.WorkingDir The specified parameter WorkingDir is not valid. The specified WorkingDir parameter is invalid.
400 MissingParam.InstanceId The parameter instanceId is missing or empty. The instance ID is empty.
400 InvalidContainerId.Malformed The specified parameter ContainerId is not valid. The specified container ID is invalid.
400 InvalidContainerName.Malformed The specified parameter ContainerName is not valid. The specified container name is invalid.
400 InvalidClientToken.Malformed The specified parameter clientToken is not valid. The specified idempotent parameter is invalid.
400 InvalidInstance.NotMatch The specified instance type does not match the command.
400 MissingParam.Frequency The frequency must be specified when you create a timed task.
400 InvalidParam.Frequency The specified frequency is invalid.
400 Parameter.MissingValue The parameter value of this command is required.
400 Parameter.Disabled Parameters cannot be passed in when the command customization function is disabled.
400 InvalidParameter.Parameters The specified parameter Parameters is not valid. The specified Parameters parameter is invalid.
400 NumberExceed.ResourceTags The maximum number of ResourceTags is exceeded.
400 MissingParameter.ResourceTagKey You must specify ResourceTag.N.Key.
400 InvalidResourceTagKey.Malformed The specified ResourceTag key is not valid.
400 InvalidResourceTagValue.Malformed The specified ResourceTag value is not valid.
400 Duplicate.ResourceTagKey The ResourceTag contains duplicate keys.
400 InvalidResourceTag.InstanceNotFound InstanceIds are not found by the specified ResourceTag.
400 InvalidResourceTag.ConflictWithInstanceIds The specified param ResourceTag conflicts with InstanceId.
400 InvalidOssOutputDelivery.BucketInOtherRegion The OSS bucket specified in the parameter OssOutputDelivery is in another region. The OSS bucket specified in the parameter OssOutputDelivery is in another region.
400 InvalidParameter.OssOutputDelivery The specified parameter OssOutputDelivery is not valid. The specified parameter OssOutputDelivery is not valid.
400 InvalidOssOutputDelivery.KeyPrefixMalformed The prefix of the OSS key specified in the parameter OssOutputDelivery is not valid. The prefix of the OSS key specified in the parameter OssOutputDelivery is not valid.
500 InternalError.Dispatch An error occurred when you dispatched the request. An error occurred while the request is being sent. Try again later.
403 InvalidParameterCharacter The specified parameter %s contains illegal characters.
403 InvalidOssOutputDelivery.BucketAccessDenied The error message returned by the OSS API is: %s
403 InstanceIds.ExceedLimit The number of instance IDs exceeds the upper limit. The number of specified instance IDs exceeds the upper limit.
403 Invocation.ExceedQuota The invocation quota in the current region has been reached for today. The maximum daily number of commands that can be run in the specified region has been reached.
403 ParameterCount.ExceedLimit The maximum number of parameters is exceeded. The number of specified custom parameters exceeds the upper limit.
403 ParameterKey.ExceedLimit The maximum length of a parameter name is exceeded. The key length of a custom parameter exceeds the upper limit.
403 CmdContent.ExceedLimit The maximum length of a command is exceeded. The length of the command content exceeds the upper limit. Shorten your command.
403 ParameterKey.Duplicate Parameter names cannot be duplicated. A parameter that has the same name already exists. Parameter names must be unique.
403 Parameter.NotMatched The passed-in parameters do not match the parameters defined when you created the command. The custom parameters passed in do not match those specified when the command was created.
403 ParameterType.NotSupported The type of parameter value is not supported.
403 Username.ExceedLimit The length of the username exceeds the upper limit. The length of the username exceeds the upper limit.
403 WindowsPasswordName.ExceedLimit The length of the WindowsPasswordName exceeds the upper limit. The length of the specified WindowsPasswordName parameter exceeds the upper limit.
403 WindowsPasswordName.Missed WindowsPasswordName must be specified when you create a Windows task. The value of the request parameter CommandType (WindowsPasswordName) is not provided.
403 ParameterStore.NotSupported Parameter Store is not supported in this region.
403 TemporaryAccessKey.Error The temporary accessKey is invalid.
403 ParameterStore.InvalidParameters The parameter is invalid in Parameter Store. The parameter specified by {{oos:?}} in the command content was not found.
403 ParameterStore.NoPermission You have no access to Parameter Store.
403 Operation.Forbidden The operation is not permitted. The operation is not supported.
403 IdempotentParameterMismatch The specified parameter has changed while using an already used clientToken. The request parameters do not match the request with the same ClientToken.
403 IdempotentProcessing The previous idempotent request(s) is still processing. A previous idempotent request is being processed. Try again later.
403 InvalidLauncher.LengthLimitExceeded The length of the parameter Launcher exceeds the limit of 1 KB characters. The length of the argument Launcher exceeds the limit of 1 KB characters.
403 InvalidParameterCharset.Parameters The parameter Parameters contains illegal charset. The command parameter contains an illegal character set.
403 CreateServiceLinkedRole.NoPermission You do not have permission to create ServiceLinkedRole for output delivery. You do not have permission to create ServiceLinkedRole for output delivery.
403 InvalidTimeout.ExceedLimit The specified parameter Timeout exceeds the upper limit.
404 InvalidRepeatMode.NotFound The specified repeat mode does not exist. The specified command execution mode does not exist.
404 InvalidRegionId.NotFound The RegionId provided does not exist in our records. Region information error
404 InvalidInstance.NotFound The specified instance does not exist. The specified instance does not exist.
404 InvalidCmdId.NotFound The specified command ID does not exist. The specified CommandId parameter is invalid. Check the parameter value. You can call the DescribeCommands operation to query all available command IDs.
404 InvalidResourceGroup.NotFound The ResourceGroup provided does not exist in our records. The specified resource group does not exist.
404 InvalidTerminationMode.NotFound The specified parameter TerminationMode does not exist. The specified parameter TerminationMode does not exist.
404 InvalidOssOutputDelivery.BucketNotFound The OSS bucket specified in the parameter OssOutputDelivery does not exist. The OSS bucket specified in the parameter OssOutputDelivery does not exist.

See Error Codes for a complete list.

Release notes

See Release Notes for a complete list.