All Products
Search
Document Center

:RunCommand

更新時間:Jan 04, 2024

Runs a shell, PowerShell, or batch command on Elastic Compute Service (ECS) instances.

Usage notes

Unlike the CreateCommand and InvokeCommand operations, RunCommand can be used to create and run a command in a single request.

Take note of the following items:

  • The instances on which you want to run a command must be in the Running state. You can call the DescribeInstances operation to query the status of instances.

  • Cloud Assistant Agent is pre-installed on the instances.

  • Before you run a PowerShell command on a Windows instance, make sure that the PowerShell module is installed on the instance.

  • When you use a CRON expression to specify a schedule, you can specify a time zone based on your business requirements. If you do not specify a time zone, the schedule is determined by the system time of the instance. Make sure that the time or time zone of the instance meets your business requirements. For information about time zones, see Configure the NTP service for ECS instances that run CentOS 6 or Configure the NTP service for Windows instances.

  • You can configure the Timeout parameter to specify the timeout period for execution of the command on ECS instances. If an execution times out, Cloud Assistant Agent forcefully terminates the command process.

    • If the one-time execution of a command times out, the execution state of the command changes to Failed. You can call the InvokeRecordStatus operation to query the command execution state.

    • For a scheduled task, the timeout period takes effect on each execution of the command. When a command execution times out, the subsequent executions of the command are not affected. If a scheduled execution of a command times out, the execution state of the command changes to Failed. You can call the InvokeRecordStatus operation to query the command execution state.

      To ensure that scheduled tasks can run as expected, the version of Cloud Assistant Agent cannot be earlier than the following ones. A scheduled task can run a command at a specified interval, only once at a specified point in time, or at designated times based on a CRON expression with a specified year or time zone. If the ClientNeedUpgrade error code is returned, you must upgrade Cloud Assistant Agent to the latest version. For more information, see Update or disable updates for Cloud Assistant Agent.

      • Linux: 2.2.3.282

      • Windows: 2.1.3.282

  • Command executions may fail due to instance status exceptions, network exceptions, or exceptions on Cloud Assistant Agent. If a command execution fails, no execution information is generated. For more information, see Check execution results and troubleshoot common issues.

  • If you set the EnableParameter parameter to true, the custom parameter feature is enabled. When you configure the CommandContent parameter, you can define custom parameters in the {{parameter}} format. Then, when the command is run, the key-value pairs of the custom parameters are passed in.

  • You can retain up to 500 to 10,000 Cloud Assistant commands in each region based on your ECS usage. You can perform operations that are described in the View and increase resource quotas topic or call the DescribeAccountAttribute operation to query resource quotas.

  • Before you run a command on instances, especially new instances, we recommend that you call the DescribeCloudAssistantStatus operation to query the status of Cloud Assistant Agent on the instances, and then run the command when the value of the CloudAssistantStatus parameter in the response is true for the instances.

Debugging

OpenAPI Explorer automatically calculates the signature value. For your convenience, we recommend that you call this operation in OpenAPI Explorer. OpenAPI Explorer dynamically generates the sample code of the operation for different SDKs.

Request parameters

Parameter

Type

Required

Example

Description

Action

String

Yes

RunCommand

The operation that you want to perform. Set the value to RunCommand.

RegionId

String

Yes

cn-hangzhou

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

ResourceGroupId

String

No

rg-bp67acfmxazb4p****

The ID of the resource group on which you want to run the command. When you configure this parameter, take note of the following items:

  • The instances that are specified by the InstanceId.N parameter must belong to this resource group.

  • After the command is run, you can call the DescribeInvocations or DescribeInvocationResults operation with the ResourceGroupId parameter configured to query the execution results in the specified resource group.

Name

String

No

testName

The name of the command. The name supports all character sets and can be up to 128 characters in length.

Description

String

No

testDescription

The description of the command. The description supports all character sets and can be up to 512 characters in length.

Type

String

Yes

RunShellScript

