All Products
Search
Document Center

Elastic Compute Service:Stop or restart an instance with a Cloud Assistant command

Last Updated:May 15, 2026

Use Cloud Assistant exit codes to stop or restart ECS instances, with options for console, OpenAPI, and OOS batch operations.

Prerequisites

(Recommended) Stop or restart an instance with an exit code

Add an exit code to the end of your Cloud Assistant command to stop or restart an instance. Without the exit code, the Cloud Assistant Agent cannot report the execution result, and the command status may not update correctly.

Important

The Cloud Assistant Agent on the target instance must be version:

  • Linux: 2.2.3.317

  • Windows: 2.2.3.317

If an error occurs, update the Cloud Assistant Agent to the latest version. See Upgrade or disable automatic upgrades of Cloud Assistant Agent.

  1. Go to ECS console - Cloud Assistant.

  2. In the upper-left corner of the page, select a region and resource group.地域

  3. Click Create/Run Command.

  4. In the Command Information section, configure the parameters. See Create and run commands.

  5. At the end of the Command, add the corresponding exit code.

    • To stop an instance, use one of the following exit codes.

      Operating system

      Exit code

      Command example

      Linux

      193

      # This Shell command returns exit code 193, which triggers an action to stop the instance.
      exit 193

      Windows

      3009

      # This PowerShell command returns exit code 3009, which triggers an action to stop the instance.
      exit 3009
    • To restart an instance, use one of the following exit codes.

      Operating system

      Exit code

      Command example

      Linux

      194

      # This Shell command returns exit code 194, which triggers an action to restart the instance.
      exit 194

      Windows

      3010

      # This PowerShell command returns exit code 3010, which triggers an action to restart the instance.
      exit 3010
  6. In the Select Instance or Select Managed Instances section, select the instances on which you want to run the command.

    Note

    A managed instance is not provided by Alibaba Cloud but is managed by Cloud Assistant. See Alibaba Cloud managed instances.

  7. Click Run and Save or Run to immediately run the command.

Batch restart instances with OpenAPI

