Create and run commands

更新时间:
复制 MD 格式

Manually logging in to each instance to perform repetitive O&M tasks, such as installing software, updating configurations, or collecting logs, is inefficient and error-prone. Cloud Assistant lets you securely and reliably run scripts, such as Shell and PowerShell, across multiple target instances.

Procedure

Console

  1. Go to ECS console - ECS Cloud Assistant.

  2. In the top navigation bar, select the region and resource group of the resource that you want to manage. Region

  3. In the upper-right corner of the ECS Cloud Assistant page, click Create/Run Command.

  4. In the Command Information section, configure the following settings:

    • Command: You can enable Use Parameters.

      The Base64-encoded command content cannot exceed 18 KB when you select Run and Save, or 24 KB when you select Run.
      • Custom parameters: Define custom parameters using the {{parameter}} format and assign values to them manually. This format supports dynamic values and parameter reuse.

      • Built-in parameters: Cloud Assistant provides built-in parameters, such as {{ACS::RegionId}} (region ID) and {{ACS::InstanceId}} (instance ID), which are automatically replaced at runtime and do not require you to assign values.

      #!/bin/bash
      # Example
      # {{name}} is a custom parameter. You must assign a value after you write the command content.
      echo {{name}}
      
      # {{ACS::RegionId}} is a built-in parameter that does not require a value.
      echo {{ACS::RegionId}}
    • Execution Plan:

      • Perform Only Dry Run: Validates the command and its parameters without executing it. This check includes request parameters, the instance execution environment, and the Cloud Assistant Agent status.

      • Timing execution:

        • Run at Fixed Interval: Runs the command at a fixed interval based on a rate expression.

          The interval, which must be between 60 seconds and 7 days, must be longer than the task's configured timeout.
        • Run on Clock-based Schedule: Schedules the command using a cron expression, which is ideal for complex, recurring tasks.

    • Username: Defaults to root (Linux) or System (Windows). To follow the principle of least privilege, run commands as a non-root user.

    • Execution Path: The working directory on the instance where the command runs. The default is /root on Linux and C:\Windows\system32 on Windows. To ensure the script runs from a specific directory, add a cd command at the beginning of your script.

    • Timeout Period: The default is 60 seconds. You can set the timeout to a value from 10 to 86,400 seconds (24 hours).

    • Task Stop Scope:

      • Command Process: Stops the script process when you stop the task.

      • Command Process Tree: Stops the process tree (the script process and all its child processes) when you stop the task.

  5. In the Select Instances or Select Managed Instances area, select the instances on which to run the command.

    You can select up to 100 instances.
  6. Click Run and Save or Run to start the task.

CLI

  1. Prepare the command content

    The RunCommand operation accepts either plaintext or Base64-encoded content for the CommandContent parameter. When using Base64-encoded content, you must also set the ContentEncoding parameter to Base64. Use the following commands to Base64-encode your script:

    Linux and macOS

    # Encode the string "hello world"
    # Use -n to avoid encoding the trailing newline
    echo -n "hello world" | base64
    # Output: aGVsbG8gd29ybGQ=

    Windows (PowerShell)

    # Encode the string "hello world"
    [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("hello world"))
    # Output: aGVsbG8gd29ybGQ=
  2. Run the command

    Use the aliyun ecs RunCommand operation to run a command on one or more instances. For details about its parameters, see RunCommand.

    • Example 1: Run a command on a single instance immediately

      # The Base64-encoded value of "yum -y update" is "eXVtIC15IHVwZGF0ZQ=="
      aliyun ecs RunCommand --RegionId 'cn-hangzhou' \
        --Type 'RunShellScript' \
        --ContentEncoding 'Base64' \
        --CommandContent 'eXVtIC15IHVwZGF0ZQ==' \
        --InstanceId.1 'i-bp1************de01' \
    • Example 2: Run a command on multiple instances

      # Reuse the --InstanceId.N parameter to specify multiple instances
      aliyun ecs RunCommand --RegionId 'cn-hangzhou' \
        --Type 'RunShellScript' \
        --ContentEncoding 'Base64' \
        --CommandContent 'eXVtIC15IHVwZGF0ZQ==' \
        --InstanceId.1 'i-bp1************de01' \
        --InstanceId.2 'i-bp1************de02' \
        --InstanceId.3 'i-bp1************de03'
    • Example 3: Create a cron scheduled task

      # The Frequency parameter uses a cron expression and a time zone
      # Example: Run the command at 12:00 PM every day in the Asia/Shanghai time zone
      aliyun ecs RunCommand --RegionId 'cn-hangzhou' \
        --Type 'RunShellScript' \
        --ContentEncoding 'Base64' \
        --CommandContent 'eXVtIC15IHVwZGF0ZQ==' \
        --RepeatMode 'Period' \
        --Frequency '0 0 12 * * ? Asia/Shanghai' \
        --InstanceId.1 'i-bp1************de01'
  3. Query execution results

    The RunCommand operation returns an InvokeId. Use the aliyun ecs DescribeInvocationResults command with the returned InvokeId to query the detailed execution results. For parameter details, see DescribeInvocationResults.

    # Replace <invoke_id> with your InvokeId
    aliyun ecs DescribeInvocationResults --RegionId 'cn-hangzhou' --InvokeId '<invoke_id>'

    In the response, the Output field is the script's standard output (STDOUT), and the ErrorInfo or ErrorMsg field contains error details.

Quotas and limits

  • Number of instances: A single API call to run a command can target a maximum of 100 instances. You can request a quota increase.

  • Number of saved commands: By default, you can save up to 500 Cloud Assistant commands per region. This quota may increase based on your ECS usage. You can request a quota increase.

    Commands that are run immediately without being saved do not count towards this quota.
  • Feature and client version dependencies: Some advanced features depend on specific versions of the Cloud Assistant Agent. For more information, see Supported features and versions.

Production best practices

  • Ensure idempotence

    When calling the RunCommand API, set the ClientToken parameter to ensure idempotence. This prevents the same command from running more than once due to client-side retries or network issues.

  • Monitoring and alerts

    Monitor Cloud Assistant execution status, especially for tasks in the Failed state. To detect and resolve issues quickly, use EventBridge or CloudMonitor to subscribe to Cloud Assistant events and create alerts for command failures.

FAQ

Q: How do I check the Cloud Assistant Agent version on an ECS instance?

A: You can check the Cloud Assistant Agent version in the console or by logging in to the instance. For specific steps, see Install the Cloud Assistant Agent.

Q: I created a Run at Fixed Interval scheduled task. Does it run immediately, or does it wait for the first interval to pass before the first run?

A: No, the task does not run immediately upon creation. It runs for the first time after the specified interval elapses. Subsequent runs are scheduled based on the fixed interval, regardless of how long each execution takes. For example, a task created at 10:00 AM with a 10-minute interval will first run at 10:10 AM, then 10:20 AM, and so on.

Q: How can I troubleshoot a command execution failure?

A: 1. In the console, navigate to the execution results page and review the Output log for script error messages.

2. Verify that the user specified to run the command has read, write, and execute permissions on the required files and directories.

3. Confirm that the script syntax is correct and that the script runs successfully when executed manually on the instance.

4. Check that the target instance is in the Running state and has proper network connectivity.

5. If you receive a ClientNeedUpgrade error, upgrade the Cloud Assistant Agent.

For more information, see View execution results and fix common errors.