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

Elastic Compute Service:Cloud Assistantを使用してインスタンスにログインせずにECSインスタンスを管理する

最終更新日:Dec 03, 2024

Cloud Assistantを使用すると、複数のECS (Elastic Compute Service) インスタンスで同時にコマンドを実行できます。 このトピックでは、SDK for Javaを使用して、Cloud Assistant Agentのステータスを確認し、Cloud Assistantコマンドを実行し、これらのコマンドの結果を確認する方法について説明します。

前提条件

  • 対象のECSインスタンスにCloud Assistant Agentがインストールされていることを確認します。 DescribeCloudAssistantStatusを使用して、エージェントのステータスを確認します。 エージェントがインストールされていない場合は、「Cloud Assistant agentのインストール」をご参照ください。

  • 環境変数ALIBABA_CLOUD_ACCESS_KEY_IDおよびALIBABA_CLOUD_ACCESS_KEY_SECRETを使用してランタイム環境を設定します。 設定の詳細については、「Linux、macOS、およびWindowsでの環境変数の設定」をご参照ください。

  • ECSインスタンスは 実行中 状態である必要があります。 DescribeInstancesを使用してインスタンスのステータスを確認します。

  • ECSインスタンスの設定と目的の操作に応じて、Cloud Assistant用のShell、Bat、またはPowerShellコマンドを準備します。

  • SDK for Javaの依存関係を開発環境に追加します。 詳細については、「ECS SDK For Java」をご参照ください。

説明

Alibaba CloudアカウントのAccessKeyペアを保護するために、RAM (Resource Access Management) ユーザーを作成し、RAMユーザーにECSへのアクセス権を付与し、RAMユーザーのAccessKeyペアを使用してSDK for Javaを呼び出すことを推奨します。 詳細は、「RAMユーザー」をご参照ください。

手順

インスタンス上のCloud Assistant Agentのステータスの照会

Cloud AssistantでECSインスタンスを管理または運用する前に、DescribeCloudAssistantStatusを使用してエージェントのステータスを確認することを推奨します。

サンプルコード

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.ecs20140526.AsyncClient;
import com.aliyun.sdk.service.ecs20140526.models.DescribeCloudAssistantStatusRequest;
import com.aliyun.sdk.service.ecs20140526.models.DescribeCloudAssistantStatusResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class DescribeCloudAssistantStatus {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // Configure credentials, including AccessKey, Secret, and Token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the on-premises environment.
                .accessKeyId("ALIBABA_CLOUD_ACCESS_KEY_ID")
                .accessKeySecret("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // Use a Security Token Service (STS) token
                .build());
        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                // Region ID
                .region("cn-hangzhou") 
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Specify an endpoint. For information about endpoints, see the topic at the following URL: https://api.aliyun.com/product/Ecs
                                .setEndpointOverride("ecs-cn-hangzhou.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // Parameter settings for API request
        DescribeCloudAssistantStatusRequest describeCloudAssistantStatusRequest = DescribeCloudAssistantStatusRequest.builder()
                .regionId("cn-hangzhou")
                .instanceId(java.util.Arrays.asList(
                        // 
                        "i-bp13orb*******"
                ))
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();
        // Asynchronously get the return value of the API request
        CompletableFuture<DescribeCloudAssistantStatusResponse> response = client.describeCloudAssistantStatus(describeCloudAssistantStatusRequest);
        // Synchronously get the return value of the API request
        DescribeCloudAssistantStatusResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        client.close();
    }
}

サンプル応答

応答では、CloudAssistantStatusはインスタンスのCloud Assistantの動作ステータスを示します。 Cloud Assistant Agentを使用してECSインスタンスを管理する前に、CloudAssistantStatustrueに設定されていることを確認してください。

{
  "TotalCount": 1,
  "PageSize": 1,
  "RequestId": "E020564A-****************",
  "NextToken": "",
  "PageNumber": 1,
  "InstanceCloudAssistantStatusSet": {
    "InstanceCloudAssistantStatus": [
      {
        "CloudAssistantVersion": "2.2.3.612",
        "SupportSessionManager": true,
        "InstanceId": "i-bp11*************",
        "InvocationCount": 5,
        "OSType": "Linux",
        "CloudAssistantStatus": "true",
        "LastHeartbeatTime": "2024-09-10T06:42:52Z",
        "LastInvokedTime": "2024-09-10T03:22:23Z",
        "ActiveTaskCount": 0
      }
    ]
  }
}

Cloud Assistantを使用したインスタンスでのコマンドの実行

