Todos los productos
Search
Centro de documentos

Cloud Control API:Gestión de recursos con la Cloud Control API y el SDK de Java

Última actualización: Sep 22, 2026

Recorra el ciclo de vida completo de la gestión de recursos (crear, leer, actualizar y eliminar, o CRUD) mediante la Cloud Control API y el SDK de Java. Este tutorial utiliza una virtual private cloud (VPC) como ejemplo y aborda el manejo de tareas asíncronas.

Requisitos previos

  • Instaló y configuró Java SDK.

  • Conoce el concepto de metadatos de recurso, que define las propiedades y la estructura de un recurso. Para obtener más información, consulte Resource metadata.

  • Comprende que la Cloud Control API suele utilizar operaciones asíncronas. Para obtener más información, consulte Synchronous and asynchronous operations.

Paso 1: Obtener los metadatos del tipo de recurso

Para gestionar un recurso, primero debe comprender su estructura mediante la recuperación de sus metadatos. Llame a la operación GetResourceType para recuperarlos. En el siguiente ejemplo se obtienen los metadatos de una VPC.

import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;

public class Sample {

    private static final String PRODUCT_CODE = "VPC"; // Product code, "VPC" in this example
    private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code, "VPC" in this example
    public static void main(String[] args) throws Exception {
        // Initialize the client.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "cloudcontrol.aliyuncs.com";
        com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);

