本教程详细介绍如何使用Alibaba Cloud SDK for Java查询创建ECS所需要的资源信息,包括可用区ID、实例规格、可用镜像资源、专有网络VPC、交换机和安全组等。

前提条件

在使用本教程之前,请确保已完成以下操作:

  • 使用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 --&gt;     <dependency&gt;         <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.*; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.google.gson.Gson; import java.util.List;  /**  * 查询创建ECS所需其他资源信息  *  * DescribeZones    查询一个阿里云地域下的可用区  * DescribeInstanceTypes    查询云服务器ECS提供的实例规格资源  * DescribeImages    查询可以使用的镜像资源  * DescribeVpcs    查询已创建的VPC  * DescribeVSwitches    查询已创建的交换机  * DescribeSecurityGroups    查询创建的安全组的基本信息  */ public class DescribeInstanceRequredResource {      public static void main(String[] args) {         IAcsClient client = Initialization();         //     查询一个阿里云地域下的可用区         List<DescribeZonesResponse.Zone> zones = DescribeZones(client);         // 查询云服务器ECS提供的实例规格资源         List<DescribeInstanceTypesResponse.InstanceType> instanceTypeList = DescribeInstanceTypes(client);         // 查询可以使用的镜像资源         List<DescribeImagesResponse.Image> images = DescribeImages(client);         // 查询已创建的VPC         List<DescribeVpcsResponse.Vpc> vpcs = DescribeVpcs(client);         // 查询已创建的交换机         List<DescribeVSwitchesResponse.VSwitch> vSwitches = DescribeVSwitches(client);         // 查询创建的安全组的基本信息         List<DescribeSecurityGroupsResponse.SecurityGroup> securityGroups = DescribeSecurityGroups(client);     }      /**      * DescribeSecurityGroups    查询创建的安全组的基本信息      */     private static List<DescribeSecurityGroupsResponse.SecurityGroup> DescribeSecurityGroups(IAcsClient client) {         DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();         // 网络类型         request.setNetworkType("vpc");         try {             DescribeSecurityGroupsResponse response = client.getAcsResponse(request);             System.out.println("--------------------查询已创建的安全组基本信息--------------------");             System.out.println(new Gson().toJson(response));             return response.getSecurityGroups();         } catch (ClientException e) {             System.out.println("ErrCode:" + e.getErrCode());             System.out.println("ErrMsg:" + e.getErrMsg());             System.out.println("RequestId:" + e.getRequestId());             return null;         }     }      /**      * DescribeVSwitches    查询已创建的交换机      */     private static List<DescribeVSwitchesResponse.VSwitch> DescribeVSwitches(IAcsClient client) {         DescribeVSwitchesRequest request = new DescribeVSwitchesRequest();         //         request.setIsDefault(false);         try {             DescribeVSwitchesResponse response = client.getAcsResponse(request);             System.out.println("--------------------查询已创建的交换机--------------------");             System.out.println(new Gson().toJson(response));             return response.getVSwitches();         } catch (ClientException e) {             System.out.println("ErrCode:" + e.getErrCode());             System.out.println("ErrMsg:" + e.getErrMsg());             System.out.println("RequestId:" + e.getRequestId());             return null;         }     }      /**      * DescribeVpcs    查询已创建的VPC      */     private static List<DescribeVpcsResponse.Vpc> DescribeVpcs(IAcsClient client) {         DescribeVpcsRequest request = new DescribeVpcsRequest();         // 是否查询指定地域下的默认VPC,取值:         // true(默认值):查询指定地域下的所有VPC。         // false:不查询默认VPC。         request.setIsDefault(false);         try {             DescribeVpcsResponse response = client.getAcsResponse(request);             System.out.println("--------------------查询已创建的VPC--------------------");             System.out.println(new Gson().toJson(response));             return response.getVpcs();         } catch (ClientException e) {             System.out.println("ErrCode:" + e.getErrCode());             System.out.println("ErrMsg:" + e.getErrMsg());             System.out.println("RequestId:" + e.getRequestId());             return null;         }     }      /**      * DescribeImages    查询可以使用的镜像资源      */     private static List<DescribeImagesResponse.Image> DescribeImages(IAcsClient client) {         DescribeImagesRequest request = new DescribeImagesRequest();         // 镜像的体系架构。取值范围:         // i386         // x86_64         request.setArchitecture("x86_64");         // 镜像来源。取值范围:         // system:阿里云提供的公共镜像。         // self:您创建的自定义镜像。         // others:其他阿里云用户共享给您的镜像。         // marketplace:镜像市场提供的镜像。您查询到的云市场镜像可以直接使用,无需提前订阅。您需要自行留意云市场镜像的收费详情         // 默认值:空,空表示返回取值为system、self以及others的结果。         request.setImageOwnerAlias("system");         // 镜像需要被使用到的场景。取值范围:         // CreateEcs(默认):创建实例         // ChangeOS:更换系统盘/更换操作系统         request.setActionType("CreateEcs");         // 镜像的操作系统类型。取值范围:         // windows         // linux         request.setOSType("linux");         try {             DescribeImagesResponse response = client.getAcsResponse(request);             System.out.println("--------------------查询可以使用的镜像资源--------------------");             System.out.println(new Gson().toJson(response));             return response.getImages();         } catch (ClientException e) {             System.out.println("ErrCode:" + e.getErrCode());             System.out.println("ErrMsg:" + e.getErrMsg());             System.out.println("RequestId:" + e.getRequestId());             return null;         }     }      /**      * DescribeInstanceTypes    查询云服务器ECS提供的实例规格资源      */     private static List<DescribeInstanceTypesResponse.InstanceType> DescribeInstanceTypes(IAcsClient client) {         DescribeInstanceTypesRequest request = new DescribeInstanceTypesRequest();         // 实例规格所属的规格族。此参数可选,不填写时返回所有实例规格         // request.setInstanceTypeFamily("ecs.t1");         try {             DescribeInstanceTypesResponse response = client.getAcsResponse(request);             System.out.println("--------------------查询ECS提供的实例规格资源--------------------");             System.out.println(new Gson().toJson(response));             return response.getInstanceTypes();         } catch (ClientException e) {             System.out.println("ErrCode:" + e.getErrCode());             System.out.println("ErrMsg:" + e.getErrMsg());             System.out.println("RequestId:" + e.getRequestId());             return null;         }     }      /**      * DescribeZones    查询一个阿里云地域下的可用区      */     private static List<DescribeZonesResponse.Zone> DescribeZones(IAcsClient client) {         DescribeZonesRequest request = new DescribeZonesRequest();         // 可用区所在的地域ID。您可以调用DescribeRegions查看最新的阿里云地域列表         request.setRegionId("cn-shanghai");         // 根据汉语、英语和日语筛选返回结果。更多详情,请参见RFC7231         // 取值范围:         // zh-CN         // en-US         // ja         // 默认值:zh-CN。         request.setAcceptLanguage("zh-CN");         try {             DescribeZonesResponse response = client.getAcsResponse(request);             System.out.println("--------------------查询地域下的可用区--------------------");             System.out.println(new Gson().toJson(response));             return response.getZones();         } catch (ClientException e) {             System.out.println("ErrCode:" + e.getErrCode());             System.out.println("ErrMsg:" + e.getErrMsg());             System.out.println("RequestId:" + e.getRequestId());         }         return null;     }     /**      * 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);     } } 				

执行结果

正确的返回结果类似如下:

--------------------查询地域下的可用区-------------------- {     "requestId": "E29890A7-A9AF-462A-80FC-01818A2BADD0",      "zones": [         {             "zoneId": "cn-shanghai-g",              "localName": "华东 2 可用区 G",              "availableResources": [],              "availableResourceCreation": [],              "availableDiskCategories": [],              "availableInstanceTypes": [],              "availableVolumeCategories": [],              "availableDedicatedHostTypes": [],              "dedicatedHostGenerations": []         },          {             "zoneId": "cn-shanghai-f",              "localName": "华东 2 可用区 F",              "availableResources": [],              "availableResourceCreation": [],              "availableDiskCategories": [],              "availableInstanceTypes": [],              "availableVolumeCategories": [],              "availableDedicatedHostTypes": [],              "dedicatedHostGenerations": []         },          {             "zoneId": "cn-shanghai-e",              "localName": "华东 2 可用区 E",              "availableResources": [],              "availableResourceCreation": [],              "availableDiskCategories": [],              "availableInstanceTypes": [],              "availableVolumeCategories": [],              "availableDedicatedHostTypes": [],              "dedicatedHostGenerations": []         },          {             "zoneId": "cn-shanghai-d",              "localName": "华东 2 可用区 D",              "availableResources": [],              "availableResourceCreation": [],              "availableDiskCategories": [],              "availableInstanceTypes": [],              "availableVolumeCategories": [],              "availableDedicatedHostTypes": [ ],              "dedicatedHostGenerations": [ ]         },          {             "zoneId": "cn-shanghai-c",              "localName": "华东 2 可用区 C",              "availableResources": [],              "availableResourceCreation": [],              "availableDiskCategories": [],              "availableInstanceTypes": [],              "availableVolumeCategories": [],              "availableDedicatedHostTypes": [ ],              "dedicatedHostGenerations": [ ]         },          {             "zoneId": "cn-shanghai-b",              "localName": "华东 2 可用区 B",              "availableResources": [],              "availableResourceCreation": [],              "availableDiskCategories": [],              "availableInstanceTypes": [],              "availableVolumeCategories": [],              "availableDedicatedHostTypes": [ ],              "dedicatedHostGenerations": [ ]         },          {             "zoneId": "cn-shanghai-a",              "localName": "华东 2 可用区 A",              "availableResources": [],              "availableResourceCreation": [],              "availableDiskCategories": [],              "availableInstanceTypes": [],              "availableVolumeCategories": [],              "availableDedicatedHostTypes": [ ],              "dedicatedHostGenerations": [ ]         }     ] } --------------------查询ECS提供的实例规格资源-------------------- {     "requestId": "AC5DEE66-446C-40BB-878F-DFBC8B05A657",      "instanceTypes": [         {             "instanceTypeId": "ecs.t1.xsmall",              "cpuCoreCount": 1,              "memorySize": 0.5,              "instanceTypeFamily": "ecs.t1",              "localStorageCategory": "",              "gPUAmount": 0,              "gPUSpec": "",              "eniQuantity": 1,              "eniPrivateIpAddressQuantity": 1,              "instanceFamilyLevel": "EntryLevel"         },          {...},          {...},          {...}     ] } --------------------查询可以使用的镜像资源-------------------- {     "requestId": "1B8E9703-E3A0-472D-B02F-A65CF4AD9D82",      "regionId": "cn-hangzhou",      "totalCount": 25,      "pageNumber": 1,      "pageSize": 10,      "images": [         {             "progress": "100%",              "imageId": "ubuntu_18_04_64_20G_alibase_20190624.vhd",              "imageName": "ubuntu_18_04_64_20G_alibase_20190624.vhd",              "imageVersion": "",              "description": "",              "size": 20,              "imageOwnerAlias": "system",              "isSupportIoOptimized": true,              "isSupportCloudinit": true,              "oSName": "Ubuntu  18.04 64位",              "oSNameEn": "Ubuntu  18.04 64 bit",              "architecture": "x86_64",              "status": "Available",              "productCode": "",              "isSubscribed": false,              "creationTime": "2019-06-25T06:36:00Z",              "isSelfShared": "",              "oSType": "linux",              "platform": "Ubuntu",              "usage": "instance",              "isCopied": false,              "resourceGroupId": "",              "diskDeviceMappings": [ ],              "tags": [ ]         },          {             "progress": "100%",              "imageId": "ubuntu_16_04_64_20G_alibase_20190620.vhd",              "imageName": "ubuntu_16_04_64_20G_alibase_20190620.vhd",              "imageVersion": "",              "description": "",              "size": 20,              "imageOwnerAlias": "system",              "isSupportIoOptimized": true,              "isSupportCloudinit": true,              "oSName": "Ubuntu  16.04 64位",              "oSNameEn": "Ubuntu  16.04 64 bit",              "architecture": "x86_64",              "status": "Available",              "productCode": "",              "isSubscribed": false,              "creationTime": "2019-06-24T07:14:01Z",              "isSelfShared": "",              "oSType": "linux",              "platform": "Ubuntu",              "usage": "instance",              "isCopied": false,              "resourceGroupId": "",              "diskDeviceMappings": [ ],              "tags": [ ]         }     ] } --------------------查询已创建的VPC-------------------- {     "requestId": "5F9210ED-7703-4783-BE3A-93EBEE474868",      "totalCount": 20,      "pageNumber": 1,      "pageSize": 10,      "vpcs": [         {             "vpcId": "vpc-bp1t3******",              "regionId": "cn-hangzhou",              "status": "Available",              "vpcName": "lalalala",              "creationTime": "2019-08-14T07:52:28Z",              "cidrBlock": "172.16.0.0/12",              "vRouterId": "vrt-bp1k*****",              "description": "",              "isDefault": false,              "vSwitchIds": [],              "userCidrs": [ ]         },          {             "vpcId": "vpc-bp1m7*****",              "regionId": "cn-hangzhou",              "status": "Available",              "vpcName": "hello",              "creationTime": "2019-04-08T00:05:29Z",              "cidrBlock": "192.168.0.0/16",              "vRouterId": "vrt-bp1fw******",              "description": "",              "isDefault": false,              "vSwitchIds": [],              "userCidrs": [ ]         }     ] } --------------------查询已创建的交换机-------------------- {     "requestId": "921AFB24-073D-4CCF-A79E-90935873CACE",      "totalCount": 29,      "pageNumber": 1,      "pageSize": 10,      "vSwitches": [         {             "vSwitchId": "vsw-bp1ug*****",              "vpcId": "vpc-bp1t3*****",              "status": "Available",              "cidrBlock": "172.16.0.0/24",              "zoneId": "cn-hangzhou-b",              "availableIpAddressCount": 251,              "description": "",              "vSwitchName": "lalalala",              "creationTime": "2019-08-14T07:52:31Z",              "isDefault": false,              "resourceGroupId": "rg-acfmxaz*****"         },          {             "vSwitchId": "vsw-bp11*****",              "vpcId": "vpc-bp1m7v2*****",              "status": "Available",              "cidrBlock": "192.168.100.0/29",              "zoneId": "cn-hangzhou-b",              "availableIpAddressCount": 3,              "description": "",              "vSwitchName": "lalalala",              "creationTime": "2019-08-14T07:48:19Z",              "isDefault": false,              "resourceGroupId": "rg-acfm*****"         }     ] } --------------------查询已创建的安全组基本信息-------------------- {     "requestId": "307D5B66-BCC7-4E33-91C1-5B669A49A9A3",      "regionId": "cn-hangzhou",      "totalCount": 47,      "pageNumber": 1,      "pageSize": 10,      "securityGroups": [         {             "securityGroupId": "sg-bp1asugr34gznjaz2x4z",              "description": "Created and used by E-HPC cluster ehpc-hz-FYUr32H5yi",              "securityGroupName": "sg1",              "vpcId": "vpc-bp1gnu8br4ay7beb2wxl8",              "creationTime": "2019-09-18T13:24:10Z",              "securityGroupType": "normal",              "resourceGroupId": "",              "tags": [ ]         },          {             "securityGroupId": "sg-bp11rndau05v8b0nkx5k",              "description": "",              "securityGroupName": "",              "vpcId": "vpc-bp1t36rn9l53iwbsf8x2q",              "creationTime": "2019-09-05T06:25:05Z",              "securityGroupType": "normal",              "resourceGroupId": "",              "tags": [ ]         }     ] }