Tüm Ürünler
Search
Belge Merkezi

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

Son Güncelleme:Sep 30, 2026

ECS örneklerini durdurmak veya yeniden başlatmak için Cloud Assistant çıkış kodlarını kullanın. Konsol, OpenAPI ve OOS toplu işlemleri için seçenekler mevcuttur.

Önkoşullar

(Önerilen) Çıkış kodu ile örneği durdurma veya yeniden başlatma

Bir örneği durdurmak veya yeniden başlatmak için Cloud Assistant komutunuzun sonuna bir çıkış kodu ekleyin. Çıkış kodu olmadan Cloud Assistant Agent yürütme sonucunu bildiremez ve komut durumu doğru şekilde güncellenmeyebilir.

Önemli

Hedef örnekteki Cloud Assistant Agent sürümü aşağıdaki gibi olmalıdır:

  • Linux: 2.2.3.317

  • Windows: 2.2.3.317

Bir hata oluşursa Cloud Assistant Agent'ı en son sürüme güncelleyin. Bkz. Cloud Assistant Agent'ın yükseltilmesi veya otomatik yükseltmelerin devre dışı bırakılması.

  1. ECS konsolu - Cloud Assistant sayfasına gidin.

  2. Sayfanın sol üst köşesinde bir bölge ve kaynak grubu seçin.

  3. Create/Run Command öğesini tıklayın.

  4. Command Information bölümünde parametreleri yapılandırın. Bkz. Komut oluşturma ve çalıştırma.

  5. Command alanının sonuna ilgili çıkış kodunu ekleyin.

    • Bir örneği durdurmak için aşağıdaki çıkış kodlarından birini kullanın.

      İşletim sistemi

      Çıkış kodu

      Komut örneği

      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
    • Bir örneği yeniden başlatmak için aşağıdaki çıkış kodlarından birini kullanın.

      İşletim sistemi

      Çıkış kodu

      Komut örneği

      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. Select Instance veya Select Managed Instances bölümünde komutu çalıştırmak istediğiniz örnekleri seçin.

    Not

    Yönetilen bir örnek Alibaba Cloud tarafından sağlanmaz ancak Cloud Assistant tarafından yönetilir. Bkz. Alibaba Cloud yönetilen örnekleri.

  7. Komutu hemen çalıştırmak için Run and Save veya Run öğesini tıklayın.

OpenAPI ile örnekleri toplu olarak yeniden başlatma

Toplu olarak komut yürüten ve örnekleri yeniden başlatan OpenAPI işlemlerini çağırmak için yerel bir Linux ortamında Python kodu çalıştırın.

  1. Gerekli bilgileri hazırlayın.

    1. RAM kullanıcısının AccessKey çiftini edinin. Bkz. Erişim anahtarı çifti oluşturma.

    2. Bölgelerin listesini almak için DescribeRegions API'sini çağırın. Bkz. DescribeRegions.

    3. Belirli koşulları karşılayan örnekleri filtrelemek için DescribeInstances API'sini çağırın. Bkz. DescribeInstances.

  2. Yerel ortamı yapılandırın ve örnek kodu çalıştırın.

    1. Python için Alibaba Cloud SDK'yı yükleyin veya yükseltin.

      sudo pip install --upgrade alibabacloud_ecs20140526
    2. Bir .py dosyası oluşturun ve aşağıdaki örnek kodu ekleyin.

      Örnek kodu görüntülemek için tıklayın

      # 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()
      

      Örnek kodda aşağıdaki değerleri kendi bilgilerinizle değiştirin:

      • AccessKey ID: access_key = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']

      • AccessKey secret: access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']

      • Bölge Kimliği: region_id = '<yourRegionId>'

      • Örnek Kimlikleri: ins_ids= ["i-bp185fcs****","i-bp14wwh****","i-bp13jbr****"]

    3. .py dosyasını çalıştırın.

      Aşağıdaki çıktı sonucu gösterir. helloworld komutu 3 örnekte çalıştırılır ve örnekler otomatik olarak yeniden başlatılır:

      [root@iZxxx ~]# vim runcommand_reboot_instances.py
      [root@iZxxx ~]# ls
      runcommand_reboot_instances.py
      [root@iZxxx ~]# python runcommand_reboot_instances.py
      /usr/lib/python2.7/site-packages/aliyunsdkcore/auth/algorithm/sha_hmac256.py:20: CryptographyDeprecationWarning: Python 2 is now deprecated in cryptography, and will be removed in the next release.
        from cryptography.hazmat.backends import default_backend
      09-18 14:33 root [INFO]: run command,invoke-id:t-hz0xxxxx
      09-18 14:34 root [INFO]: instance i-bp185fcs**** command execute finished,status: Finished,output:helloworld
      
      09-18 14:34 root [INFO]: instance i-bp14wwh**** command execute finished,status: Finished,output:helloworld
      
      09-18 14:34 root [INFO]: instance i-bp13jbr**** command execute finished,status: Finished,output:helloworld
      
      09-18 14:34 root [WARNING]: reboot instance Now
      09-18 14:39 root [WARNING]: reboot instance Finished
      09-18 14:39 root [INFO]: instance i-bp185fcs**** status: Running
      09-18 14:39 root [INFO]: instance i-bp14wwh**** status: Running
      09-18 14:39 root [INFO]: instance i-bp13jbr**** status: Running

