This topic describes how to use Alibaba Cloud SDK for Java to query all Elastic Compute Service (ECS) instances in a specific status. The sample code in this topic uses the running state as an example.

Prerequisites

Before you begin, ensure that the following requirements are met:
  • You must have an Alibaba Cloud account and an AccessKey pair (AccessKey ID and AccessKey secret) to use Alibaba Cloud SDK for Java. You can create and view your AccessKey pair on the AccessKey Management page in the Alibaba Cloud Management Console.
  • You have installed Alibaba Cloud SDK for Java. For more information about SDK versions, see Alibaba Cloud SDK.
    <dependencies>
        <! -- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.3</version>
        </dependency>
        <! -- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-ecs-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-ecs</artifactId>
            <version>4.17.4</version>
        </dependency>
    </dependencies>

Sample code

This section shows the sample request code:
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.ecs.model.v20140526.DescribeInstanceStatusRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeInstanceStatusResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;

/**
 * DescribeInstanceStatus    Queries the status of one or more ECS instances.
 * DescribeInstances    Queries the details of one or more instances.
 */
public class Demo{

    public static void main(String[] args) {
        Gson gson = new Gson();
        // Initialize request parameters.
        IAcsClient client = Initialization();
        // Used to store instance IDs.
        List<String> instanceIds = new ArrayList<>();
        // Query the status of all ECS instances.
        List<DescribeInstanceStatusResponse.InstanceStatus> instanceStatuses = TestDescribeInstanceStatus(client);
        for (DescribeInstanceStatusResponse.InstanceStatus instanceStatu : instanceStatuses) {
            // Query the IDs of all ECS instances that are in the running state.
            if (instanceStatu.getStatus().equals("Running")) {
                // Place the IDs of the instances that meet the requirement into the instanceIds set.
                instanceIds.add(instanceStatu.getInstanceId());
            }
        }
        // The DescribeInstances operation requires that the instance IDs be listed in a JSON string.
        // Therefore, you must convert the instanceIds set into a JSON string.
        String instanceIdsForJson = gson.toJson(instanceIds);
        System.out.println("IDs of instances that are in the running state:" + instanceIdsForJson);
        // Query the details of instances that are in the running state.       
        List<DescribeInstancesResponse.Instance> instances = DescribeInstances(client, instanceIdsForJson);
        System.out.println("Details of all instances that are in the running state:" + gson.toJson(instances));

    }

    /**
     * DescribeInstances    Queries the details of one or more instances.
     */
    private static List<DescribeInstancesResponse.Instance> DescribeInstances(IAcsClient client, String instanceIdsForJson) {
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        // The IDs of the instances that you want to query. It can be a JSON array that consists of up to 100 instance IDs. Separate multiple instance IDs with commas (,).
        // For example: ["i-xxxxxxxxx", "i-yyyyyyyyy", … "i-zzzzzzzzz"]
        request.setInstanceIds(instanceIdsForJson);
        try {
            DescribeInstancesResponse response = client.getAcsResponse(request);
            // Query and return the details of the instances.
            return response.getInstances();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            throw new RuntimeException();
        }
    }

    /**
     * DescribeInstanceStatus    Queries the status of one or more ECS instances.
     */
    private static List<DescribeInstanceStatusResponse.InstanceStatus> TestDescribeInstanceStatus(IAcsClient client) {
        DescribeInstanceStatusRequest request = new DescribeInstanceStatusRequest();
        // The page number of the page to return. Pages start from page 1.
        // Default value: 1.
        request.setPageNumber(1);
        // The number of entries to return on each page. Valid values: 1 to 50.
        // Default value: 10.
        // To query all information at once, we recommend that you select the maximum value.
        request.setPageSize(50);
        try {
            DescribeInstanceStatusResponse response = client.getAcsResponse(request);
            // Query the status and IDs of all instances.
            return response.getInstanceStatuses();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            throw new RuntimeException();
        }
    }

    /**
     * Initialization  Initializes common request parameters.
     */
    private static IAcsClient Initialization() {
        // Initialize request parameters.
        DefaultProfile profile = DefaultProfile.getProfile(
                "<your-region-id>", // The ID of the region.
                "<your-access-key-id>", // The AccessKey ID.
                "<your-access-key-secret>"); // The AccessKey secret.
        return new DefaultAcsClient(profile);
    }
}
                

Output