        // Configure runtime options.
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        // Define the request path.
        String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resourceTypes/" + RESOURCE_TYPE_CODE;
        com.aliyun.cloudcontrol20220830.models.GetResourceTypeHeaders getResourceTypeHeaders = new com.aliyun.cloudcontrol20220830.models.GetResourceTypeHeaders()
            .setXAcsAcceptLanguage("en-US"); // Select the language for the response. zh-CN: Chinese (default), en-US: English.
        try {
            // Send the request. 
            GetResourceTypeResponse getResourceTypeResponse = client.getResourceTypeWithOptions(requestPath, getResourceTypeHeaders, runtime);
            // Print the response result.
            System.out.println(new Gson().toJson(getResourceTypeResponse.getBody()));
        } catch (TeaException error) {
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

La respuesta devuelve los metadatos completos de la VPC. Estos incluyen sus propiedades, los parámetros exclusivos de creación (createOnlyProperties), las propiedades de solo lectura (readOnlyProperties) y los permisos obligatorios para cada acción (handlers). Utilizará esta información en los pasos siguientes.

Ejemplo de respuesta:

{
    "requestId": "BE9E0796-DB31-5320-A446-1A2316E7CB92",
    "resourceType": {
        "createOnlyProperties": [
            "/properties/DryRun",
            "/properties/Ipv6Isp",
            "/properties/EnableIpv6"
        ],
        "deleteOnlyProperties": [],
        "filterProperties": [
            "/properties/DhcpOptionsSetId",
            "/properties/ResourceGroupId",
            "/properties/VpcId",
            "/properties/VpcName",
            "/properties/IsDefault"
        ],
        "getOnlyProperties": [
            "/properties/DryRun"
        ],
        "getResponseProperties": [
            "/properties/Ipv6CidrBlocks/items/properties/Ipv6Isp",
            "/properties/RegionId",
            "/properties/VpcName",
            "/properties/ResourceType",
            "/properties/DhcpOptionsSetId",
            "/properties/CreateTime",
            "/properties/Tags/items/properties/TagKey",
            "/properties/SecondaryCidrBlocks/items",
            "/properties/Tags",
            "/properties/IsDefault",
            "/properties/UserCidrs/items",
            "/properties/ResourceGroupId",
            "/properties/CidrBlock",
            "/properties/RouterId",
            "/properties/Tags/items",
            "/properties/Description",
            "/properties/Ipv6CidrBlocks",
            "/properties/SecondaryCidrBlocks",
            "/properties/Status",
            "/properties/VSwitchIds",
            "/properties/Tags/items/properties/TagValue",
            "/properties/Ipv6CidrBlocks/items",
            "/properties/Ipv6CidrBlocks/items/properties/Ipv6CidrBlock",
            "/properties/Ipv6CidrBlock",
            "/properties/ClassicLinkEnabled",
            "/properties/UserCidrs",
            "/properties/VSwitchIds/items",
            "/properties/VpcId"
        ],
        "handlers": {
            "create": {
                "permissions": [
                    "vpc:CreateVpc"
                ]
            },
            "delete": {
                "permissions": [
                    "vpc:DeleteVpc"
                ]
            },
            "get": {
                "permissions": [
                    "vpc:ListTagResources",
                    "vpc:DescribeVpcAttribute",
                    "vpc:DescribeVpcs"
                ]
            },
            "list": {
                "permissions": [
                    "vpc:DescribeVpcs"
                ]
            },
            "update": {
                "permissions": [
                    "vpc:TagResources",
                    "vpc:AssociateVpcCidrBlock",
                    "vpc:MoveResourceGroup",
                    "vpc:ModifyVpcAttribute",
                    "vpc:UnTagResources",
                    "vpc:UnassociateVpcCidrBlock",
                    "vpc:EnableVpcClassicLink",
                    "vpc:DisableVpcClassicLink"
                ]
            }
        },
        "info": {
            "chargeType": "free",
            "deliveryScope": "region",
            "description": "A VPC instance represents a virtual private cloud that you created. You have full control over your VPC, such as specifying the IP address range, configuring route tables, and setting up gateways. You can use Alibaba Cloud resources such as Elastic Compute Service (ECS) instances, ApsaraDB RDS instances, and Server Load Balancer (SLB) instances within your VPC.",
            "title": "Virtual Private Cloud"
        },
        "listOnlyProperties": [
            "/properties/DryRun"
        ],
        "listResponseProperties": [
            "/properties/Ipv6CidrBlocks/items/properties/Ipv6Isp",
            "/properties/RegionId",
            "/properties/VpcName",
            "/properties/DhcpOptionsSetId",
            "/properties/CreateTime",
            "/properties/Tags/items/properties/TagKey",
            "/properties/SecondaryCidrBlocks/items",
            "/properties/Tags",
            "/properties/IsDefault",
            "/properties/UserCidrs/items",
            "/properties/ResourceGroupId",
            "/properties/CidrBlock",
            "/properties/RouterId",
            "/properties/Tags/items",
            "/properties/Description",
            "/properties/Ipv6CidrBlocks",
            "/properties/SecondaryCidrBlocks",
            "/properties/Status",
            "/properties/VSwitchIds",
            "/properties/Tags/items/properties/TagValue",
            "/properties/Ipv6CidrBlocks/items",
            "/properties/Ipv6CidrBlocks/items/properties/Ipv6CidrBlock",
            "/properties/Ipv6CidrBlock",
            "/properties/UserCidrs",
            "/properties/VSwitchIds/items",
            "/properties/VpcId"
        ],
        "primaryIdentifier": "/properties/VpcId",
        "product": "VPC",
        "properties": {
            "Status": {
                "isRequired": false,
                "extMonitorInfo": false,
                "deprecated": false,
                "pattern": "",
                "description": "The status of the VPC.",
                "readOnly": true,
                "sensitive": false,
                "title": "The status of the VPC.",
                "type": "string",
                "updateType": false
            },
            "IsDefault": {
                "isRequired": false,
                "extMonitorInfo": false,
                "deprecated": false,
                "description": "Indicates whether it is the default VPC.",
                "readOnly": false,
                "sensitive": false,
                "title": "Indicates whether it is the default VPC.",
                "type": "boolean",
                "updateType": false
            },
            "Ipv6Isp": {
                "isRequired": false,
                "extMonitorInfo": false,
                "deprecated": false,
                "pattern": "",
                "description": "The IPv6 CIDR block type for the VPC. Valid values:\n\n- **BGP** (default): Alibaba Cloud BGP IPv6.\n- **ChinaMobile**: China Mobile (single line).\n- **ChinaUnicom**: China Unicom (single line).\n- **ChinaTelecom**: China Telecom (single line).\n\n\u003e This field can be set to **ChinaTelecom**, **ChinaUnicom**, or **ChinaMobile** if you are on the single-line bandwidth whitelist.",
                "operatePrivateType": [
                    "create"
                ],
                "readOnly": false,
                "sensitive": false,
                "title": "The IPv6 CIDR block type for the VPC. Valid values:\n\n- **BGP** (default): Alibaba Cloud BGP IPv6.\n- **ChinaMobile**: China Mobile (single line).\n- **ChinaUnicom**: China Unicom (single line).\n- **ChinaTelecom**: China Telecom (single line).\n\n\u003e This field can be set to **ChinaTelecom**, **ChinaUnicom**, or **ChinaMobile** if you are on the single-line bandwidth whitelist.",
                "type": "string",
                "updateType": false
            },
            "Description": {
                "isRequired": false,
                "extMonitorInfo": false,
                "description": "The description of the VPC.",
                "readOnly": false,
                "sensitive": false,
                "title": "The description of the VPC.",
                "type": "string",
                "updateType": true
            },
            "ResourceGroupId": {
                "isRequired": false,
                "extMonitorInfo": false,
                "description": "The ID of the resource group.",
                "readOnly": false,
                "sensitive": false,
                "title": "The ID of the resource group.",
                "type": "string",
                "updateType": true
            },
            "ClassicLinkEnabled": {
                "isRequired": false,
                "extMonitorInfo": false,
                "deprecated": false,
                "description": "The status of the ClassicLink feature.",
                "readOnly": false,
                "sensitive": false,
                "title": "The status of the ClassicLink feature.",
                "type": "boolean",
                "updateType": true
            },
            "SecondaryCidrBlocks": {
                "isRequired": false,
                "extMonitorInfo": false,
                "description": "The secondary CIDR block information.",
                "readOnly": false,
                "sensitive": false,
                "title": "The secondary CIDR block information.",
                "type": "array",
                "items": {
                    "description": "The secondary CIDR block of the VPC.",
                    "title": "The secondary CIDR block of the VPC.",
                    "type": "string",
                    "updateType": true
                },
                "updateType": true
            },
            "VSwitchIds": {
                "isRequired": false,
                "extMonitorInfo": false,
                "deprecated": false,
                "description": "The list of VSwitches in the VPC.",
                "readOnly": true,
                "sensitive": false,
                "title": "The list of VSwitches in the VPC.",
                "type": "array",
                "items": {
                    "extMonitorInfo": false,
                    "deprecated": false,
                    "pattern": "",
                    "description": "The list of VSwitches in the VPC.",
                    "readOnly": true,
                    "sensitive": false,
                    "title": "The list of VSwitches in the VPC.",
                    "type": "string",
                    "updateType": false
                },
                "updateType": false
            },
            "CreateTime": {
                "isRequired": false,
                "extMonitorInfo": false,
                "deprecated": false,
                "pattern": "",
                "description": "The time when the VPC was created.",
                "readOnly": true,
                "sensitive": false,
                "title": "The time when the VPC was created.",
                "type": "string",
                "updateType": false
            },
            "DryRun": {
                "isRequired": false,
                "extMonitorInfo": false,
                "deprecated": false,
                "description": "Indicates whether to perform a dry run. Valid values:\n- **true**: Sends a check request without creating the VPC. The system checks for required parameters, request format, and service limits. If the check fails, an error is returned. If the check passes, the `DryRunOperation` error code is returned.\n- **false** (default): Sends a normal request, and if the check passes, returns a 2xx HTTP status code and creates the VPC.",
                "operatePrivateType": [
                    "create",
                    "list",
                    "get"
                ],
                "readOnly": false,
                "sensitive": false,
                "title": "Indicates whether to perform a dry run. Valid values:\n- **true**: Sends a check request without creating the VPC. The system checks for required parameters, request format, and service limits. If the check fails, an error is returned. If the check passes, the `DryRunOperation` error code is returned.\n- **false** (default): Sends a normal request, and if the check passes, returns a 2xx HTTP status code and creates the VPC.",
                "type": "boolean",
                "updateType": false
            },
            "RouterId": {
                "isRequired": false,
                "extMonitorInfo": false,
                "deprecated": false,
                "pattern": "",
                "description": "The router ID of the VPC.",
                "readOnly": true,
                "sensitive": false,
                "title": "The router ID of the VPC.",
                "type": "string",
                "updateType": false
            },
            "CidrBlock": {
                "isRequired": false,
                "extMonitorInfo": false,
                "description": "The private CIDR block of the VPC.",
                "readOnly": false,
                "sensitive": false,
                "title": "The private CIDR block of the VPC.",
                "type": "string",
                "updateType": true
            },
            "UserCidrs": {
                "isRequired": false,
                "extMonitorInfo": false,
                "description": "The CIDR block of the user-side network. To specify multiple CIDR blocks, separate them with commas. Up to 3 CIDR blocks are supported.",
                "readOnly": false,
                "sensitive": false,
                "title": "The CIDR block of the user-side network. To specify multiple CIDR blocks, separate them with commas. Up to 3 CIDR blocks are supported.",
                "type": "array",
                "items": {
                    "isRequired": false,
                    "extMonitorInfo": false,
                    "deprecated": false,
                    "pattern": "",
                    "description": "The CIDR block of the user-side network. To specify multiple CIDR blocks, separate them with commas. Up to 3 CIDR blocks are supported.",
                    "sensitive": false,
                    "title": "The CIDR block of the user-side network. To specify multiple CIDR blocks, separate them with commas. Up to 3 CIDR blocks are supported.",
                    "type": "string",
                    "updateType": false
                },
                "updateType": false
            },
            "EnableIpv6": {
                "isRequired": false,
                "extMonitorInfo": false,
                "deprecated": false,
                "description": "Indicates whether to enable the IPv6 CIDR block. Valid values:\n\n- **false** (default): No.\n- **true**: Yes.",
                "operatePrivateType": [
                    "create"
                ],
                "readOnly": false,
                "sensitive": false,
                "title": "Indicates whether to enable the IPv6 CIDR block. Valid values:\n\n- **false** (default): No.\n- **true**: Yes.",
                "type": "boolean",
                "updateType": false
            },
            "DhcpOptionsSetId": {
                "isRequired": false,
                "extMonitorInfo": false,
                "description": "The ID of the DHCP options set.",
                "readOnly": false,
                "sensitive": false,
                "title": "The ID of the DHCP options set.",
                "type": "string",
                "updateType": false
            },
            "VpcId": {
                "isRequired": false,
                "extMonitorInfo": false,
                "description": "The ID of the VPC.",
                "readOnly": false,
                "sensitive": false,
                "title": "The ID of the VPC.",
                "type": "string",
                "updateType": false
            },
            "VpcName": {
                "isRequired": false,
                "extMonitorInfo": false,
                "description": "The name of the VPC.",
                "readOnly": false,
                "sensitive": false,
                "title": "The name of the VPC.",
                "type": "string",
                "updateType": true
            },
            "RegionId": {
                "isRequired": true,
                "extMonitorInfo": false,
                "description": "The region where the VPC is located.",
                "readOnly": false,
                "sensitive": false,
                "title": "The region where the VPC is located.",
                "type": "string",
                "updateType": false
            },
            "Ipv6CidrBlocks": {
                "isRequired": false,
                "extMonitorInfo": false,
                "deprecated": false,
                "description": "The IPv6 CIDR block information of the VPC.",
                "readOnly": true,
                "sensitive": false,
                "title": "The IPv6 CIDR block information of the VPC.",
                "type": "array",
                "items": {
                    "extMonitorInfo": false,
                    "deprecated": false,
                    "description": "The IPv6 CIDR block information of the VPC.",
                    "readOnly": true,
                    "sensitive": false,
                    "title": "The IPv6 CIDR block information of the VPC.",
                    "type": "object",
                    "properties": {
                        "Ipv6Isp": {
                            "isRequired": false,
                            "extMonitorInfo": false,
                            "deprecated": false,
                            "pattern": "",
                            "description": "The IPv6 CIDR block type of the VPC. Valid values:\n\n- **BGP**: Alibaba Cloud BGP IPv6.\n- **ChinaMobile**: China Mobile (single line).\n- **ChinaUnicom**: China Unicom (single line).\n- **ChinaTelecom**: China Telecom (single line).\n\n\u003e This field can be set to **ChinaTelecom**, **ChinaUnicom**, and **ChinaMobile** if you are on the single-line bandwidth whitelist.",
                            "readOnly": true,
                            "sensitive": false,
                            "title": "The IPv6 CIDR block type of the VPC. Valid values:\n\n- **BGP**: Alibaba Cloud BGP IPv6.\n- **ChinaMobile**: China Mobile (single line).\n- **ChinaUnicom**: China Unicom (single line).\n- **ChinaTelecom**: China Telecom (single line).\n\n\u003e This field can be set to **ChinaTelecom**, **ChinaUnicom**, and **ChinaMobile** if you are on the single-line bandwidth whitelist.",
                            "type": "string",
                            "updateType": false
                        },
                        "Ipv6CidrBlock": {
                            "isRequired": false,
                            "extMonitorInfo": false,
                            "deprecated": false,
                            "pattern": "",
                            "description": "The IPv6 CIDR block of the VPC.",
                            "readOnly": true,
                            "sensitive": false,
                            "title": "The IPv6 CIDR block of the VPC.",
                            "type": "string",
                            "updateType": false
                        }
                    },
                    "updateType": false
                },
                "updateType": false
            },
            "Ipv6CidrBlock": {
                "isRequired": false,
                "extMonitorInfo": false,
                "description": "The IPv6 address.",
                "readOnly": false,
                "sensitive": false,
                "title": "The IPv6 address.",
                "type": "string",
                "updateType": true
            },
            "Tags": {
                "isRequired": false,
                "extMonitorInfo": false,
                "description": "The tags of the VPC.",
                "readOnly": false,
                "sensitive": false,
                "title": "The tags of the VPC.",
                "type": "array",
                "items": {
                    "extMonitorInfo": false,
                    "deprecated": false,
                    "description": "The tags of the VPC.",
                    "sensitive": false,
                    "title": "The tags of the VPC.",
                    "type": "object",
                    "properties": {
                        "TagKey": {
                            "isRequired": false,
                            "extMonitorInfo": false,
                            "description": "The key of the tag.",
                            "readOnly": false,
                            "sensitive": false,
                            "title": "The key of the tag.",
                            "type": "string",
                            "updateType": true
                        },
                        "TagValue": {
                            "isRequired": false,
                            "extMonitorInfo": false,
                            "description": "The value of the tag.",
                            "readOnly": false,
                            "sensitive": false,
                            "title": "The value of the tag.",
                            "type": "string",
                            "updateType": true
                        }
                    },
                    "updateType": false
                },
                "updateType": true
            }
        },
        "publicProperties": [
            "/properties/RouterId",
            "/properties/VpcId",
            "/properties/DhcpOptionsSetId",
            "/properties/ResourceGroupId",
            "/properties/UserCidrs",
            "/properties/UserCidrs/items",
            "/properties/VSwitchIds",
            "/properties/RegionId",
            "/properties/Ipv6CidrBlocks",
            "/properties/VSwitchIds/items",
            "/properties/Tags",
            "/properties/Tags/items",
            "/properties/Ipv6CidrBlocks/items",
            "/properties/CidrBlock",
            "/properties/Ipv6CidrBlocks/items/properties/Ipv6Isp",
            "/properties/Tags/items/properties/TagKey",
            "/properties/Ipv6CidrBlocks/items/properties/Ipv6CidrBlock",
            "/properties/Status",
            "/properties/Tags/items/properties/TagValue",
            "/properties/CreateTime",
            "/properties/Ipv6CidrBlock",
            "/properties/Description",
            "/properties/VpcName",
            "/properties/ClassicLinkEnabled",
            "/properties/IsDefault",
            "/properties/SecondaryCidrBlocks",
            "/properties/SecondaryCidrBlocks/items"
        ],
        "readOnlyProperties": [
            "/properties/Ipv6CidrBlocks/items/properties/Ipv6Isp",
            "/properties/CreateTime",
            "/properties/RouterId",
            "/properties/Ipv6CidrBlocks",
            "/properties/Status",
            "/properties/VSwitchIds",
            "/properties/Ipv6CidrBlocks/items",
            "/properties/Ipv6CidrBlocks/items/properties/Ipv6CidrBlock",
            "/properties/VSwitchIds/items"
        ],
        "required": [
            "RegionId"
        ],
        "resourceType": "VPC",
        "sensitiveInfoProperties": [],
        "updateOnlyProperties": [],
        "updateTypeProperties": [
            "/properties/ResourceGroupId",
            "/properties/Tags",
            "/properties/CidrBlock",
            "/properties/Tags/items/properties/TagKey",
            "/properties/Tags/items/properties/TagValue",
            "/properties/Ipv6CidrBlock",
            "/properties/Description",
            "/properties/VpcName",
            "/properties/ClassicLinkEnabled",
            "/properties/SecondaryCidrBlocks",
            "/properties/SecondaryCidrBlocks/items"
        ]
    }
}

Paso 2: Crear un recurso

Utilice la operación CreateResource para crear un recurso nuevo. El cuerpo de la solicitud debe contener las propiedades definidas en los metadatos del recurso. Esta operación es asíncrona y devuelve un taskId que le permite dar seguimiento a su progreso.

import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;

public class Sample {

    private static final String PRODUCT_CODE = "VPC"; // Product code. In this example, "VPC".
    private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code. In this example, "VPC".
    public static void main(String[] args) throws Exception {
        // Initialize the client.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "cloudcontrol.aliyuncs.com";
        com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        // The headers parameter allows you to customize request headers, override default values, or add extra information.
        java.util.Map < String, String > headers = new java.util.HashMap < > ();
        // Request path.
        String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resources/" + RESOURCE_TYPE_CODE;
        java.util.Map < String, Object > body = TeaConverter.buildMap(
            new TeaPair("IsDefault", true), // Specifies whether this is the default VPC.
            new TeaPair("Description", "This is a test VPC"), // Description.
            new TeaPair("VpcName", "VPC_Test"), // VPC name.
            new TeaPair("Tags", java.util.Arrays.asList(
                TeaConverter.buildMap(
                    new TeaPair("TagKey", "key"),
                    new TeaPair("TagValue", "value")
                )
            )), // VPC tags.
            new TeaPair("EnableIpv6", false), // Specifies whether to enable the IPv6 CIDR block.
            new TeaPair("DryRun", false) // Specifies whether to perform only a dry run.
        );
        // Configure request parameters.
        com.aliyun.cloudcontrol20220830.models.CreateResourceRequest createResourceRequest = new com.aliyun.cloudcontrol20220830.models.CreateResourceRequest()
            .setRegionId("cn-qingdao") // Region ID.
            .setBody(body);
        try {

            // Initiate the request.
            CreateResourceResponse createResourceResponse = client.createResourceWithOptions(requestPath, createResourceRequest, headers, runtime);
            // Print the result.
            System.out.println(new Gson().toJson(createResourceResponse.getBody()));
        } catch (TeaException error) {
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Paso 3: Comprobar el estado de una tarea asíncrona

Después de iniciar una operación asíncrona, como CreateResource o DeleteResource, utilice la operación GetTask junto con el taskId devuelto para comprobar su estado.

Ejemplo de respuesta:

{
    "requestId": "D3AA2FD7-CA66-5A6D-B1AE-A5C8C785ADBB",
    "resourceId": "vpc-m5eml8m3XXXXXXXX",
    "resourcePath": "VPC/vpc-m5eml8m3XXXXXXXX",
    "taskId": "task-5057a4fbef2bc1a4XXXXXXXX"
}

Paso 4: Leer, actualizar y eliminar un recurso

Una vez creado el recurso, utilice su resourceId para leer sus detalles, actualizar sus propiedades o eliminarlo.

Leer un recurso individual (GetResources)

Para obtener el estado actual de un recurso específico, agregue su resourceId a la ruta de la solicitud.

import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;

public class Sample {

    private static final String PRODUCT_CODE = "VPC"; // Product code. In this example, "VPC".
    private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code. In this example, "VPC".
    public static void main(String[] args) throws Exception {
        //      Initialize the client.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "cloudcontrol.aliyuncs.com"; // Endpoint.
        com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        //        // Ignore SSL certificate verification.
        //        runtime.ignoreSSL = true;
        //        // Proxy configuration.
        //        runtime.httpProxy = "http://127.0.0.1:9898";
        //        runtime.httpsProxy = "http://user:password@127.0.0.1:8989";
        //        runtime.noProxy = "127.0.0.1,localhost";
        //        // Connection timeout.
        //        runtime.connectTimeout = 5000;
        //        // Read timeout.
        //        runtime.readTimeout = 10000;
        //        // Enable automatic retry.
        //        runtime.autoretry = true;
        //        // Set the maximum number of retries.
        //        runtime.maxAttempts = 3;
        //     The headers parameter allows you to customize request headers, override default values, or add extra information.
        java.util.Map < String, String > headers = new java.util.HashMap < > ();

        String resourceId = "vrt-m5eyitbd6XXXXXXXX";
        String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resources/" + RESOURCE_TYPE_CODE + "/" + resourceId;
        // Request parameters.
        com.aliyun.cloudcontrol20220830.models.GetResourcesRequest getResourcesRequest = new com.aliyun.cloudcontrol20220830.models.GetResourcesRequest()
            .setRegionId("cn-qingdao");
        try {
            // Initiate the request.
            GetResourcesResponse getResourcesResponse = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
            // Print the response.
            System.out.println(new Gson().toJson(getResourcesResponse.getBody()));
        } catch (TeaException error) {
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Listar todos los recursos (GetResources)

Para listar todos los recursos de un tipo determinado en una región, envíe una solicitud a la ruta base del recurso. También puede aplicar filtros.

import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;

public class Sample {

    private static final String PRODUCT_CODE = "VPC"; // Product code. In this example, "VPC".
    private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code. In this example, "VPC".
    public static void main(String[] args) throws Exception {
        //      Initialize the client.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "cloudcontrol.aliyuncs.com";
        com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        //        The headers parameter allows you to customize request headers, override default values, or add extra information.
        java.util.Map < String, String > headers = new java.util.HashMap < > ();
        //        headers.put("x-acs-action", "GetResource"); // Set the API operation name.
        //       Request path.
        String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resources/" + RESOURCE_TYPE_CODE;
        // Filter conditions (optional).
        // java.util.Map < String, Object > filter = TeaConverter.buildMap(
        //    new TeaPair("IsDefault", true), // Specifies whether this is the default VPC.
        //    new TeaPair("ResourceGroupId", "<YOUR_RESOURCEGROUPID>"), // Resource group ID.
        //    new TeaPair("DhcpOptionsSetId", "<YOUR_DHCPOPTIONSSETID>"), // DHCP options set ID.
        //    new TeaPair("VpcId", "<YOUR_VPCID>"), // VPC ID.
        //    new TeaPair("VpcName", "<YOUR_VPCNAME>") // VPC name.
        // );
        com.aliyun.cloudcontrol20220830.models.GetResourcesRequest getResourcesRequest = new com.aliyun.cloudcontrol20220830.models.GetResourcesRequest()
            //            .setFilter(filter)
            .setRegionId("cn-qingdao");

        try {
            GetResourcesResponse getResourcesResponse = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
            System.out.println(new Gson().toJson(getResourcesResponse.getBody()));
        } catch (TeaException error) {
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Actualizar un recurso (UpdateResource)

Especifique el resourceId en la ruta y las propiedades que desea actualizar en el cuerpo de la solicitud.

import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;

public class Sample {

    private static final String PRODUCT_CODE = "VPC"; // Product code. In this example, "VPC".
    private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code. In this example, "VPC".
    public static void main(String[] args) throws Exception {
        //      Initialize the client.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "cloudcontrol.aliyuncs.com";
        com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        //          The headers parameter allows you to customize request headers, override default values, or add extra information.
        java.util.Map < String, String > headers = new java.util.HashMap < > ();

        // Resource ID.
        String resourceId = "vpc-m5eml8m3XXXXXXXX";
        // Request path.
        String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resources/" + RESOURCE_TYPE_CODE +"/" + resourceId;
        java.util.Map < String, Object > body = TeaConverter.buildMap(
            new TeaPair("Description", "Updated test VPC description"), // Update the resource description.
            new TeaPair("VpcName", "UpdateVpc"), // Update the resource name.
            new TeaPair("Tags", java.util.Arrays.asList(
                TeaConverter.buildMap(
                    new TeaPair("TagKey", "key1"),
                    new TeaPair("TagValue", "value1")
                )
            )) // Update the resource tags.
        );
        com.aliyun.cloudcontrol20220830.models.UpdateResourceRequest updateResourceRequest = new com.aliyun.cloudcontrol20220830.models.UpdateResourceRequest()
            .setRegionId("cn-qingdao") // Region.
            .setBody(body);
        try {
            // Initiate the request.
            UpdateResourceResponse updateResourceResponse = client.updateResourceWithOptions(requestPath, updateResourceRequest, headers, runtime);
            System.out.println(new Gson().toJson(updateResourceResponse.getBody()) + new Gson().toJson(updateResourceResponse.statusCode));
        } catch (TeaException error) {
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Eliminar un recurso (DeleteResource)

Especifique el resourceId en la ruta de la solicitud. Al igual que la creación, la eliminación es una operación asíncrona que devuelve un taskId para darle seguimiento.

Importante

La eliminación es una operación irreversible. Proceda con precaución.

import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;

public class Sample {

    private static final String PRODUCT_CODE = "VPC"; // Product code. In this example, "VPC".
    private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code. In this example, "VPC".
    public static void main(String[] args) throws Exception {
        //      Initialize the client.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "cloudcontrol.aliyuncs.com";
        com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        //          The headers parameter allows you to customize request headers, override default values, or add extra information.
        java.util.Map < String, String > headers = new java.util.HashMap < > ();
        // Resource ID.
        String resourceId = "vpc-m5ei5XXXXXXXX";
        // Request path.
        String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resources/" + RESOURCE_TYPE_CODE + "/" + resourceId;
        // Request parameters.
        com.aliyun.cloudcontrol20220830.models.DeleteResourceRequest deleteResourceRequest = new com.aliyun.cloudcontrol20220830.models.DeleteResourceRequest()
            .setRegionId("cn-qingdao");
        try {
            // Initiate the request.
            DeleteResourceResponse deleteResourceResponse = client.deleteResourceWithOptions(requestPath, deleteResourceRequest, headers, runtime);
            // Print the result.
            System.out.println(new Gson().toJson(deleteResourceResponse.getBody()));
        } catch (TeaException error) {
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Preguntas frecuentes

Error: Cannot invoke "com.aliyun.credentials.Client.getCredential()" because "this._credential" is null

Este error indica que el SDK no encontró sus credenciales de Alibaba Cloud (el par de AccessKey).

Solución:

  1. Compruebe sus variables de entorno. La forma recomendada de proporcionar las credenciales es establecer las variables de entorno ALIBABA_CLOUD_ACCESS_KEY_ID y ALIBABA_CLOUD_ACCESS_KEY_SECRET. Asegúrese de que estén configuradas correctamente en la terminal o en la configuración de ejecución donde ejecute su código.

    Para comprobar sus variables de entorno, ejecute el comando correspondiente a su sistema operativo:

    Linux/macOS

    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

    Windows

    echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
    echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

    Si la configuración es correcta, se mostrará su AccessKey ID. Si la salida está vacía, la variable no se estableció bien y deberá configurarla de nuevo.

    Para obtener más información, consulte Configure environment variables on Linux, macOS, and Windows.

  2. Revise su código de inicialización. Asegúrese de que el código con el que inicializa el cliente lea correctamente las variables de entorno o esté configurado con un proveedor de credenciales válido.

    Importante

    No incluya su par de AccessKey directamente en el código fuente, ya que esto representa un riesgo de seguridad importante.