Walk through the full lifecycle of resource management—create, read, update, and delete (CRUD)—with the Cloud Control API and Java SDK. This tutorial uses a virtual private cloud (VPC) as an example and covers asynchronous task handling.
Prerequisites
-
You have installed and configured the Java SDK.
-
You are familiar with the concept of resource metadata, which defines the properties and structure of a resource. For more information, see Resource metadata.
-
You understand that the Cloud Control API often uses asynchronous operations. For more information, see Synchronous and asynchronous operations.
Step 1: Get resource type metadata
To manage a resource, you first need to understand its structure by retrieving its metadata. Call the GetResourceType operation to retrieve the metadata. The following example gets the metadata for a 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);
}
}
}
The response returns the complete VPC metadata, including its properties, creation-only parameters (createOnlyProperties), read-only properties (readOnlyProperties), and the permissions required for each action (handlers). You use this information in the following steps.
Example response:
{
"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"
]
}
}
Step 2: Create a resource
Use the CreateResource operation to create a new resource. The request body must contain the properties defined in the resource metadata. This operation is asynchronous and returns a taskId that you use to track its progress.
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);
}
}
}
Step 3: Check the status of an asynchronous task
After you initiate an asynchronous operation like CreateResource or DeleteResource, use the GetTask operation with the returned taskId to check its status.
Example response:
{
"requestId": "D3AA2FD7-CA66-5A6D-B1AE-A5C8C785ADBB",
"resourceId": "vpc-m5eml8m3XXXXXXXX",
"resourcePath": "VPC/vpc-m5eml8m3XXXXXXXX",
"taskId": "task-5057a4fbef2bc1a4XXXXXXXX"
}
Step 4: Read, update, and delete a resource
After you create a resource, you can use its resourceId to read its details, update its properties, or delete it.
Read a single resource (GetResources)
To get the current state of a specific resource, append its resourceId to the request path.
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);
}
}
}
List all resources (GetResources)
To list all resources of a given type in a region, send a request to the base resource path. You can also apply filters.
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);
}
}
}
Update a resource (UpdateResource)
Specify the resourceId in the path and the properties to update in the request body.
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);
}
}
}
Delete a resource (DeleteResource)
Specify the resourceId in the request path. Like creation, deletion is an asynchronous operation that returns a taskId for tracking.
Deletion is an irreversible operation. Proceed with caution.
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);
}
}
}
FAQ
Error: Cannot invoke "com.aliyun.credentials.Client.getCredential()" because "this._credential" is null
This error indicates that the SDK could not find your Alibaba Cloud credentials (AccessKey pair).
Solution:
-
Verify your environment variables. The recommended way to provide credentials is by setting the
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETenvironment variables. Ensure they are set correctly in the terminal or run configuration where you are executing your code.To verify your environment variables, run the command for your operating system:
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%A successful configuration will print your AccessKey ID. If the output is empty, the variable is not set correctly and you will need to configure it again.
For more information, see Configure environment variables in Linux, macOS, and Windows.
-
Check your initialization code. Ensure that your client initialization code is correctly reading the environment variables or is otherwise configured with a valid credential provider.
ImportantDo not hard-code your AccessKey pair directly in your source code, as this is a major security risk.