All Products
Search
Document Center

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

Last Updated:Aug 12, 2024

You can use Cloud Assistant to simultaneously run a command on multiple Elastic Compute Service (ECS) instances. The command can be a shell, batch, or PowerShell command. This topic describes how to use ECS SDK for Java to check the status of Cloud Assistant Agent, run a Cloud Assistant command, and query the execution results of the Cloud Assistant command.

Prerequisites

  • The ECS instances are in the Running (Running) state. For information about how to use SDK for Java to check the status of ECS instances, see Query ECS instances.

  • SDK for Java 2.0 is installed in the development environment. The required dependencies are added to the Maven project. For more information, visit MVN Repository to view the latest versions of Maven.

  • The shell, batch, or PowerShell command is compiled based on the instance configurations and the operations that you want to perform.

Procedure

  1. Obtain the AccessKey pair, which consists of an AccessKey ID and an AccessKey secret, of your account and query the region ID.

    For more information, see Regions and zones and Obtain an AccessKey pair.

  2. Create a RunCommandBestPractice class to run a Cloud Assistant command on one or more ECS instances.

    The RunCommandBestPractice class performs the following actions:

    1. Check the status of Cloud Assistant Agent.

      Cloud Assistant Agent can run remote commands only when it is in the Running state. In this step, the RunCommandBestPractice class checks whether Cloud Assistant Agent is in the Running state, and takes action based on the check result.

      • If Cloud Assistant Agent is not in the Running state, try again later.

      • If Cloud Assistant Agent is in the Running state, go to the next step.

    2. Run a Cloud Assistant command on ECS instances.

    Sample code:

    import com.aliyun.auth.credentials.Credential;
    import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
    import com.aliyun.sdk.service.ecs20140526.models.RunCommandRequest;
    import com.aliyun.sdk.service.ecs20140526.models.RunCommandResponse;
    import com.aliyun.sdk.service.ecs20140526.AsyncClient;
    import com.google.gson.Gson;
    import darabonba.core.client.ClientOverrideConfiguration;
    import java.util.concurrent.CompletableFuture;
    
    public class RunCommand {
        public static void main(String[] args) throws Exception {
    
            // Configure credentials, including an AccessKey ID, an AccessKey secret, and a 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(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                    //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // Use a Security Token Service (STS) token.
                    .build());
    
            // Configure a client.
            AsyncClient client = AsyncClient.builder()
                    // You must specify a region ID.
                    .region("cn-nanjing")
                    // Use a configured HTTP client. If no HTTP client is configured, Apache HttpClient is used. Apache HttpClient is the default HTTP client.
                    .credentialsProvider(provider)
                    // Configure the service-level settings.
                    // Rewrite the client-level settings, including the endpoint and HTTP request parameters.
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    // Specify an endpoint. You can view endpoints at https://api.aliyun.com/product/Ecs.
                                    .setEndpointOverride("ecs.cn-nanjing.aliyuncs.com")
                    )
                    .build();
    
            // Configure the API request parameters.
            RunCommandRequest runCommandRequest = RunCommandRequest.builder()
                    // The region ID.
                    .regionId("cn-nanjing")
                    // The type of the command.
                    .type("RunShellScript") 
                    .commandContent("yourScript")
                    // The script that you want to execute.
                    .instanceId(java.util.Arrays.asList(
                            // The IDs of instances. You must specify this parameter.
                            "i-gc75qem27b6n******"
                    ))
                    // Rewrite the request-level settings, including the HTTP request parameters.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();
    
            // Asynchronously obtain the response to the API request.
            CompletableFuture<RunCommandResponse> response = client.runCommand(runCommandRequest);
            // Synchronously obtain the response to the API request.
            RunCommandResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            // Close the client.
            client.close();
        }
    }
    Note

    If Cloud Assistant Agent remains in a non-running state, we recommend that you troubleshoot the issue by performing the following operations:

    • Check whether Cloud Assistant Agent is installed. By default, ECS instances that are created from public images after December 1, 2017 are pre-installed with Cloud Assistant Agent. If Cloud Assistant Agent is not installed on your ECS instance, install Cloud Assistant Agent on the instance. For more information, see Install Cloud Assistant Agent.

    • Check network configurations. Make sure that you can perform domain name resolution or make network requests on the ECS instances and that you can access the endpoint of Cloud Assistant in the format of https://{regionId}.axt.aliyun.com. Replace {regionId} with the region ID of your ECS instance.

    A response similar to the following one is returned. Record the value of InvokeId, which indicates the task ID of the Cloud Assistant command.

    {
    	"headers":{
    		"Keep-Alive":"timeout=25",
    		"Access-Control-Expose-Headers":"*",
    		"Access-Control-Allow-Origin":"*",
    		"ETag":"1CT+jOmffBsGnpxVQRtwUaw5",
    		"x-acs-request-id":"E14423A1-4D3C-5FA9-BE6D-E5D9E******",
    		"Connection":"keep-alive",
    		"Content-Length":"115",
    		"Date":"Tue, 30 Jul 2024 05:28:59 GMT",
    		"Content-Type":"application/json;charset=utf-8",
    		"x-acs-trace-id":"1e73536caf966986c0de6******"
    	},
    	"statusCode":200,
    	"body":{
    		"commandId":"c-nj04s3ja******",
    		"invokeId":"t-nj04s3j******",
    		"requestId":"E14423A1-4D3C-5FA9-BE6D-E5D9E******"
    	}
    }
  3. Create a DescribeInvocationsSample.java class to check whether the command is successfully run.

    import com.aliyun.auth.credentials.Credential;
    import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
    import com.aliyun.sdk.service.ecs20140526.models.*;
    import com.aliyun.sdk.service.ecs20140526.*;
    import com.google.gson.Gson;
    import darabonba.core.client.ClientOverrideConfiguration;
    import java.util.concurrent.CompletableFuture;
    
    public class DescribeInvocations {
        public static void main(String[] args) throws Exception {
    
    
            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(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
    
                    .build());
    
            AsyncClient client = AsyncClient.builder()
                    // You must specify a region ID.
                    .region("cn-nanjing")
    
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                      // Specify an endpoint. You can view endpoints at https://api.aliyun.com/product/Ecs.
                                    .setEndpointOverride("ecs.cn-nanjing.aliyuncs.com")
    
                    )
                    .build();
    
    
            DescribeInvocationsRequest describeInvocationsRequest = DescribeInvocationsRequest.builder()
                    .regionId("cn-nanjing")
                    // You must enter the task ID of the Cloud Assistant command that you recorded.
                    .invokeId("t-nj04s3ja******")
                    .build();
    
    
            CompletableFuture<DescribeInvocationsResponse> response = client.describeInvocations(describeInvocationsRequest);
    
            DescribeInvocationsResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
    
            client.close();
        }
    
    }