The language type of the command. Valid values:

  • RunBatScript: batch command, applicable to Windows instances.

  • RunPowerShellScript: PowerShell command, applicable to Windows instances.

  • RunShellScript: shell command, applicable to Linux instances.

CommandContent

String

Yes

ZWNobyAxMjM=

The content of the command. The command content can be plaintext or Base64-encoded. Take note of the following items:

  • If you want to retain the command, make sure that the Base64-encoded command content does not exceed 18 KB in size. If you do not want to retain the command, make sure that the Base64-encoded command content does not exceed 24 KB in size. You can configure the KeepCommand parameter to specify whether to retain the command.

  • If the command content is Base64-encoded, you must set the ContentEncoding parameter to Base64.

  • If you set the EnableParameter parameter to true, the custom parameter feature is enabled and you can configure custom parameters based on the following rules:

    • Define custom parameters in the {{}} format. Within {{}}, the spaces and line feeds before and after the parameter names are ignored.

    • You can define up to 20 custom parameters.

    • A custom parameter name can contain only letters, digits, underscores (_), and hyphens (-). The name is case-insensitive. The ACS:: prefix cannot be used to specify non-built-in environment parameters.

    • Each custom parameter name cannot exceed 64 bytes in length.

  • You can specify built-in environment parameters as custom parameters. Then, when you run a command, the values of the parameters are automatically replaced by Cloud Assistant. You can specify the following built-in environment parameters:

    • {{ACS::RegionId}}: the region ID.

    • {{ACS::AccountId}}: the UID of the Alibaba Cloud account.

    • {{ACS::InstanceId}}: the instance ID. When a command is run on multiple instances, if you want to specify {{ACS::InstanceId}} as a built-in environment parameter, make sure that the version of Cloud Assistant Agent is not earlier than the following ones:

      • Linux: 2.2.3.309

      • Windows: 2.1.3.309

    • {{ACS::InstanceName}}: the instance name. When a command is run on multiple instances, if you want to specify {{ACS::InstanceName}} as a built-in environment parameter, make sure that the version of Cloud Assistant Agent is not earlier than the following ones:

      • Linux: 2.2.3.344

      • Windows: 2.1.3.344

    • {{ACS::InvokeId}}: the command task ID. If you want to specify {{ACS::InvokeId}} as a built-in environment parameter, make sure that the version of Cloud Assistant Agent is not earlier than the following ones:

      • Linux: 2.2.3.309

      • Windows: 2.1.3.309

    • {{ACS::CommandId}}: the command ID. If you want to specify {{ACS::CommandId}} as a built-in environment parameter, make sure that the version of Cloud Assistant Agent is not earlier than the following ones:

      • Linux: 2.2.3.309

      • Windows: 2.1.3.309

WorkingDir

String

No

/home/user

The working directory of the command on the instance. The value can be up to 200 characters in length.

Default value:

  • For Linux instances, the default value is /root, which is the home directory of the administrator (the root user).

  • For Windows instances, the default value is the directory where the Cloud Assistant Agent process resides, such as C:\Windows\System32.

Timeout

Long

No

3600

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

A timeout error occurs if the command cannot be run because the process slows down or because a specific module or Cloud Assistant Agent does not exist. When an execution times out, the command process is forcefully terminated.

Default value: 60.

EnableParameter

Boolean

No

false

Specifies whether to include custom parameters in the command.

Default value: false.

RepeatMode

String

No

Once

The mode in which you want to run the command. Valid values:

  • Once: immediately runs the command.

  • Period: runs the command on a regular basis. If you set this parameter to Period, you must also configure the Frequency parameter.

  • NextRebootOnly: runs the command the next time the instance is started.

  • EveryReboot: runs the command every time the instance is started.

Default value:

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

  • If you configure the Frequency parameter, Period is used as the value of RepeatMode regardless of whether the RepeatMode parameter is set to Period.

Take note of the following items:

  • You can all the StopInvocation operation to stop the pending or scheduled executions of the command.

  • If you set this parameter to Period or EveryReboot, you can call the DescribeInvocationResults operation with IncludeHistory set to true to query the results of historical scheduled executions.