Run Python code in a local Linux environment to call OpenAPI operations that execute a command and restart instances in batches.

  1. Prepare the required information.

    1. Obtain the AccessKey pair of the RAM user. See Create an access key pair.

    2. Call DescribeRegions to retrieve the list of regions. See DescribeRegions.

    3. Call DescribeInstances to filter instances that meet specified conditions. See DescribeInstances.

  2. Configure the local environment and run the sample code.

    1. Install or upgrade the Alibaba Cloud SDK for Python.

      sudo pip install --upgrade alibabacloud_ecs20140526
    2. Create a .py file and add the following sample code.

      Click to view the sample code

      # coding=utf-8
      # If the Python SDK is not installed, run 'sudo pip install alibabacloud_ecs20140526'.
      # Make sure you use the latest SDK version.
      # Run 'sudo pip install --upgrade alibabacloud_ecs20140526' to upgrade.
      
      import base64
      import logging
      import os
      import sys
      import time
      
      from alibabacloud_ecs20140526.client import Client as Ecs20140526Client
      from alibabacloud_ecs20140526.models import (
          DescribeInvocationResultsRequest,
          DescribeInstancesRequest,
          RunCommandRequest,
          RebootInstancesRequest
      )
      from alibabacloud_tea_openapi.models import Config
      
      # Configure the log output formatter.
      logging.basicConfig(level=logging.INFO,
                          format="%(asctime)s %(name)s [%(levelname)s]: %(message)s",
                          datefmt='%m-%d %H:%M')
      
      logger = logging.getLogger()
      
      # Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set in the runtime environment.
      # If your project code is leaked, your AccessKey pair may be compromised, threatening the security of all resources in your account. The following sample code uses environment variables to get the AccessKey pair. This method is for reference only. For better security, use STS tokens.
      access_key = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
      access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
      region_id = '<yourRegionId>'  # Enter the region ID that you obtained.
      
      ecs_config = Config(
          access_key_id=access_key,
          access_key_secret=access_key_secret,
          endpoint=f'ecs.{region_id}.aliyuncs.com'
      )
      client = Ecs20140526Client(ecs_config)
      
      
      def base64_decode(content, code='utf-8'):
          if sys.version_info.major == 2:
              return base64.b64decode(content)
          else:
              return base64.b64decode(content).decode(code)
      
      
      def get_invoke_result(invoke_id):
          request = DescribeInvocationResultsRequest(
              region_id=region_id,
              invoke_id=invoke_id
          )
          response = client.describe_invocation_results(request)
          response_details = response.body.invocation.invocation_results.invocation_result
          dict_res = {detail.instance_id: {"status": detail.invocation_status,
                                           "output": base64_decode(detail.output)} for detail in
                      response_details}
          return dict_res
      
      
      def get_instances_status(instance_ids):
          request = DescribeInstancesRequest(
              region_id=region_id,
              instance_ids=str(instance_ids)
          )
          response = client.describe_instances(request)
          response_details = response.body.instances.instance
          dict_res = {detail.instance_id: {"status": detail.status} for detail in response_details}
          return dict_res
      
      
      def run_command(cmdtype, cmdcontent, instance_ids, timeout=60):
          """
          cmdtype: The command type. Valid values: RunBatScript, RunPowerShellScript, and RunShellScript.
          cmdcontent: The content of the command.
          instance_ids: A list of instance IDs.
          """
          try:
              request = RunCommandRequest(
                  region_id=region_id,
                  type=cmdtype,
                  command_content=cmdcontent,
                  instance_id=instance_ids,
                  timeout=timeout  # The command execution timeout period in seconds. The default value is 60. Set an appropriate timeout period based on the command to be executed.
              )
              response = client.run_command(request)
              return response.body.invoke_id
          except Exception as e:
              logger.error("run command failed", exc_info=True)
      
      
      def reboot_instances(instance_ids, Force=False):
          """
          instance_ids: A list of instance IDs to restart.
          Force: Specifies whether to forcefully restart the instances. The default is False.
          """
          request = RebootInstancesRequest(
              region_id=region_id,
              instance_id=instance_ids,
              force_reboot=Force
          )
          response = client.reboot_instances(request)
      
      
      def wait_invoke_finished_get_out(invoke_id, wait_count, wait_interval):
          for i in range(wait_count):
              result = get_invoke_result(invoke_id)
              if set([res['status'] for _, res in result.items()]) & set(["Running", "Pending", "Stopping"]):
                  time.sleep(wait_interval)
              else:
                  return result
          return result
      
      
      def wait_instance_reboot_ready(ins_ids, wait_count, wait_interval):
          for i in range(wait_count):
              result = get_instances_status(ins_ids)
              if set([res['status'] for _, res in result.items()]) != set(["Running"]):
                  time.sleep(wait_interval)
              else:
                  return result
          return result
      
      
      def run_task():
          # Set the type of the Cloud Assistant command.
          cmdtype = "RunShellScript"
          # Set the content of the Cloud Assistant command.
          cmdcontent = """
          #!/bin/bash
          echo helloworld
          """
          # Set the timeout period.
          timeout = 60
          # Enter the IDs of the instances on which to run the command and then restart.
          ins_ids = ["i-bp185fcs****", "i-bp14wwh****", "i-bp13jbr****"]
      
          # Execute the command.
          invoke_id = run_command(cmdtype, cmdcontent, ins_ids, timeout)
          logger.info("run command,invoke-id:%s" % invoke_id)
      
          if invoke_id is None:
              logger.error("Failed to run command, stopping further execution")
              return
      
          # Wait for the command to finish. The system queries the status 10 times at an interval of 5 seconds. Configure the number of queries and the interval as needed.
          invoke_result = wait_invoke_finished_get_out(invoke_id, 10, 5)
          for ins_id, res in invoke_result.items():
              logger.info(
                  "instance %s command execute finished,status: %s,output:%s" % (ins_id, res['status'], res['output']))
      
          # Restart the instances.
          logger.warning("reboot instance Now")
          reboot_instances(ins_ids)
      
          time.sleep(5)
          # Wait for the instances to restart and enter the Running state. The system queries the status 30 times at an interval of 10 seconds.
          reboot_result = wait_instance_reboot_ready(ins_ids, 30, 10)
          logger.warning("reboot instance Finished")
          for ins_id, res in reboot_result.items():
              logger.info("instance %s status: %s" % (ins_id, res['status']))
      
      
      if __name__ == '__main__':
          run_task()
      

      Replace the following values in the sample code with your own:

      • AccessKey ID:

        access_key = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']

      • AccessKey secret:

        access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']

      • Region ID:

        region_id = '<yourRegionId>'

      • Instance IDs:

        ins_ids= ["i-bp185fcs****","i-bp14wwh****","i-bp13jbr****"]

    3. Run the .py file.

      The following figure shows the result: a command runs on three instances to output helloworld, then the instances restart automatically.openapi-exec-reboot

Batch restart instances with OOS