Execution result

A response similar to the following one is returned. You can call the InvokeInstances operation to view the execution status and results of the command. For more information, see DescribeInvocations.

{
	"body":{
		"invocations":{
			"invocation":[
				{
					"commandContent":"eW91clNjc******",
					"commandDescription":"",
					"commandId":"c-nj04s3j******",
					"commandName":"cmd-2024-07-30",
					"commandType":"RunShellScript",
					"containerId":"",
					"containerName":"",
					"creationTime":"2024-07-30T05:28:59Z",
					"frequency":"",
					"invocationStatus":"Failed",
					"invokeId":"t-nj04s3******",
					"invokeInstances":{
						"invokeInstance":[
							{
								"creationTime":"2024-07-30T05:28:59Z",
								"dropped":0,
								"errorCode":"ExitCodeNonzero",
								"errorInfo":"the command execution exit code is not zero.",
								"exitCode":127,
								"finishTime":"2024-07-30T05:29:01Z",
								"instanceId":"i-gc75qem27b6n5******",
								"instanceInvokeStatus":"Finished",
								"invocationStatus":"Failed",
								"output":******
								"repeats":1,
								"startTime":"2024-07-30T05:29:00Z",
								"stopTime":"",
								"timed":false,
								"updateTime":"2024-07-30T05:29:01Z"
							}
						]
					},
					"invokeStatus":"Finished",
					"parameters":"{}",
					"repeatMode":"Once",
					"tags":{
						"tag":[]
					},
					"terminationMode":"Process",
					"timed":false,
					"timeout":60,
					"username":"",
					"workingDir":""
				}
			]
		},
		"nextToken":"",
		"pageNumber":1,
		"pageSize":10,
		"requestId":"7AB4D3FF-E251-5235-99C4-1A18099E0F01",
		"totalCount":1
	},
	"headers":{
		"Access-Control-Allow-Origin":"*",
		"Access-Control-Expose-Headers":"*",
		"Connection":"keep-alive",
		"Content-Length":"1207",
		"Content-Type":"application/json;charset=utf-8",
		"Date":"Tue, 30 Jul 2024 05:41:14 GMT",
		"ETag":"13/WTudylqHr+WPQBunND8g7",
		"Keep-Alive":"timeout=25",
		"Vary":"Accept-Encoding",
		"x-acs-request-id":"7AB4D3FF-E251-5235-99C4******",
		"x-acs-trace-id":"028dd251acfb4dbfceac9b56e******f"
	},
	"statusCode":200
}