This topic describes how to use the Alibaba Cloud ECS Java SDK to call the DescribeInstances operation to filter ECS instances based on specified conditions.

Prerequisites

You must have at least one existing ECS instance. For more information, see Batch create ECS instances.

Background information

You can call this operation to query instances that meet specified conditions. For example:
  • Before you modify the public bandwidth of an instance with a specific ID, you can filter eligible ECS instances based on the billing method of instances, running status, and billing method for network usage.
  • Before you update applications on an instance, query all ECS instances that use the same image as the instance.

Sample code

The following code can be used to query VPC-type pay-as-you-go instances that use pay-by-traffic billing method for network usage in the China (Hangzhou) region.
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import java.util.*;
import com.aliyuncs.ecs.model.v20140526.*;

public class DescribeInstances {

    public static void main(String[] args) {
        // Create and initialize a DefaultAcsClient instance.
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<yourAccessKeyId>", "<yourAccessSecret>");
        IAcsClient client = new DefaultAcsClient(profile);

        // Create an API request and configure the parameters.
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        request.setRegionId("cn-hangzhou");
        request.setInstanceNetworkType("vpc");
        request.setInstanceChargeType("PostPaid");
        request.setInternetChargeType("PayByTraffic");
        request.setPageSize(10);

        try {
        // Initiate the request and handle the response or exceptions.
            DescribeInstancesResponse response = client.getAcsResponse(request);
        for (DescribeInstancesResponse.Instance instance:response.getInstances()) 
            {
                 System.out.println(instance.getImageId());
                 System.out.println(instance.getInstanceId());
                 System.out.println(instance.getPublicIpAddress());
             }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }

    }
}

Result

The preceding code requests the ID of the image, the ID of the instance, and the public IP address. The response is:
i-bp1gvi17n5p8hav0i***
[47.97. ***.21]
ubuntu_16_04_64_20G_alibase_20190620.vhd
i-bp1gc5z6103qs2t40***
[47.99. ***.82]
centos_7_06_64_20G_alibase_20190711.vhd