Timed

Boolean

No

true

Note

This parameter is deprecated and does not take effect.

Frequency

String

No

0 */20 * * * ?

The schedule based on which you want to run the command. You can configure a command to run at a fixed interval based on a rate expression, run only once at a specified point in time, or run at designated points in time based on a CRON expression.

  • To run a command at a fixed interval, use a rate expression to specify the interval. You can specify the interval in seconds, minutes, hours, or days. This option is suitable for scenarios in which tasks need to be executed at a fixed interval. Specify the interval in the following format: rate(<Execution interval value><Execution interval unit>). For example, specify rate(5m) to run the command every 5 minutes. When you specify an interval, take note of the following limits:

    • The interval can be anywhere from 60 seconds to 7 days, but must be longer than the timeout period of the scheduled task.

    • The interval is the amount of time that elapses between two consecutive executions. The interval is irrelevant to the amount of time that is required to run the command once. For example, you set the interval to 5 minutes and 2 minutes are required to run the command each time. Each time the command is run, the system waits 3 minutes before it runs the command again.

    • A task is not immediately executed after the task is created. For example, you set the interval to 5 minutes for a task. The task begins to be executed 5 minutes after it is created.

  • To run a command only once at a specific time, specify a point in time and a time zone. Specify the point in time in the at(yyyy-MM-dd HH:mm:ss <Time zone>) format, which indicates at(Year-Month-Day Hour:Minute:Second <Time zone>). If you do not specify a time zone, the default time zone is UTC. You can specify a time zone in the following forms:

    • The time zone name. Examples: Asia/Shanghai and America/Los_Angeles.

    • The time offset from GMT. Examples: GMT+8:00 (UTC+8) and GMT-7:00 (UTC-7). If you use the GMT format, do not add leading zeros to the hour value.

    • The time zone abbreviation. Only UTC is supported.

      For example, to configure a command to run only once at 13:15:30 on June 6, 2022 (China/Shanghai time), set the time to at(2022-06-06 13:15:30 Asia/Shanghai). To configure a command to run only once at 13:15:30 on June 6, 2022 (UTC-7), set the time to at(2022-06-06 13:15:30 GMT-7:00).

  • To run a command at designated times, specify a CRON expression. Specify the time in the following format: <CRON expression> <Time zone>, where the CRON expression is in the format of <Seconds> <Minutes> <Hours> <Day of the month> <Month> <Day of the week> <Year (optional)>. The system calculates the execution times of the command based on the specified CRON expression and time zone and runs the command as scheduled. If you do not specify a time zone, the system time zone of the instance on which you want to run the command is used by default. For more information about CRON expressions, see CRON expressions. You can specify a time zone in the following forms:

    • The time zone name. Examples: Asia/Shanghai and America/Los_Angeles.

    • The time offset from GMT. Examples: GMT+8:00 (UTC+8) and GMT-7:00 (UTC-7). If you use the GMT format, do not add leading zeros to the hour value.

    • The time zone abbreviation. Only UTC is supported.

      For example, to configure a command to run at 10:15:00 every day in 2022 (China/Shanghai time), set the time to 0 15 10 ? * * 2022 Asia/Shanghai. To configure a command to run every half an hour from 10:00:00 to 11:30:00 every day in 2022 (UTC+8), set the time to 0 0/30 10-11 * * ? 2022 GMT+8:00. To configure a command to run every 5 minutes from 14:00:00 to 14:55:00 every day, every October, every two years since 2022 (UTC), set the time to 0 0/5 14 * 10 ? 2022/2 UTC.

      Note

      The minimum interval must be 10 seconds or more and cannot be shorter than the timeout period of scheduled executions.

Parameters

Map

No

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

The key-value pairs of the custom parameters that are passed in when the command that can include custom parameters is run. For example, the command content is echo {{name}}. You can use the Parameters parameter to pass in the {"name":"Jack"} key-value pair. The name key of the custom parameter is automatically replaced by the paired Jack value to generate a new command. As a result, the echo Jack command is actually run.

