通过SDK实现资源管理

更新时间:2025-01-22 07:43:18

此教程演示如何通过SDK调用云控制API实现资源管理。将使用Java语言,以专有网络VPC的交换机为例,演示如何集成SDK,查询资源元数据,如何创建、查询、更新与删除资源,以及遇到云控制API采用异步操作处理任务时如何查询任务状态。

前提条件

  1. RAM用户:

    • 由于阿里云账号(主账号)拥有资源的所有权限,其AccessKey一旦泄露风险巨大,所以建议您使用满足最小化权限需求的RAM用户的AccessKey。具体操作方式请参见创建AccessKey

    • RAM用户授予操作专有网络VPC相关资源的权限。此教程涉及VPCVSwitch多种操作,所以选择系统权限策略AliyunVPCFullAccess,您在使用的时候可以根据需求进行自定义授权,请参见创建自定义权限策略

    • 在环境变量中配置AccessKey,具体操作步骤请参见Linux、macOSWindows系统配置环境变量

  2. VPC

    您需要有一个VPC资源,用于交换机的绑定,如果您没有VPC,请参见创建和管理专有网络

  3. 资源元数据

    资源管理是基于资源元数据的操作,因此您需要熟悉资源元数据

  4. 同步操作与异步操作

    此教程中创建资源和删除资源的请求,云控制API处理任务时采用异步操作,你需要了解同步操作与异步操作的概念。云控制API采用异步处理时,查询任务状态参见教程中的查询任务

  5. Java

    最低要求Java 8

初始化项目

引入云控制APISDK,获取环境变量中的AccessKey。

  1. 在项目中引入SDK,具体参见安装SDK,SDK能够帮助您高效的集成与使用云控制API。本例中,SDK引入如下:

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>cloudcontrol20220830</artifactId>
        <version>1.1.1</version>
    </dependency>
  2. 新建一个ExampleDemo类,用于实现资源管理。ExampleDemo类中添加createClient方法,用于获取环境变量中的AccessKey,初始化账号Client。示例如下:

    /**
     * 初始化账号Client
     * @return Client
     */
    public static Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html。
        Config config = new Config()
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Endpoint 请参考 https://api.aliyun.com/product/cloudcontrol
        config.endpoint = "cloudcontrol.aliyuncs.com";
        return new Client(config);
    }

查询资源类型的详情

