すべてのプロダクト
Search
ドキュメントセンター

Elastic Compute Service:Cloud Assistant コマンドを使用したインスタンスの停止または再起動

最終更新日:May 16, 2026

Cloud Assistant の終了コードを使用して Elastic Compute Service (ECS) インスタンスを停止または再起動します。この操作は、コンソール、OpenAPI、および CloudOps Orchestration Service (OOS) を使用したバッチ処理で実行できます。

前提条件

(推奨) 終了コードを使用したインスタンスの停止または再起動

Cloud Assistant コマンドの末尾に終了コードを追加して、インスタンスを停止または再起動します。終了コードがない場合、Cloud Assistant Agent は実行結果を報告できず、コマンドのステータスが正しく更新されない可能性があります。

重要

対象インスタンスの Cloud Assistant Agent は、以下のバージョンである必要があります:

  • Linux: 2.2.3.317

  • Windows: 2.2.3.317

エラーが発生した場合は、Cloud Assistant Agent を最新バージョンに更新してください。詳細については、「Cloud Assistant Agent のアップグレードまたは自動アップグレードの無効化」をご参照ください。

  1. ECS コンソール - ECS クラウドアシスタントに移動します。

  2. 上部メニューで、対象リソースのリージョンとリソースグループを選択します。 地域

  3. コマンドの作成/実行 をクリックします。

  4. コマンド情報 セクションで、パラメーターを設定します。 詳細については、「コマンドの作成と実行」をご参照ください。

  5. コマンドの最後に、対応する終了コードを追加します。

    • インスタンスを停止するには、次のいずれかの終了コードを使用します。

      オペレーティングシステム

      終了コード

      コマンド例

      Linux

      193

      # この Shell コマンドは終了コード 193 を返し、インスタンスを停止するアクションをトリガーします。
      exit 193

      Windows

      3009

      # この PowerShell コマンドは終了コード 3009 を返し、インスタンスを停止するアクションをトリガーします。
      exit 3009
    • インスタンスを再起動するには、次のいずれかの終了コードを使用します。

      オペレーティングシステム

      終了コード

      コマンド例

      Linux

      194

      # この Shell コマンドは終了コード 194 を返し、インスタンスを再起動するアクションをトリガーします。
      exit 194

      Windows

      3010

      # この PowerShell コマンドは終了コード 3010 を返し、インスタンスを再起動するアクションをトリガーします。
      exit 3010
  6. インスタンスの選択」または「マネージドインスタンスの選択」セクションで、コマンドを実行するインスタンスを選択します。

    説明

    マネージドインスタンスは Alibaba Cloud が提供するものではなく、Cloud Assistant が管理するインスタンスです。詳細については、「Alibaba Cloud マネージドインスタンス」をご参照ください。

  7. 実行して保存 または 実行 をクリックして、コマンドをすぐに実行します。

OpenAPI を使用したインスタンスの一括再起動