You can specify up to 10 custom parameters. Take note of the following items:

  • The key cannot be an empty string. It can be up to 64 characters in length.

  • The value can be an empty string.

  • If you want to retain a command, make sure that the command after Base64 encoding, including custom parameters and original command content, does not exceed 18 KB in size. If you do not want to retain the command, make sure that the command after Base64 encoding does not exceed 24 KB in size. You can configure the KeepCommand parameter to specify whether to retain the command.

  • The custom parameter names that are specified by the Parameters parameter must be included in the custom parameter names that you specify when you created the command. You can use empty strings to represent the parameters that are not passed in.

This parameter is empty by default. You can leave this parameter empty to disable the custom parameter feature.

KeepCommand

Boolean

No

false

Specifies whether to retain the command after the command is run. Valid values:

  • true: retains the command. You can call the InvokeCommand operation to rerun the command. The retained command counts against the quota of Cloud Assistant commands.

  • false: does not retain the command. The command is automatically deleted after it is run and does not count against the quota of Cloud Assistant commands.

Default value: false.

ContentEncoding

String

No

Base64

The encoding mode of the command content that is specified by the CommandContent parameter. The valid values are case-insensitive. Valid values:

  • PlainText: The command content is not encoded.

  • Base64: The command content is encoded in Base64.

Default value: PlainText. If an invalid value is specified for this parameter, PlainText is used.

Username

String

No

test

The username to use to run the command on instances. The username cannot exceed 255 characters in length.

  • For Linux instances, the root username is used by default.

  • For Windows instances, the System username is used by default.

You can also specify other usernames that already exist in the instances to run the command. For security purposes, we recommend that you run Cloud Assistant commands as a regular user. For more information, see Run Cloud Assistant commands as a regular user.

WindowsPasswordName

String

No

axtSecretPassword

The name of the password to use to run the command on Windows instances. The name cannot exceed 255 characters in length.

If you do not want to use the default System user to run the command on Windows instances, configure both the WindowsPasswordName and Username parameters. The password is hosted in plaintext in the parameter repository of CloudOps Orchestration Service (OOS) to mitigate the risk of password leaks. Only the name of the password is passed in by using the WindowsPasswordName parameter. For more information, see Manage encryption parameters and Run Cloud Assistant commands as a regular user.

Note

If you use the root user for Linux instances or the System user for Windows instances to run the command, you do not need to configure the WindowsPasswordName parameter.

InstanceId.N

String

Yes

i-bp185dy2o3o6neg****

The ID of instance N. Valid values of N: 1 to 50.

If one of the specified instances does not meet the conditions for running the command, the call fails. To ensure that the call is successful, specify only the IDs of instances that meet the conditions.

Tag.N.Key

String

No

TestKey

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

If a single tag is specified to query resources, up to 1,000 resources that have this tag added can be displayed in the response. If multiple tags are specified to query resources, up to 1,000 resources that have all these tags added can be displayed in the response. To query more than 1,000 resources that have specified tags, call the ListTagResources operation.

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

Tag.N.Value

String

No

TestValue

The value of tag N to add to the command task. 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://.

ContainerId

String

No

ab141ddfbacfe02d9dbc25966ed971536124527097398d419a6746873fea****

The container ID. Only 64-bit hexadecimal strings are supported. Container IDs that are prefixed with docker://, containerd://, or cri-o:// are allowed to specify container runtimes.

Take note of the following items:

  • If this parameter is configured, Cloud Assistant runs scripts in the specified container of the instance.

  • If this parameter is configured, scripts can be run only on Linux instances on which Cloud Assistant Agent is installed. The version of Cloud Assistant Agent must be 2.2.3.344 or later.

  • If this parameter is configured, the configured Username and WorkingDir parameters do not take effect. You can run the command in the default working directory of the container only by using the default user of the container. For more information, see Use Cloud Assistant to run commands in containers.

  • If this parameter is configured, only shell scripts can be run in Linux containers. You cannot add a command in the format similar to #!/usr/bin/python at the beginning of a script to specify a script interpreter. For more information, see Use Cloud Assistant to run commands in containers.

