All Products
Search
Document Center

Elastic Compute Service:Use Cloud Assistant to manage ECS instances without logging on to the instances

Last Updated:Nov 27, 2024

Cloud Assistant enables the execution of commands on multiple Elastic Compute Service (ECS) instances simultaneously. This topic explains how to verify the Cloud Assistant Agent status, execute Cloud Assistant commands, and check the results of these commands using the SDK for Java.

Prerequisites

  • Ensure the target ECS instance has the Cloud Assistant Agent installed. Use DescribeCloudAssistantStatus to check the agent status. If the agent is not installed, refer to Install Cloud Assistant Agent.

  • Configure the runtime environment with the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. For configuration details, see Configure environment variables in Linux, macOS, and Windows.

  • The ECS instance must be in the Running state. Use DescribeInstances to check the instance status.

  • Prepare the Shell, Bat, or PowerShell commands for Cloud Assistant according to the configuration of the ECS instance and the desired operations.

  • Add the dependency of the SDK for Java to your development environment. For more information, see ECS SDK for Java.

Note

To protect the AccessKey pair of your Alibaba Cloud account, we recommend that you create a Resource Access Management (RAM) user, grant the RAM user access to ECS, and then use the AccessKey pair of the RAM user to call the SDK for Java. For more information, see RAM users.

Procedure

Query the status of Cloud Assistant Agent on an instance

Before managing or operating ECS instances with Cloud Assistant, we recommend that you use DescribeCloudAssistantStatus to check the agent status.

Sample code

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();
    }
}

Sample response

In the response, CloudAssistantStatus indicates the operational status of Cloud Assistant on the instance. Ensure that CloudAssistantStatus is set to true before using Cloud Assistant Agent to manage ECS instances.

{
  "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
      }
    ]
  }
}

Execute commands on instances using Cloud Assistant

Execute Shell, PowerShell, or Bat commands on one or more ECS instances using RunCommand.

Note

Ensure the Windows instance has the PowerShell module installed before running a PowerShell command.

Sample code

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();
    }
}

Sample response

The response includes CommandId, the command ID, and InvokeId, the execution ID. Keep these IDs for future reference to the command execution result.

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

Obtain command execution results of Cloud Assistant

To view the execution result of a command on the ECS instance, use parameters such as InvokeId and CommandId with DescribeInvocationResults.

Sample code

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();
    }
}

Sample response

The response includes InvocationStatus, showing the execution status on the instance, and Output, displaying the output of the execution.

{
  "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
  }
}