RunCommandを使用して、1つ以上のECSインスタンスでShell、PowerShell、またはBatコマンドを実行します。

説明

PowerShellコマンドを実行する前に、WindowsインスタンスにPowerShellモジュールがインストールされていることを確認します。

サンプルコード

package com.aliyun.simple;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.ecs20140526.AsyncClient;
import com.aliyun.sdk.service.ecs20140526.models.RunCommandRequest;
import com.aliyun.sdk.service.ecs20140526.models.RunCommandResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class RunCommand {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // Configure credentials, including AccessKey, Secret, and Token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the on-premises environment.
                .accessKeyId("ALIBABA_CLOUD_ACCESS_KEY_ID")
                .accessKeySecret("ALIBABA_CLOUD_ACCESS_KEY_SECRETNDAlRU3Y8Q")
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // Use a Security Token Service (STS) token
                .build());
        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Specify an endpoint. For information about endpoints, see the topic at the following URL: https://api.aliyun.com/product/Ecs
                                .setEndpointOverride("ecs-cn-hangzhou.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // Parameter settings for API request
        RunCommandRequest runCommandRequest = RunCommandRequest.builder()
                .regionId("cn-hangzhou")
                .type("RunShellScript")
                .commandContent("{Command content to be executed on ECS}")
                .instanceId(java.util.Arrays.asList(
                        "i-bp11cx***********"
                ))
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();
        // Asynchronously get the return value of the API request
        CompletableFuture<RunCommandResponse> response = client.runCommand(runCommandRequest);
        // Synchronously get the return value of the API request
        RunCommandResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        client.close();
    }
}

サンプル応答

レスポンスには、コマンドIDであるCommandIdと、実行IDであるInvokeIdが含まれます。 これらのIDは, コマンドの実行結果を今後参照するために保管してください。

{
  "RequestId": "AC95DAC5-************************",
  "CommandId": "c-hz04*****************",
  "InvokeId": "t-hz04*************"
}

Cloud Assistantのコマンド実行結果の取得

ECSインスタンスでのコマンドの実行結果を表示するには、InvokeIdCommandIdなどのパラメーターとDescribeInvocationResultsを使用します。

サンプルコード

package com.aliyun.simple;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.ecs20140526.AsyncClient;
import com.aliyun.sdk.service.ecs20140526.models.DescribeInvocationResultsRequest;
import com.aliyun.sdk.service.ecs20140526.models.DescribeInvocationResultsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class DescribeInvocationResults {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // Configure credentials, including AccessKey, Secret, and Token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the on-premises environment.
                .accessKeyId("ALIBABA_CLOUD_ACCESS_KEY_ID")
                .accessKeySecret("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // Use a Security Token Service (STS) token
                .build());
        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Specify an endpoint. For information about endpoints, see the topic at the following URL: https://api.aliyun.com/product/Ecs
                                .setEndpointOverride("ecs-cn-hangzhou.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // Parameter settings for API request
        DescribeInvocationResultsRequest describeInvocationResultsRequest = DescribeInvocationResultsRequest.builder()
                .regionId("cn-hangzhou")
                .invokeId("t-hz0**********")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();
        // Asynchronously get the return value of the API request
        CompletableFuture<DescribeInvocationResultsResponse> response = client.describeInvocationResults(describeInvocationResultsRequest);
        // Synchronously get the return value of the API request
        DescribeInvocationResultsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        client.close();
    }
}

サンプル応答

応答には、インスタンスの実行ステータスを示すInvocationStatusと、実行の出力を表示するOutputが含まれます。

{
  "RequestId": "2D4967FE-************************",
  "Invocation": {
    "InvocationResults": {
      "InvocationResult": [
        {
          "Dropped": 2517254,
          "InvocationStatus": "Success",
          "InstanceId": "i-bp11c***********",
          "ExitCode": 0,
          "ErrorInfo": "",
          "StartTime": "2024-09-10T03:22:24Z",
          "Repeats": 1,
          "InvokeRecordStatus": "Finished",
          "FinishedTime": "2024-09-10T03:22:26Z",
          "Username": "",
          "ContainerId": "",
          "ContainerName": "",
          "Output":"{Command execution output}",
          "Launcher": "",
          "CommandId": "c-hz04**********",
          "ErrorCode": "",
          "InvokeId": "t-hz04w**********",
          "TerminationMode": "Process",
          "Tags": {
            "Tag": []
          },
          "StopTime": ""
        }
      ]
    },
    "TotalCount": 1,
    "PageSize": 10,
    "NextToken": "",
    "PageNumber": 1
  }
}