OOS ile örnekleri toplu olarak yeniden başlatma

CloudOps Orchestration Service (OOS), şablonlar aracılığıyla bakım görevlerini otomatikleştirir. Eylemlerinizi bir şablonda tanımlayın ve ardından komutları çalıştırmak ve örnekleri toplu olarak yeniden başlatmak için bu şablonu yürütün.

  1. Şablon yapılandırma sayfasına gidin.

    1. OOS konsoluna giriş yapın.

    2. Automated Tasks > Custom Template seçeneğini belirleyin.

    3. Create Template öğesini tıklayın.

  2. Şablon yapılandırmasını tamamlayın.

    1. Create Template sayfasında varsayılan ayarları koruyun ve Next öğesini tıklayın.

    2. YAML sekmesini tıklayın ve aşağıdaki kodu girin.

      Örnek kodu görüntülemek için tıklayın

      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. Create Template öğesini tıklayın.

    4. Açılan iletişim kutusunda şablon adı olarak runcommand_reboot_instances girin ve OK öğesini tıklayın.

  3. Şablonu yürütün.

    1. Az önce oluşturduğunuz şablonu bulun ve Actions sütununda Create an execution öğesini tıklayın.

    2. Yürütme yapılandırmasını tamamlayın.

      Yapılandırmayı tamamlamak için istemleri izleyin. Parameter Settings sayfasında birden fazla örnek seçin ve diğer ayarları varsayılan olarak bırakın. Örnek aşağıdaki parametre ayarlarını kullanır:

      • Bölge: China (Hangzhou) seçin

      • Hedef Örnekler: Select Instances Manually seçeneğini belirleyin, ardından komutu çalıştırmak istediğiniz ECS örneklerini eklemek için Select Instances öğesini tıklayın

      • Komut Türü: RunShellScript seçin

      • Komut İçeriği: echo hello girin

    3. OK sayfasında Create öğesini tıklayın.

      Şablon otomatik olarak yürütülür. Basic Information sayfasında Execution Status durumu Successful olarak değişene kadar bekleyin.

  4. Yürütme sürecini ve görev düğümü ayrıntılarını görüntüleyin.

    1. Execution Steps And Results bölümünde yürütme sürecini görüntülemek için View Execution Flowchart öğesini tıklayın. Yürütme akış şeması, görevin sırasıyla Get ECS Instances, Run Cloud Assistant Command ve Restart Instances aşamalarından geçtiğini ve tümünün başarıyla yürütüldüğünü gösterir.

    2. Cloud Assistant komut yürütme adımını tıklayın. Döngü görev listesi sekmesinde her görev düğümünün yürütme ayrıntılarını görüntüleyin. Planlanan tüm işlemler başarıyla tamamlanmıştır.