All Products
Search
Document Center

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

Last Updated:Sep 02, 2025

This topic describes how to stop or restart an instance using a Cloud Assistant command.

Prerequisites

(Recommended) Use a special exit code to stop or restart an instance

When you execute a command in Cloud Assistant to stop or restart an instance, you must add an exit code to the end of the command. This ensures the accuracy and real-time status of the command execution. Otherwise, the Cloud Assistant Agent cannot report the execution result, and the command status may not be updated correctly.

Important

Make sure that the Cloud Assistant Agent on the target instance is not an earlier version than the following:

  • Linux: 2.2.3.317

  • Windows: 2.2.3.317

If an error occurs when you run a command, you must update the Cloud Assistant Agent to the latest version. For more information, see Upgrade or disable automatic upgrades of Cloud Assistant Agent.

  1. ECS console - Storage Capacity Units
  2. In the top navigation bar, select the region and resource group of the resource that you want to manage. 地域

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

  4. In the Command Information section, configure the parameters. For more information, see Create and run a command.

  5. At the end of the Command Content, set the corresponding exit code.

    • To stop an instance, specify 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 using a command, specify 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 an instance that is not provided by Alibaba Cloud but is managed by Cloud Assistant. For more information, see Alibaba Cloud managed instances.

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

Use OpenAPI to run a Cloud Assistant command to restart instances in batches

Alibaba Cloud provides a rich set of OpenAPI operations for you to manage cloud resources. This section provides an example of how to run Python code in a local Linux environment to call OpenAPI operations. The example shows how to execute a command and restart instances in batches.

  1. Prepare the information required to execute the command.

    1. Obtain the AccessKey pair of the Resource Access Management (RAM) user that you want to use. For more information, see Create an AccessKey pair.

    2. Call the DescribeRegions operation to retrieve the list of regions. For a detailed description of the parameters, see DescribeRegions.

    3. Call the DescribeInstances operation to filter instances that meet specified conditions. For descriptions of the parameters in the DescribeInstances operation, see DescribeInstances.

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

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

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

      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 information in the sample code with the information that you obtained:

      • 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 is executed on three instances to output helloworld, and then the instances are automatically restarted.openapi-exec-reboot

Use OOS to run a Cloud Assistant command to restart instances in batches

CloudOps Orchestration Service (OOS) is an automated O&M service from Alibaba Cloud. You can define O&M actions in templates and then execute the templates to run automated O&M tasks.

  1. Go to the template configuration page.

    1. Log on to the OOS console.

    2. In the navigation pane on the left, click Automated Tasks > Custom Templates.

    3. Click Create Template.

  2. Complete the template configuration.

    1. On the Create Template page, keep the default configurations 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 Finish Creation.

  3. Execute the template.

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

    2. Complete the execution configuration.

      Follow the prompts to complete the configuration. On the Set Parameters page, select multiple instances and keep the default values for the other settings.exec-temp

    3. On the Confirm page, click Create.

      After the execution is created, the template starts to execute automatically. You are redirected to the Basic Information page of the execution. Wait until the Execution Status changes to Succeeded.

  4. View the task execution process and the details of each task node.

    1. In the Execution Steps And Results section, 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. The following figure shows that the scheduled actions are completed successfully.

      image