通过产品code与资源类型code,查询资源类型的详情,返回数据为资源元数据。后续的创建、查询、列举和删除等资源管理操作都是基于资源元数据。

  1. 调用GetResourceType,获取资源类型的详情。此教程的示例为专有网络VPC的交换机,专有网络VPC的产品codeVPC,交换机的资源类型codeVSwitch。调用示例如下:

    说明

    产品code和资源code的获取方式,请参见:产品code和资源code哪里获取?

    /**
     * 查询资源类型的详情
     * @param productCode      产品code,此例中为"VPC"
     * @param resourceTypeCode 资源类型code,此例中为“VSwitch”
     * @param client           账号client
     * @return resourceTypeWithOptions 返回对象
     */
    public GetResourceTypeResponse getResourceType(String productCode, String resourceTypeCode, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resourceTypes/" + resourceTypeCode;
        com.aliyun.cloudcontrol20220830.models.GetResourceTypeHeaders getResourceTypeHeaders = new com.aliyun.cloudcontrol20220830.models.GetResourceTypeHeaders()
                .setXAcsAcceptLanguage("zh_CH");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        GetResourceTypeResponse resourceTypeWithOptions = client.getResourceTypeWithOptions(requestPath, getResourceTypeHeaders, runtime);
        return resourceTypeWithOptions;
    }
  2. 返回bodyVSwitch的资源元数据,解读资源元数据请参见GetResourceType - 查询资源类型的详情,此次调用返回body如下:

    resourceTypeWithOptions.getBody()

    {
      "requestId": "DF147125-4F39-57EF-8E9C-554FE0E3AB77",
      "resourceType": {
        "product": "VPC",
        "listResponseProperties": [
          "/properties/VSwitchName",
          "/properties/ResourceGroupId",
          "/properties/CidrBlock",
          "/properties/Tags/items",
          "/properties/Description",
          "/properties/VSwitchId",
          "/properties/Status",
          "/properties/Tags/items/properties/TagValue",
          "/properties/Ipv6CidrBlock",
          "/properties/CreateTime",
          "/properties/RouteTableId",
          "/properties/VpcId",
          "/properties/Tags/items/properties/TagKey",
          "/properties/ZoneId",
          "/properties/Tags",
          "/properties/IsDefault",
          "/properties/AvailableIpAddressCount"
        ],
        "updateOnlyProperties": [
          
        ],
        "readOnlyProperties": [
          "/properties/Status",
          "/properties/CreateTime",
          "/properties/AvailableIpAddressCount"
        ],
        "createOnlyProperties": [
          "/properties/VpcIpv6CidrBlock"
        ],
        "listOnlyProperties": [
          
        ],
        "primaryIdentifier": "/properties/VSwitchId",
        "getOnlyProperties": [
          
        ],
        "required": [
          "CidrBlock",
          "VpcId",
          "ZoneId"
        ],
        "publicProperties": [
          "/properties/RouteTableId",
          "/properties/CidrBlock",
          "/properties/Description",
          "/properties/VSwitchId",
          "/properties/AvailableIpAddressCount",
          "/properties/CreateTime",
          "/properties/VSwitchName",
          "/properties/ResourceGroupId",
          "/properties/VpcId",
          "/properties/ZoneId",
          "/properties/Status",
          "/properties/RegionId",
          "/properties/IsDefault",
          "/properties/Ipv6CidrBlock",
          "/properties/Tags",
          "/properties/Tags/items",
          "/properties/Tags/items/properties/TagValue",
          "/properties/Tags/items/properties/TagKey"
        ],
        "filterProperties": [
          "/properties/VSwitchName",
          "/properties/ResourceGroupId",
          "/properties/RouteTableId",
          "/properties/VpcId",
          "/properties/VSwitchId",
          "/properties/ZoneId",
          "/properties/IsDefault"
        ],
        "getResponseProperties": [
          "/properties/ResourceGroupId",
          "/properties/CidrBlock",
          "/properties/VSwitchName",
          "/properties/Tags/items",
          "/properties/Description",
          "/properties/VSwitchId",
          "/properties/Status",
          "/properties/Tags/items/properties/TagValue",
          "/properties/Ipv6CidrBlock",
          "/properties/CreateTime",
          "/properties/RouteTableId",
          "/properties/VpcId",
          "/properties/Tags/items/properties/TagKey",
          "/properties/ZoneId",
          "/properties/Tags",
          "/properties/IsDefault",
          "/properties/AvailableIpAddressCount"
        ],
        "handlers": {
          "get": {
            "permissions": [
              "vpc:DescribeVSwitchAttributes",
              "vpc:ListTagResources"
            ]
          },
          "create": {
            "permissions": [
              "vpc:CreateVSwitch"
            ]
          },
          "update": {
            "permissions": [
              "vpc:TagResources",
              "vpc:UnTagResources",
              "vpc:ModifyVSwitchAttribute"
            ]
          },
          "list": {
            "permissions": [
              "vpc:DescribeVSwitches"
            ]
          },
          "delete": {
            "permissions": [
              "vpc:DeleteVSwitch"
            ]
          }
        },
        "deleteOnlyProperties": [
          
        ],
        "updateTypeProperties": [
          "/properties/Description",
          "/properties/VSwitchName",
          "/properties/Ipv6CidrBlock",
          "/properties/Tags",
          "/properties/Tags/items",
          "/properties/Tags/items/properties/TagValue",
          "/properties/Tags/items/properties/TagKey"
        ],
        "properties": {
          "Status": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "pattern": "",
            "description": "代表资源状态的资源属性字段",
            "readOnly": true,
            "sensitive": false,
            "title": "资源状态",
            "type": "string",
            "updateType": false
          },
          "IsDefault": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "description": "是否是该可用区的默认交换机。",
            "readOnly": true,
            "sensitive": false,
            "title": "是否是该可用区的默认交换机。",
            "type": "boolean",
            "updateType": false
          },
          "RouteTableId": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "pattern": "",
            "description": "交换机关联路由表ID",
            "readOnly": true,
            "sensitive": false,
            "title": "交换机关联路由表ID",
            "type": "string",
            "updateType": false
          },
          "Description": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "交换机的描述信息。",
            "readOnly": false,
            "sensitive": false,
            "title": "交换机的描述信息。",
            "type": "string",
            "updateType": true
          },
          "ResourceGroupId": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "pattern": "",
            "description": "交换机所属的资源组ID。",
            "readOnly": true,
            "sensitive": false,
            "title": "交换机所属的资源组ID。",
            "type": "string",
            "updateType": false
          },
          "ZoneId": {
            "isRequired": true,
            "extMonitorInfo": false,
            "description": "代表zone的资源属性字段",
            "readOnly": false,
            "sensitive": false,
            "title": "可用区ID",
            "type": "string",
            "updateType": false
          },
          "VSwitchId": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "交换机的ID。",
            "readOnly": false,
            "sensitive": false,
            "title": "交换机的ID。",
            "type": "string",
            "updateType": false
          },
          "AvailableIpAddressCount": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "format": "int64",
            "pattern": "",
            "description": "交换机中可用的IP地址数量。",
            "readOnly": true,
            "sensitive": false,
            "title": "交换机中可用的IP地址数量。",
            "type": "integer",
            "updateType": false
          },
          "CreateTime": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "pattern": "",
            "description": "交换机的创建时间。",
            "readOnly": true,
            "sensitive": false,
            "title": "交换机的创建时间。",
            "type": "string",
            "updateType": false
          },
          "CidrBlock": {
            "isRequired": true,
            "extMonitorInfo": false,
            "description": "交换机的网段。",
            "readOnly": false,
            "sensitive": false,
            "title": "交换机的网段。",
            "type": "string",
            "updateType": false
          },
          "VpcId": {
            "isRequired": true,
            "extMonitorInfo": false,
            "description": "VPC的ID。",
            "readOnly": false,
            "sensitive": false,
            "title": "VPC的ID。",
            "type": "string",
            "updateType": false
          },
          "VSwitchName": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "交换机的名称。",
            "readOnly": false,
            "sensitive": false,
            "title": "交换机的名称。",
            "type": "string",
            "updateType": true
          },
          "VpcIpv6CidrBlock": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "pattern": "",
            "description": "VPC的IPv6网段。",
            "operatePrivateType": [
              "create"
            ],
            "readOnly": false,
            "sensitive": false,
            "title": "VPC的IPv6网段。",
            "type": "string",
            "updateType": false
          },
          "RegionId": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "代表region的资源属性字段",
            "readOnly": false,
            "sensitive": false,
            "title": "地域ID",
            "type": "string",
            "updateType": false
          },
          "Ipv6CidrBlock": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "交换机的IPv6网段。",
            "readOnly": false,
            "sensitive": false,
            "title": "交换机的IPv6网段。",
            "type": "string",
            "updateType": true
          },
          "Tags": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "标签结构体",
            "readOnly": false,
            "sensitive": false,
            "title": "标签",
            "type": "array",
            "items": {
              "extMonitorInfo": false,
              "deprecated": false,
              "description": "标签结构体",
              "sensitive": false,
              "title": "标签结构体",
              "type": "object",
              "properties": {
                "TagKey": {
                  "isRequired": false,
                  "extMonitorInfo": false,
                  "description": "标签的键值。",
                  "readOnly": false,
                  "sensitive": false,
                  "title": "标签的键值。",
                  "type": "string",
                  "updateType": true
                },
                "TagValue": {
                  "isRequired": false,
                  "extMonitorInfo": false,
                  "description": "标签的取值。",
                  "readOnly": false,
                  "sensitive": false,
                  "title": "标签的取值。",
                  "type": "string",
                  "updateType": true
                }
              },
              "updateType": true
            },
            "updateType": true
          }
        },
        "sensitiveInfoProperties": [
          
        ],
        "info": {
          "deliveryScope": "zone",
          "chargeType": "free",
          "description": "交换机",
          "title": " 交换机"
        },
        "resourceType": "VSwitch"
      }
    }