CloudOps Orchestration Service (OOS) automates O&M tasks through templates. Define your actions in a template and execute it to run commands and restart instances in batches.

  1. Go to the template configuration page.

    1. Log on to the OOS console.

    2. Choose Automated Tasks > Custom Template.

    3. Click Create Template.

  2. Complete the template configuration.

    1. On the Create Template page, keep the default settings and click Next.

    2. Click the YAML tab and enter the following code.

      Click to view the sample code

      FormatVersion: OOS-2019-06-01
      Description:
        en: Run a Cloud Assistant command on multiple ECS instances in a batch and then restart them.
        name-en: Batch Run Command and Restart ECS Instances
        categories:
          - run_command
      Parameters:
        regionId:
          Type: String
          Description:
            en: The ID of the region.
          Label:
            en: Region
          AssociationProperty: RegionId
          Default: '{{ ACS::RegionId }}'
        targets:
          Type: Json
          Label:
            en: Target Instances   
          AssociationProperty: Targets
          AssociationPropertyMetadata:
            ResourceType: ALIYUN::ECS::Instance
            RegionId: regionId
        commandType:
          Description:
            en: The type of the command.
            
          Label:
            en: Command Type
            
          Type: String
          AllowedValues:
            - RunBatScript
            - RunPowerShellScript
            - RunShellScript
          Default: RunShellScript
        commandContent:
          Description:
            en: The command content to execute on the ECS instance.
            
          Label:
            en: Command Content
            
          Type: String
          MaxLength: 16384
          AssociationProperty: Code
          Default: echo hello
        workingDir:
          Description:
            en: 'The directory where the command runs on the ECS instances. For Linux instances, the default is the home directory of the root user (/root). For Windows instances, the default is the directory where the Cloud Assistant client process is located, such as C:\Windows\System32.'
          Label:
            en: Working Directory
            
          Type: String
          Default: ''
        timeout:
          Description:
            en: The timeout period for command execution on an ECS instance.  
          Label:
            en: Timeout
          Type: Number
          Default: 600
        enableParameter:
          Description:
            en: Specifies whether the command contains secret or custom parameters.
          Label:
            en: Enable Parameters
          Type: Boolean
          Default: false
        username:
          Description:
            en: The username used to run the command on the ECS instance.
          Label:
            en: Username
          Type: String
          Default: ''
        windowsPasswordName:
          Description:
            en: The name of the password for the user who runs the command on a Windows instance.
          Label:
            en: Windows Password Name
          Type: String
          Default: ''
          AssociationProperty: SecretParameterName
        rateControl:
          Description:
            en: The concurrency ratio for task execution.
          Label:
            en: Rate Control
          Type: Json
          AssociationProperty: RateControl
          Default:
            Mode: Concurrency
            MaxErrors: 0
            Concurrency: 10
        OOSAssumeRole:
          Description:
            en: The RAM role that OOS assumes.
          Label:
            en: OOS Assume Role 
          Type: String
          Default: OOSServiceRole
      RamRole: '{{ OOSAssumeRole }}'
      Tasks:
        - Name: getInstance
          Description:
            en: Get the ECS instances.
          Action: ACS::SelectTargets
          Properties:
            ResourceType: ALIYUN::ECS::Instance
            RegionId: '{{ regionId }}'
            Filters:
              - '{{ targets }}'
          Outputs:
            instanceIds:
              Type: List
              ValueSelector: Instances.Instance[].InstanceId
        - Name: runCommand
          Action: ACS::ECS::RunCommand
          Description:
            en: Execute the Cloud Assistant command.
          Properties:
            regionId: '{{ regionId }}'
            commandContent: '{{ commandContent }}'
            instanceId: '{{ ACS::TaskLoopItem }}'
            commandType: '{{ commandType }}'
            workingDir: '{{ workingDir }}'
            timeout: '{{ timeout }}'
            enableParameter: '{{ enableParameter }}'
            username: '{{ username }}'
            windowsPasswordName: '{{ windowsPasswordName }}'
          Loop:
            RateControl: '{{ rateControl }}'
            Items: '{{ getInstance.instanceIds }}'
            Outputs:
              commandOutputs:
                AggregateType: Fn::ListJoin
                AggregateField: commandOutput
          Outputs:
            commandOutput:
              Type: String
              ValueSelector: invocationOutput
        - Name: rebootInstance
          Action: ACS::ECS::RebootInstance
          Description:
            en: Restart the ECS instances.
          Properties:
            regionId: '{{ regionId }}'
            instanceId: '{{ ACS::TaskLoopItem }}'
          Loop:
            RateControl: '{{ rateControl }}'
            Items: '{{ getInstance.instanceIds }}'
      Outputs:
        instanceIds:
          Type: List
          Value: '{{ getInstance.instanceIds }}'
    3. Click Create Template.

    4. In the dialog box that appears, enter the template name runcommand_reboot_instances and click OK.

  3. Execute the template.

    1. Find the template that you just created and click Create an execution in the Actions column.

    2. Complete the execution configuration.

      Select multiple instances on the Parameter Settings page and keep the default values for other settings.exec-temp

    3. On the OK page, click Create.

      The template executes automatically. On the Basic Information page, wait until Execution Status changes to Successful.

  4. View the execution process and task node details.

    1. In Execution Steps And Results, click View Execution Flowchart to view the execution process.

      image

    2. Click the Cloud Assistant command execution step. On the loop task list tab, view the execution details of each task node.

      image