ContainerName

String

No

test-container

The name of the container.

Take note of the following items:

  • If this parameter is configured, Cloud Assistant runs scripts in the specified container of the instance.

  • If this parameter is configured, scripts can be run only on Linux instances on which Cloud Assistant Agent is installed. The version of Cloud Assistant Agent must be 2.2.3.344 or later.

  • If this parameter is configured, the configured Username and WorkingDir parameters do not take effect. You can run the command in the default working directory of the container only by using the default user of the container. For more information, see Use Cloud Assistant to run commands in containers.

  • If this parameter is configured, only shell scripts can be run in Linux containers. You cannot add a command in the format similar to #!/usr/bin/python at the beginning of a script to specify a script interpreter. For more information, see Use Cloud Assistant to run commands in containers.

ClientToken

String

No

123e4567-e89b-12d3-a456-426655440000

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

Response parameters

Parameter

Type

Example

Description

RequestId

String

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

The request ID.

CommandId

String

c-7d2a745b412b4601b2d47f6a768d****

The command ID.

InvokeId

String

t-7d2a745b412b4601b2d47f6a768d****

The command task ID.

Examples

Sample requests

http(s)://ecs.aliyuncs.com/?Action=RunCommand
&CommandContent='echo hello'
&InstanceId.1=i-bp185dy2o3o6neg****
&InstanceId.2=i-bp541dc26ko6dd5****
&Name=Test
&RegionId=cn-hangzhou
&Type=RunShellScript
&Username=test
&<Common request parameters>

Sample success responses

XML format

HTTP/1.1 200 OK
Content-Type:application/xml

<RunCommandResponse>
    <RequestId>E69EF3CC-94CD-42E7-8926-F133B863****</RequestId>
    <CommandId>c-7d2a745b412b4601b2d47f6a768d****</CommandId>
    <InvokeId>t-7d2a745b412b4601b2d47f6a768d****</InvokeId>
</RunCommandResponse>

JSON format

HTTP/1.1 200 OK
Content-Type:application/json

{
  "RequestId" : "E69EF3CC-94CD-42E7-8926-F133B863****",
  "CommandId" : "c-7d2a745b412b4601b2d47f6a768d****",
  "InvokeId" : "t-7d2a745b412b4601b2d47f6a768d****"
}

Error codes

HTTP status code

Error code

Error message

Description

400

RegionId.ApiNotSupported

The api is not supported in this region.

The operation cannot be called in the specified region. Check whether the value of the RegionId parameter is valid.

400

MissingParam.InstanceId

The parameter instanceId is missing or empty.

InstanceId.N is required.

400

NumberExceed.Tags

Ensure the number of tag parameters is not greater than 20.

The maximum number of tags is exceeded.

400

InvalidTagValue.Malformed

The specified Tag.n.Value is not valid.

Invalid Tag.N.Value value.

400

Duplicate.TagKey

The Tag.N.Key contain duplicate key.

The tag key already exists. Tag keys must be unique.

400

InvalidTagKey.Malformed

The specified Tag.n.Key is not valid.

Invalid Tag.N.Key value.

400

MissingParameter.TagKey

You must specify Tag.N.Key.

Tag.N.Key is required.

400

InvalidContainerId.Malformed

The specified parameter ContainerId is not valid.

Invalid ContainerId value.

400

InvalidContainerName.Malformed

The specified parameter ContainerName is not valid.

Invalid ContainerName value.

400

InvalidClientToken.Malformed

The specified parameter clientToken is not valid.

Invalid ClientToken value.

400

CmdParam.EmptyKey

Command parameters can not be empty.

The custom parameters are required in the command.

400

CmdParam.InvalidParamName

A command parameter name is invalid.