创建资源

创建一个交换机,此交换机将用于后续的更新、查询和删除等操作。

  1. 调用CreateResource,根据资源元数据填写请求参数。调用示例如下:

    /**
     * 创建资源
     * @param regionId         地域ID
     * @param productCode      产品code,此例中为"VPC"
     * @param resourceTypeCode 资源类型code,此例中为“VSwitch”
     * @param client           RAM用户client
     * @return resourceWithOptions 返回对象
     */
    public CreateResourceResponse createResource(String regionId, String productCode, String resourceTypeCode, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode;
        // 参数集合
        Map body = new HashMap();
        body.put("VpcId", "vpc-m5esjf3a6b380olet****");  // VPC的ID
        body.put("CidrBlock", "172.16.24.0/24");  // 交换机的网段。
        body.put("ZoneId", "cn-qingdao-b");  // 可用区ID 请参见:https://help.aliyun.com/document_detail/40654.html?spm=5176.28426678.J_HeJR_wZokYt378dwP-lLl.11.51145181tKif1n&scm=20140722.S_help@@%E6%96%87%E6%A1%A3@@40654.S_BB2@bl+RQW@ag0+BB1@ag0+os0.ID_40654-RL_%E5%8F%AF%E7%94%A8%E5%8C%BAID-LOC_search~UND~helpdoc~UND~item-OR_ser-PAR1_213e364e17289863905338434ea19d-V_3-P0_0
        CreateResourceRequest createResourceRequest = new CreateResourceRequest()
                .setRegionId(regionId)
                .setBody(body);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        CreateResourceResponse resourceWithOptions = client.createResourceWithOptions(requestPath, createResourceRequest, headers, runtime);
        return resourceWithOptions;
    }
  2. 此次调用成功,返回statusCode=202,说明为异步操作,需要进一步查询任务状态,记录taskId,用于查询任务,请参见查询任务。同时,记录resourceId,用于后续步骤中的查询资源、更新资源与删除资源等操作。返回body如下:

    resourceWithOptions.getBody()

    {
      "resourceId": "vsw-m5eaburrn73mdpemo****",
      "requestId": "4F7069A4-3CA8-5A48-9D3D-40A1302CBD1B",
      "resourcePath": "VSwitch/vsw-m5eaburrn73mdpemo****",
      "taskId": "task-5057a4fbef2bcffe44d6b3590****"
    }

