本教程详细介绍如何使用Alibaba Cloud SDK for Java获取某状态的所有ECS实例集合(本文代码示例为:运行中)。

前提条件

在使用本教程前,请确保已完成以下操作:
  • 使用Alibaba Cloud SDK for Java,您需要一个阿里云账号和访问密钥(AccessKey)。 请在阿里云控制台中的AccessKey管理页面上创建和查看您的AccessKey。
  • 确保您已经安装了Alibaba Cloud SDK for Java,准确的SDK版本号,请参见 阿里云开发工具包(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>

代码示例

本文操作示例主要以代码形式体现,具体代码如下:
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    获取一台或多台ECS实例的状态信息
 * DescribeInstances    查询一台或多台实例的详细信息
 */
public class Demo{

    public static void main(String[] args) {
        Gson gson = new Gson();
        // 初始化请求参数
        IAcsClient client = Initialization();
        // 用来存放实例ID
        List<String> instanceIds = new ArrayList<>();
        // 获取所有ECS实例的状态信息
        List<DescribeInstanceStatusResponse.InstanceStatus> instanceStatuses = TestDescribeInstanceStatus(client);
        for (DescribeInstanceStatusResponse.InstanceStatus instanceStatu : instanceStatuses) {
            // 获取所有状态为运行中的实例ID
            if (instanceStatu.getStatus().equals("Running")) {
                // 将符合条件的实例ID放入instanceIds集合中
                instanceIds.add(instanceStatu.getInstanceId());
            }
        }
        // 因为DescribeInstances接口中需要的实例ID为Json格式的字符串
        // 所以在此处需要把instanceIds转化为Json格式的字符串
        String instanceIdsForJson = gson.toJson(instanceIds);
        System.out.println("运行状态的实例id集合:" + instanceIdsForJson);
        // 查询状态为Running的实例详情undefined       List<DescribeInstancesResponse.Instance> instances = DescribeInstances(client, instanceIdsForJson);
        System.out.println("运行中的所有的实例详细信息:" + gson.toJson(instances));

    }

    /**
     * DescribeInstances    查询一台或多台实例的详细信息
     */
    private static List<DescribeInstancesResponse.Instance> DescribeInstances(IAcsClient client, String instanceIdsForJson) {
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        // 实例ID。取值可以由多个实例ID组成一个JSON数组,最多支持100个ID,ID之间用半角逗号(,)隔开
        // 参数示例: ["i-xxxxxxxxx", "i-yyyyyyyyy", … "i-zzzzzzzzz"]
        request.setInstanceIds(instanceIdsForJson);
        try {
            DescribeInstancesResponse response = client.getAcsResponse(request);
            // 获取到实例详细信息集合并返回
            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    获取一台或多台ECS实例的状态信息
     */
    private static List<DescribeInstanceStatusResponse.InstanceStatus> TestDescribeInstanceStatus(IAcsClient client) {
        DescribeInstanceStatusRequest request = new DescribeInstanceStatusRequest();
        // 实例状态列表的页码。起始值:1。
        // 默认值:1。
        request.setPageNumber(1);
        // 分页查询时设置的每页行数。取值范围:1~50
        // 默认值:10。
        // 为了可以一次取到所有,这里尽量选最大
        request.setPageSize(50);
        try {
            DescribeInstanceStatusResponse response = client.getAcsResponse(request);
            // 获取所有实例状态和实例ID
            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  初始化公共请求参数
     */
    private static IAcsClient Initialization() {
        // 初始化请求参数
        DefaultProfile profile = DefaultProfile.getProfile(
                // "<your-region-id>", // 您的可用区ID
                // "<your-access-key-id>", // 您的AccessKey ID
                "<your-access-key-secret>"); // 您的AccessKey Secret
        return new DefaultAcsClient(profile);
    }
}
				

执行结果

正确的返回结果类似如下:
运行状态的实例id集合:
[
    "i-bp13****", 
    "i-bp1q****"
]
运行中的所有的实例详细信息:
[
    {
        "instanceId": "i-bp13p*****", 
        "instanceName": "ehpc-hz-F*****", 
        "description": "", 
        "imageId": "centos_7_02_64_20G_alibase_20170818.vhd", 
        "oSName": "CentOS  7.2 64位", 
        "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位", 
        "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": {}
    }
]