Invalid custom parameter name.

400

CmdContent.DecodeError

The CommandContent can not be base64 decoded.

The command content cannot be decoded in Base64.

400

InvalidInstance.NotMatch

The specified instance type does not match the command.

The specified command cannot be run on the specified instance. Check whether the state of the instance meets the conditions for running the Cloud Assistant command.

400

MissingParam.Frequency

The frequency must be specified when you create a timed task.

Frequency is required when you create a scheduled command task.

400

InvalidParam.Frequency

The specified frequency is invalid.

Invalid Frequency value. Check whether the specified Frequency value is valid.

400

ParameterKey.Duplicate

The parameter may not contain duplicate keys.

A parameter that has the same name already exists. Parameter names must be unique.

400

Parameter.NotMatched

The parameters of creation do not match those of invocation.

The custom parameters passed in do not match those specified when the command was created.

400

WindowsPasswordName.Missed

WindowsPasswordName must be specified when you create a Windows task.

WindowsPasswordName is required.

400

Parameter.Disabled

Parameters should not be passed when CreateCommand.EnableParameter is false.

Do not specify custom parameters when you disable the custom parameter feature.

400

InvalidParameter.WorkingDir

The specified parameter WorkingDir is not valid.

Invalid WorkingDir value.

403

CmdContent.ExceedLimit

The length of the command content exceeds the upper limit.

The maximum length of the command content is exceeded.

403

CmdName.ExceedLimit

The length of the command name exceeds the upper limit.

The maximum length of the command name is exceeded.

403

CmdDesc.ExceedLimit

The length of the command description exceeds the upper limit.

The maximum length of the command description is exceeded.

403

CmdCount.ExceedQuota

The total number of commands in the current region exceeds the quota.

The maximum number of Cloud Assistant commands in the current region is exceeded.

403

CmdParamName.ExceedLimit

The length of the command parameter name exceeds the limit.

The maximum length of the custom parameter name in the command is exceeded.

403

InstanceIds.ExceedLimit

The number of instance IDs exceeds the upper limit.

The maximum number of instance IDs is exceeded.

403

Invocation.ExceedQuota

The invocation quota in the current region has been reached for today.

The daily maximum number of command executions in the current region is exceeded.

403

ParameterCount.ExceedLimit

The number of command parameters exceeds the maximum number that can be set.

The maximum number of custom parameters is exceeded.

403

ParameterKey.ExceedLimit

The length of the specified parameter key exceeds the maximum length that can be set.

The key length of a custom parameter exceeds the upper limit.

403

ParameterType.NotSupported

The type of parameter value is not supported.

Invalid custom parameter type.

403

Username.ExceedLimit

The length of the username exceeds the upper limit.

The maximum length of the username is exceeded.

403

WindowsPasswordName.ExceedLimit

The length of the WindowsPasswordName exceeds the upper limit.

The maximum length of the name that is specified by the WindowsPasswordName parameter is exceeded.

403

ParameterStore.InvalidParameters

The parameter is invalid in Parameter Store.

The custom parameter in the {{oos:?}} format is not found.

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 client token is already in use.

403

IdempotentProcessing

The previous idempotent request(s) is still processing.

A previous idempotent request is being processed. Try again later.

403

InvalidStatus.ResourceGroup

You cannot perform an operation on a resource group that is being created or deleted.

This operation cannot be performed on a resource group that is being created or deleted.

404

InvalidCmdType.NotFound

The specified command type does not exist.

The specified command type is not found.

404

InvalidRepeatMode.NotFound

The specified repeat mode does not exist.

Invalid RepeatMode value.

404

InvalidInstance.NotFound

The specified instance does not exist.

The instance is not found.

404

InvalidCmdId.NotFound

The specified command ID does not exist.

Invalid CommandId 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 ResourceGroupId value is not found.

500

InternalError.Dispatch

An error occurred when you dispatched the request.

An error occurred while the request was being sent. Try again later.

For a list of error codes, see Service error codes.