ローカルの Linux 環境で Python コードを実行して OpenAPI を呼び出し、コマンドを実行してインスタンスを一括で再起動します。

  1. 必要な情報を準備します。

    1. RAM ユーザーのアクセスキーペアを取得します。詳細については、「アクセスキーペアの作成」をご参照ください。

    2. DescribeRegions API を呼び出してリージョンのリストを取得します。詳細については、「DescribeRegions」をご参照ください。

    3. DescribeInstances API を呼び出して、指定された条件を満たすインスタンスをフィルターします。詳細については、「DescribeInstances」をご参照ください。

  2. ローカル環境を設定し、サンプルコードを実行します。

    1. Alibaba Cloud SDK for Python をインストールまたはアップグレードします。

      sudo pip install --upgrade alibabacloud_ecs20140526
    2. .py ファイルを作成し、次のサンプルコードを追加します。

      サンプルコードを表示するにはここをクリック

      # coding=utf-8
      # Python SDK がインストールされていない場合は、「sudo pip install alibabacloud_ecs20140526」を実行します。
      # 最新の SDK バージョンを使用していることを確認してください。
      # 「sudo pip install --upgrade alibabacloud_ecs20140526」を実行してアップグレードします。
      
      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
      
      # ログ出力フォーマッターを設定します。
      logging.basicConfig(level=logging.INFO,
                          format="%(asctime)s %(name)s [%(levelname)s]: %(message)s",
                          datefmt='%m-%d %H:%M')
      
      logger = logging.getLogger()
      
      # ALIBABA_CLOUD_ACCESS_KEY_ID と ALIBABA_CLOUD_ACCESS_KEY_SECRET 環境変数が実行環境に設定されていることを確認してください。
      # プロジェクトコードが漏洩した場合、アクセスキーペアが侵害され、アカウント内のすべてのリソースのセキュリティが脅かされる可能性があります。次のサンプルコードでは、環境変数を使用してアクセスキーペアを取得します。この方法は参考用です。セキュリティを強化するため、STS トークンを使用することを推奨します。
      access_key = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
      access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
      region_id = '<yourRegionId>'  # 取得したリージョン ID を入力します。
      
      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: コマンドタイプ。有効な値:RunBatScript、RunPowerShellScript、RunShellScript。
          cmdcontent: コマンドの内容。
          instance_ids: インスタンス ID のリスト。
          """
          try:
              request = RunCommandRequest(
                  region_id=region_id,
                  type=cmdtype,
                  command_content=cmdcontent,
                  instance_id=instance_ids,
                  timeout=timeout  # コマンド実行のタイムアウト期間 (秒) 。デフォルト値は 60 です。実行するコマンドに基づいて、適切なタイムアウト期間を設定してください。
              )
              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: 再起動するインスタンス ID のリスト。
          Force: インスタンスを強制的に再起動するかどうかを指定します。デフォルトは 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():
          # Cloud Assistant コマンドのタイプを設定します。
          cmdtype = "RunShellScript"
          # Cloud Assistant コマンドの内容を設定します。
          cmdcontent = """
          #!/bin/bash
          echo helloworld
          """
          # タイムアウト期間を設定します。
          timeout = 60
          # コマンドを実行してから再起動するインスタンスの ID を入力します。
          ins_ids = ["i-bp185fcs****", "i-bp14wwh****", "i-bp13jbr****"]
      
          # コマンドを実行します。
          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
      
          # コマンドが完了するまで待機します。システムは 5 秒間隔で 10 回ステータスを照会します。必要に応じて、クエリの数と間隔を設定してください。
          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']))
      
          # インスタンスを再起動します。
          logger.warning("reboot instance Now")
          reboot_instances(ins_ids)
      
          time.sleep(5)
          # インスタンスが再起動して実行中状態になるまで待機します。システムは 10 秒間隔で 30 回ステータスを照会します。
          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()
      

      サンプルコードの次の値を、ご自身の値に置き換えます。

      • アクセスキー ID:

        access_key = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']

      • アクセスキーシークレット:

        access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']

      • リージョン ID:

        region_id = '<yourRegionId>'

      • インスタンス ID:

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

    3. .py ファイルを実行します。

      次の図は結果を示しています。コマンドが 3 つのインスタンスで実行されて helloworld が出力され、その後インスタンスが自動的に再起動します。openapi-exec-reboot

OOS を使用したインスタンスの一括再起動

CloudOps Orchestration Service (OOS) は、テンプレートを使用して運用保守タスクを自動化します。テンプレートでアクションを定義して実行することで、コマンドを実行し、インスタンスを一括で再起動します。

  1. テンプレート設定ページに移動します。

    1. OOS コンソールにログインします。

    2. [自動タスク] > [カスタムテンプレート] を選択します。

    3. テンプレートの作成をクリックします。

  2. テンプレートの設定を完了します。

    1. テンプレートの作成 ページで、デフォルト設定のままにし、次へ をクリックします。

    2. [YAML] タブをクリックし、次のコードを入力します。

      サンプルコードを表示するにはここをクリック

      FormatVersion: OOS-2019-06-01
      Description:
        en: Runs Cloud Assistant commands on multiple ECS instances in batches and then restarts the instances.
        name-en: Batch Run Commands 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 Instance
          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 content of the command to be run on the ECS instance.
            
          Label:
            en: Command Content
            
          Type: String
          MaxLength: 16384
          AssociationProperty: Code
          Default: echo hello
        workingDir:
          Description:
            en: 'The directory in which the command is run on the ECS instance. 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 the command execution on the ECS instance.
          Label:
            en: Timeout
          Type: Number
          Default: 600
        enableParameter:
          Description:
            en: Specifies whether the command contains secret or custom parameters.
          Label:
            en: Enable Parameter
          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 password name of the user that runs the command on the Windows instance.
          Label:
            en: Windows Password Name
          Type: String
          Default: ''
          AssociationProperty: SecretParameterName
        rateControl:
          Description:
            en: The rate control for the 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: Gets 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: Runs 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: Restarts the ECS instance.
          Properties:
            regionId: '{{ regionId }}'
            instanceId: '{{ ACS::TaskLoopItem }}'
          Loop:
            RateControl: '{{ rateControl }}'
            Items: '{{ getInstance.instanceIds }}'
      Outputs:
        instanceIds:
          Type: List
          Value: '{{ getInstance.instanceIds }}'
    3. テンプレートの作成 をクリックします。

    4. 表示されるダイアログボックスで、テンプレート名 runcommand_reboot_instances を入力し、OK をクリックします。

  3. テンプレートを実行します。

    1. 作成したテンプレートを見つけ、操作 列の エグゼキューションの作成 をクリックします。

    2. 実行設定を完了します。

      パラメーター設定 ページで複数のインスタンスを選択し、その他の設定はデフォルト値のままにします。exec-temp

    3. OK ページで、作成 をクリックします。

      テンプレートは自動的に実行されます。基本情報 ページで、実行ステータス成功 に変わるまで待ちます。

  4. 実行プロセスとタスクノードの詳細を表示します。

    1. [実行手順と結果][実行フローチャートを表示] をクリックすると、実行プロセスが表示されます。

      image

    2. Cloud Assistant コマンドの実行ステップをクリックします。[ループタスクリスト] タブで、各タスクノードの実行詳細を表示します。

      image