列举资源

  1. 调用GetResources,列举所有VSwitch资源。调用示例如下:

    /**
     * 列举资源
     * @param regionId         地域ID
     * @param productCode      产品code,此例中为"VPC"
     * @param resourceTypeCode 资源类型code,此例中为“VSwitch”
     * @param client           RAM用户client
     * @return resourcesWithOptions 返回对象
     */
    public GetResourcesResponse getResources(String regionId, String productCode, String resourceTypeCode, Client client) throws Exception {
        String requestPath = "/api/v1/providers/aliyun/products/" + productCode + "/resources/" + resourceTypeCode;
        GetResourcesRequest getResourcesRequest = new GetResourcesRequest()
                .setRegionId(regionId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        GetResourcesResponse resourcesWithOptions = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
        return resourcesWithOptions;
    }
  2. 此次调用成功,返回body如下:

    resourcesWithOptions.getBody()

    {
      "maxResults": 10,
      "nextToken": "2",
      "requestId": "1B5258F0-656F-5005-9FA7-33845FD9FE33",
      "resources": [
       ...,
        {
          "resourceId": "vsw-m5eaburrn73mdpemo****",
          "resourceAttributes": {
            "IsDefault": false,
            "Status": "Available",
            "Description": "",
            "RouteTableId": "vtb-m5epr0god70hpomnn****",
            "ResourceGroupId": "rg-acfmykd63gtpfpa",
            "ZoneId": "cn-qingdao-b",
            "AvailableIpAddressCount": 252,
            "CreateTime": "2024-10-16T05:30:31Z",
            "VSwitchId": "vsw-m5eaburrn73mdpemo****",
            "CidrBlock": "172.16.24.0/24",
            "VpcId": "vpc-m5esjf3a6b380olet****",
            "VSwitchName": "",
            "RegionId": "cn-qingdao",
            "Ipv6CidrBlock": "",
            "Tags": [
              {
                "TagKey": "acs:tag:createdby",
                "TagValue": "sub:206453422934844953:user****"
              }
            ]
          }
        }
      ],
      "totalCount": 29
    }    

更新资源

  1. 调用UpdateResource,更新指定资源。调用示例如下:

    重要

    更新资源时,请谨慎操作,避免误操作影响其他资源。

    /**
     * 更新资源
     * @param regionId         地域ID
     * @param productCode      产品code,此例中为"VPC"
     * @param resourceTypeCode 资源类型code,此例中为“VSwitch”
     * @param resourceId       资源ID,传入此例中创建VSwitch的ID
     * @param client           RAM用户client
     * @return updateResourceResponse 返回对象
     */
    public UpdateResourceResponse updateResource(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        // 参数集合
        Map body = new HashMap();
        body.put("Description", "测试更新");
        UpdateResourceRequest updateResourceRequest = new UpdateResourceRequest()
                .setRegionId(regionId)
                .setBody(body);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        UpdateResourceResponse updateResourceResponse = client.updateResourceWithOptions(requestPath, updateResourceRequest, headers, runtime);
        return updateResourceResponse;
    }
  2. 此次请求返回码statusCode=200,说明请求成功,返回body如下。验证更新结果可执行查询资源操作,请参见查询资源

    updateResourceResponse.getBody()

    {
      "requestId": "C97193DF-FA5A-5B9B-B822-4C128CAC371E"
    }

查询资源

  1. 调用GetResources,查询指定资源。调用示例如下:

    /**
     * 查询资源
     * @param regionId         地域ID
     * @param productCode      产品code,此例中为"VPC"
     * @param resourceTypeCode 资源类型code,此例中为“VSwitch”
     * @param resourceId       资源ID,传入此例中创建VSwitch的ID
     * @param client           RAM用户client
     * @return resourcesWithOptions 返回对象
     */
    public GetResourcesResponse getResources(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        Map<String, String> body = new HashMap<>();
        GetResourcesRequest getResourcesRequest = new GetResourcesRequest()
                .setRegionId(regionId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        GetResourcesResponse resourcesWithOptions = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
        return resourcesWithOptions;
    }
  2. 此次请求成功,返回body如下:

    resourcesWithOptions.getBody()

    {
      "resource": {
        "resourceId": "vsw-m5eaburrn73mdpemo****",
        "resourceAttributes": {
          "IsDefault": false,
          "Status": "Available",
          "Description": "测试更新",
          "RouteTableId": "vtb-m5epr0god70hpomnn****",
          "ResourceGroupId": "rg-acfmykd63gtpfpa",
          "ZoneId": "cn-qingdao-b",
          "AvailableIpAddressCount": 252,
          "CreateTime": "2024-10-16T05:30:31Z",
          "VSwitchId": "vsw-m5eaburrn73mdpemo****",
          "CidrBlock": "172.16.24.0/24",
          "VpcId": "vpc-m5esjf3a6b380olet****",
          "VSwitchName": "",
          "RegionId": "cn-qingdao",
          "Ipv6CidrBlock": "",
          "Tags": [
            {
              "TagKey": "acs:tag:createdby",
              "TagValue": "sub:206453422934844953:user****"
            }
          ]
        }
      },
      "requestId": "B16A5BFC-20FC-5C3A-B640-6CB014328E16"
    }

删除资源

  1. 调用DeleteResource,删除指定资源。调用示例如下:

    重要

    删除资源时,请谨慎操作,避免误操作影响其他资源。

    /**
     * 删除资源
     * @param regionId         地域ID
     * @param productCode      产品code,此例中为"VPC"
     * @param resourceTypeCode 资源类型code,此例中为“VSwitch”
     * @param resourceId       资源ID,传入此例中创建VSwitch的ID
     * @param client           RAM用户client
     * @return deleteResourceResponse 返回对象
     */
    public DeleteResourceResponse deleteResource(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        DeleteResourceRequest deleteResourceRequest = new DeleteResourceRequest()
                .setRegionId(regionId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        DeleteResourceResponse deleteResourceResponse = client.deleteResourceWithOptions(requestPath, deleteResourceRequest, headers, runtime);
        return deleteResourceResponse;
    }
  2. 此次调用成功,返回statusCode=202,说明为异步操作,需要进一步查询任务状态,记录taskId,用于查询任务,请参见查询任务

    deleteResourceResponse.getBody()

    {
      "requestId": "A9BC357C-7ED1-5046-ADDF-4BE17C5A7064",
      "taskId": "task-5057a4fbef2bcffe4562c2954****"
    }

查询任务

查询指定任务的任务状态。

  1. 调用GetTask,查询指定任务的状态。调用示例为查询此教程中的创建VSwitch任务,如下:

    /**
     * 查询异步任务
     * @param taskId 任务Id
     * @param client RAM用户client
     * @return taskWithOptions 返回对象
     */
    public GetTaskResponse getTask(String taskId, Client client) throws Exception {
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        GetTaskResponse taskWithOptions = client.getTaskWithOptions(taskId, headers, runtime);
        return taskWithOptions;
    }
  2. 此次请求成功,返回bodystatus="Succeeded",说明任务处理完成。

    taskWithOptions.getBody()

    {
      "task": {
        "taskAction": "Create",
        "product": "VPC",
        "resourceId": "vsw-m5eaburrn73mdpemo****",
        "createTime": "2024-10-16T05:30:31Z",
        "regionId": "cn-qingdao",
        "resourcePath": "VSwitch/vsw-m5eaburrn73mdpemo****",
        "taskId": "task-5057a4fbef2bcffe44d6b3590****",
        "resourceType": "VSwitch",
        "status": "Succeeded"
      },
      "requestId": "C062613B-8A99-5E69-86DB-26446D1AB845"
    }

完整示例代码

本教程中完整ExampleDemo如下:

ExampleDemo

package org.example;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.util.HashMap;
import java.util.Map;

/**
 * 实现资源管理
 */
public class ExampleDemo {

    /**
     * 初始化账号Client
     * @return Client
     */
    public static Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html。
        Config config = new Config()
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Endpoint 请参考 https://api.aliyun.com/product/cloudcontrol
        config.endpoint = "cloudcontrol.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 列举产品
     * @param client 账号client
     * @return listProductsResponse 返回对象
     */
    public ListProductsResponse listProducts(Client client) throws Exception {
        ListProductsHeaders listProductsHeaders = new ListProductsHeaders();
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        RuntimeOptions runtime = new RuntimeOptions();
        ListProductsResponse listProductsResponse = client.listProductsWithOptions("Aliyun", listProductsRequest, listProductsHeaders, runtime);
        return listProductsResponse;
    }

    /**
     * 列举资源类型
     * @param productCode 产品code,此例中为"VPC"
     * @param client      账号client
     * @return listResourceTypesResponse 返回对象
     */
    public ListResourceTypesResponse listResourceTypes(String productCode, Client client) throws Exception {
        com.aliyun.cloudcontrol20220830.models.ListResourceTypesHeaders listResourceTypesHeaders = new com.aliyun.cloudcontrol20220830.models.ListResourceTypesHeaders();
        com.aliyun.cloudcontrol20220830.models.ListResourceTypesRequest listResourceTypesRequest = new com.aliyun.cloudcontrol20220830.models.ListResourceTypesRequest();
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        ListResourceTypesResponse listResourceTypesResponse = client.listResourceTypesWithOptions("Aliyun", productCode, listResourceTypesRequest, listResourceTypesHeaders, runtime);
        return listResourceTypesResponse;
    }

    /**
     * 创建资源
     * @param regionId         地域ID
     * @param productCode      产品code,此例中为"VPC"
     * @param resourceTypeCode 资源类型code,此例中为“VPC”
     * @param client           RAM用户client
     * @return resourceWithOptions 返回对象
     */
    public CreateResourceResponse createResource(String regionId, String productCode, String resourceTypeCode, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode;
        // 参数集合
        Map body = new HashMap();
        body.put("Description", "测试新建");
        com.aliyun.cloudcontrol20220830.models.CreateResourceRequest createResourceRequest = new com.aliyun.cloudcontrol20220830.models.CreateResourceRequest()
                .setRegionId(regionId).setBody(body);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        CreateResourceResponse resourceWithOptions = client.createResourceWithOptions(requestPath, createResourceRequest, headers, runtime);
        return resourceWithOptions;
    }

    /**
     * 查询异步任务
     * @param taskId 任务Id
     * @param client RAM用户client
     * @return taskWithOptions 返回对象
     */
    public GetTaskResponse getTask(String taskId, Client client) throws Exception {
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        GetTaskResponse taskWithOptions = client.getTaskWithOptions(taskId, headers, runtime);
        return taskWithOptions;
    }

    /**
     * 列举资源
     * @param regionId         地域ID
     * @param productCode      产品code,此例中为"VPC"
     * @param resourceTypeCode 资源类型code,此例中为“VPC”
     * @param client           RAM用户client
     * @return resourcesWithOptions 返回对象
     */
    public GetResourcesResponse getResources(String regionId, String productCode, String resourceTypeCode, Client client) throws Exception {
        String requestPath = "/api/v1/providers/aliyun/products/" + productCode + "/resources/" + resourceTypeCode;
        // 参数集合
        Map body = new HashMap();
        body.put("VpcId", "vpc-m5er4j63farlj8d53****");
        com.aliyun.cloudcontrol20220830.models.GetResourcesRequest getResourcesRequest = new com.aliyun.cloudcontrol20220830.models.GetResourcesRequest()
                .setRegionId(regionId).setFilter(body);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        GetResourcesResponse resourcesWithOptions = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
        return resourcesWithOptions;
    }

    /**
     * 查询资源
     * @param regionId         地域ID
     * @param productCode      产品code,此例中为"VPC"
     * @param resourceTypeCode 资源类型code,此例中为“VPC”
     * @param resourceId       资源ID,传入此例中创建VPC的ID
     * @param client           RAM用户client
     * @return resourcesWithOptions 返回对象
     */
    public GetResourcesResponse getResources(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        com.aliyun.cloudcontrol20220830.models.GetResourcesRequest getResourcesRequest = new com.aliyun.cloudcontrol20220830.models.GetResourcesRequest()
                .setRegionId(regionId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        GetResourcesResponse resourcesWithOptions = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
        return resourcesWithOptions;
    }

    /**
     * 更新资源
     * @param regionId         地域ID
     * @param productCode      产品code,此例中为"VPC"
     * @param resourceTypeCode 资源类型code,此例中为“VPC”
     * @param resourceId       资源ID,传入此例中创建VPC的ID
     * @param client           RAM用户client
     * @return updateResourceResponse 返回对象
     */
    public UpdateResourceResponse updateResource(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        // 参数集合
        Map body = new HashMap();
        body.put("Description", "测试更新");
        com.aliyun.cloudcontrol20220830.models.UpdateResourceRequest updateResourceRequest = new com.aliyun.cloudcontrol20220830.models.UpdateResourceRequest()
                .setRegionId(regionId).setBody(body);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        UpdateResourceResponse updateResourceResponse = client.updateResourceWithOptions(requestPath, updateResourceRequest, headers, runtime);
        return updateResourceResponse;
    }

    /**
     * 删除资源
     * @param regionId         地域ID
     * @param productCode      产品code,此例中为"VPC"
     * @param resourceTypeCode 资源类型code,此例中为“VPC”
     * @param resourceId       资源ID,传入此例中创建VPC的ID
     * @param client           RAM用户client
     * @return deleteResourceResponse 返回对象
     */
    public DeleteResourceResponse deleteResource(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        com.aliyun.cloudcontrol20220830.models.DeleteResourceRequest deleteResourceRequest = new com.aliyun.cloudcontrol20220830.models.DeleteResourceRequest()
                .setRegionId(regionId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        DeleteResourceResponse deleteResourceResponse = client.deleteResourceWithOptions(requestPath, deleteResourceRequest, headers, runtime);
        return deleteResourceResponse;
    }
}

  • 本页导读 (1)
  • 前提条件
  • 初始化项目
  • 查询资源类型的详情
  • 创建资源
  • 列举资源
  • 更新资源
  • 查询资源
  • 删除资源
  • 查询任务
  • 完整示例代码
AI助理

点击开启售前

在线咨询服务

你好,我是AI助理

可以解答问题、推荐解决方案等