This section shows the sample success response:
The IDs of instances that are in the running state:
[
    "i-bp13****", 
    "i-bp1q****"
]
The details of all instances that are in the running state:
[
    {
        "instanceId": "i-bp13p*****", 
        "instanceName": "ehpc-hz-F*****", 
        "description": "", 
        "imageId": "centos_7_02_64_20G_alibase_20170818.vhd", 
        "oSName": "CentOS  7.2 64-bit", 
        "oSNameEn": "CentOS  7.2 64 bit", 
        "oSType": "linux", 
        "regionId": "cn-hangzhou", 
        "zoneId": "cn-hangzhou-b", 
        "clusterId": "", 
        "instanceType": "ecs.n1.tiny", 
        "cpu": 1, 
        "memory": 1024, 
        "hostName": "compute0", 
        "deploymentSetId": "", 
        "status": "Running", 
        "serialNumber": "b8561257-ebf4-4baa-860b-198d0c312a33", 
        "internetChargeType": "PayByTraffic", 
        "internetMaxBandwidthIn": 0, 
        "internetMaxBandwidthOut": 0, 
        "vlanId": "", 
        "creationTime": "2019-09-18T13:24Z", 
        "startTime": "2019-09-18T13:24Z", 
        "instanceNetworkType": "vpc", 
        "instanceChargeType": "PostPaid", 
        "saleCycle": "", 
        "expiredTime": "2099-12-31T15:59Z", 
        "autoReleaseTime": "", 
        "ioOptimized": true, 
        "deviceAvailable": true, 
        "instanceTypeFamily": "ecs.n1", 
        "gPUAmount": 0, 
        "gPUSpec": "", 
        "spotStrategy": "NoSpot", 
        "spotPriceLimit": 0, 
        "resourceGroupId": "rg-acfm*****", 
        "recyclable": false, 
        "stoppedMode": "Not-applicable", 
        "creditSpecification": "", 
        "deletionProtection": false, 
        "networkInterfaces": [], 
        "operationLocks": [ ], 
        "tags": [ ], 
        "securityGroupIds": [], 
        "publicIpAddress": [ ], 
        "innerIpAddress": [ ], 
        "rdmaIpAddress": [ ], 
        "vpcAttributes": {}, 
        "eipAddress": {}, 
        "dedicatedHostAttribute": {}, 
        "ecsCapacityReservationAttr": {}, 
        "dedicatedInstanceAttribute": {}
    }, 
    {
        "instanceId": "i-bp1j******", 
        "instanceName": "ehpc-hz-FYUr******", 
        "description": "", 
        "imageId": "centos_7_02_64_20G_alibase_20170818.vhd", 
        "oSName": "CentOS  7.2 64-bit", 
        "oSNameEn": "CentOS  7.2 64 bit", 
        "oSType": "linux", 
        "regionId": "cn-hangzhou", 
        "zoneId": "cn-hangzhou-b", 
        "clusterId": "", 
        "instanceType": "ecs.n1.tiny", 
        "cpu": 1, 
        "memory": 1024, 
        "hostName": "login0", 
        "deploymentSetId": "", 
        "status": "Running", 
        "serialNumber": "3dc23541-eab5-40aa-8ac7-8f87f9e28790", 
        "internetChargeType": "", 
        "internetMaxBandwidthIn": 0, 
        "internetMaxBandwidthOut": 0, 
        "vlanId": "", 
        "creationTime": "2019-09-18T13:24Z", 
        "startTime": "2019-09-18T13:24Z", 
        "instanceNetworkType": "vpc", 
        "instanceChargeType": "PostPaid", 
        "saleCycle": "", 
        "expiredTime": "2099-12-31T15:59Z", 
        "autoReleaseTime": "", 
        "ioOptimized": true, 
        "deviceAvailable": true, 
        "instanceTypeFamily": "ecs.n1", 
        "gPUAmount": 0, 
        "gPUSpec": "", 
        "spotStrategy": "NoSpot", 
        "spotPriceLimit": 0, 
        "resourceGroupId": "rg-acf******", 
        "recyclable": false, 
        "stoppedMode": "Not-applicable", 
        "creditSpecification": "", 
        "deletionProtection": false, 
        "networkInterfaces": [], 
        "operationLocks": [ ], 
        "tags": [ ], 
        "securityGroupIds": [], 
        "publicIpAddress": [ ], 
        "innerIpAddress": [ ], 
        "rdmaIpAddress": [ ], 
        "vpcAttributes": {}, 
        "eipAddress": {}, 
        "dedicatedHostAttribute": {}, 
        "ecsCapacityReservationAttr": {}, 
        "dedicatedInstanceAttribute": {}
    }
]