Percorra todo o ciclo de vida do gerenciamento de recursos — criação, leitura, atualização e exclusão (CRUD) — com a Cloud Control API e o Java SDK. Este tutorial usa uma Virtual Private Cloud (VPC) como exemplo e aborda o tratamento de tarefas assíncronas.
Pré-requisitos
Instale e configure o Java SDK.
Conheça o conceito de metadados de recurso, que definem as propriedades e a estrutura de um recurso. Para mais informações, consulte Metadados de recurso.
Entenda que a Cloud Control API frequentemente utiliza operações assíncronas. Para mais informações, consulte Operações síncronas e assíncronas.
Etapa 1: Obter metadados do tipo de recurso
Para gerenciar um recurso, compreenda sua estrutura recuperando os metadados correspondentes. Chame a operação GetResourceType para obter esses dados. O exemplo a seguir recupera os metadados de uma 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);
}
}
}
A resposta retorna os metadados completos da VPC, incluindo propriedades, parâmetros exclusivos de criação (createOnlyProperties), propriedades somente leitura (readOnlyProperties) e permissões necessárias para cada ação (handlers). Utilize essas informações nas etapas seguintes.
Exemplo de resposta:
{
"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"
]
}
}
Etapa 2: Criar um recurso
Use a operação CreateResource para criar um novo recurso. O corpo da requisição deve conter as propriedades definidas nos metadados do recurso. Essa operação é assíncrona e retorna um taskId para acompanhamento do progresso.
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);
}
}
}
Etapa 3: Verificar o status de uma tarefa assíncrona
Após iniciar uma operação assíncrona como CreateResource ou DeleteResource, use a operação GetTask com o taskId retornado para verificar o status.
Exemplo de resposta:
{
"requestId": "D3AA2FD7-CA66-5A6D-B1AE-A5C8C785ADBB",
"resourceId": "vpc-m5eml8m3XXXXXXXX",
"resourcePath": "VPC/vpc-m5eml8m3XXXXXXXX",
"taskId": "task-5057a4fbef2bc1a4XXXXXXXX"
}
Etapa 4: Ler, atualizar e excluir um recurso
Após criar um recurso, use o resourceId para ler detalhes, atualizar propriedades ou excluí-lo.
Ler um único recurso (GetResources)
Para obter o estado atual de um recurso específico, anexe o resourceId ao caminho da requisição.
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 os recursos (GetResources)
Para listar todos os recursos de um determinado tipo em uma região, envie uma requisição para o caminho base do recurso. Também é possível 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);
}
}
}
Atualizar um recurso (UpdateResource)
Especifique o resourceId no caminho e as propriedades a atualizar no corpo da requisição.
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);
}
}
}
Excluir um recurso (DeleteResource)
Especifique o resourceId no caminho da requisição. Assim como a criação, a exclusão é uma operação assíncrona que retorna um taskId para rastreamento.
A exclusão é uma operação irreversível. Prossiga com cautela.
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);
}
}
}
Perguntas frequentes
Erro: Cannot invoke "com.aliyun.credentials.Client.getCredential()" because "this._credential" is null
Esse erro indica que o SDK não encontrou suas credenciais do Alibaba Cloud (par AccessKey).
Solução:
-
Verifique suas variáveis de ambiente. A forma recomendada de fornecer credenciais é definir as variáveis de ambiente
ALIBABA_CLOUD_ACCESS_KEY_IDeALIBABA_CLOUD_ACCESS_KEY_SECRET. Certifique-se de que estejam configuradas corretamente no terminal ou na configuração de execução onde o código está sendo executado.Para verificar suas variáveis de ambiente, execute o comando correspondente ao seu sistema operacional:
Linux/macOS
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRETWindows
echo %ALIBABA_CLOUD_ACCESS_KEY_ID% echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%Uma configuração bem-sucedida exibirá seu AccessKey ID. Se a saída estiver vazia, a variável não foi definida corretamente e será necessário configurá-la novamente.
Para mais informações, consulte Configurar variáveis de ambiente no Linux, macOS e Windows.
-
Revise seu código de inicialização. Garanta que o código de inicialização do cliente leia corretamente as variáveis de ambiente ou esteja configurado com um provedor de credenciais válido.
ImportanteNão codifique seu par AccessKey diretamente no código-fonte, pois isso representa um grande risco de segurança.