Alibaba Cloud provides various APIs and SDKs that allow you to programmatically create and manage Elastic Compute Service (ECS) instances, improving business efficiency and implementing system automation. This topic describes how to use ECS SDK 2.0 for Java to create an ECS instance, run a command on the ECS instance by calling a Cloud Assistant API operation, and release resources.
Preparations
Create an AccessKey pair for a Resource Access Management (RAM) user. An Alibaba Cloud account has all permissions on resources. If the AccessKey pair of your Alibaba Cloud account is leaked, your resources are exposed to great risks. We recommend that you use the AccessKey pair of a RAM user. For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair.
Grant the required permissions on ECS and Virtual Private Cloud (VPC) resources to the RAM user that you want to use. The sample code provided in this topic creates resources, such as an ECS instance, a VPC, and a vSwitch. To grant the permissions required to run the sample code, we recommend that you attach the policies described in the following table to the RAM user.
Alibaba Cloud service
Policy
VPC
AliyunVPCFullAccess
ECS
AliyunECSFullAccess
Configure the AccessKey pair of the RAM user that you want to use in environment variables. The sample code provided in this topic reads the AccessKey pair from the environment variables and uses the AccessKey pair as credentials to access Alibaba Cloud services. For information about how to configure an AccessKey pair in environment variables, see Configure environment variables in Linux, macOS, and Windows.
Obtain ECS SDK 2.0 for Java and VPC SDK 2.0 for Java. In this topic, ECS SDK 2.0 for Java and VPC SDK 2.0 for Java are installed by adding Maven dependencies. For information about other installation methods, see Install ECS SDK for Java and Install VPC SDK for Java.
Create an ECS instance
Multiple parameters, such as vSwitch ID, security group ID, and image ID, are required to create an ECS instance. You can pass in the IDs of existing resources or call API operations to create new resources.
Create a VPC
A VPC is a dedicated private network in the cloud. You can configure and manage VPCs as logically isolated networks in the public cloud.
API operation
Parameter
Description and example
RegionId
The ID of the region in which to create the VPC. Example: cn-hangzhou.
CidrBlock
The CIDR block of the VPC. Example: 192.168.0.0/16.
Query the details of the VPC.
After you call the CreateVpc operation to create a VPC, you can call an API operation to query the status of the VPC. If the VPC is in the Available state, call API operations to perform subsequent steps.
API operation
Parameter
Description and example
RegionId
The region ID of the VPC. Example: cn-hangzhou.
VpcId
The ID of the VPC. Example: vpc-bp1aag0sb9s4i92i3****.
Create a vSwitch
A vSwitch is a network switching device in a VPC, which supports the functionality of a physical switch. It serves to enable communication between virtual machines (VMs) and between VMs and physical networks.
API operation
Parameter
Description and example
RegionId
The ID of the region in which to create the vSwitch. Example: cn-hangzhou.
ZoneId
The ID of the zone in which to create the vSwitch. Example: cn-hangzhou-i.
VpcId
The ID of the VPC in which you want to create the vSwitch. Example: vpc-bp1aag0sb9s4i92i3****.
CidrBlock
The CIDR block of the vSwitch. Example: 192.168.0.0/24.
Create a security group.
A security group acts as a virtual firewall that controls inbound and outbound traffic for ECS instances.
API operation
Parameter
Description and example
RegionId
The ID of the region in which to create the security group. Example: cn-hangzhou.
VpcId
The ID of the VPC in which to create the security group. Example: vpc-bp1aag0sb9s4i92i3****.
Create an inbound rule in the security group.
API operation
Parameter
Description and example
RegionId
The region ID of the security group. Example: cn-hangzhou.
SecurityGroupId
The ID of the security group. Example: sg-bp1esyhwfbqeyudt****.
IpProtocol
The protocol. Example: tcp.
SourceCidrIp
The source IPv4 CIDR block. Example: 0.0.0.0/0.
PortRange
The port range. Examples:
Linux instances: 22/22.
Windows instances: 3389/3389.
Create an SSH key pair.
Alibaba Cloud provides the secure and convenient SSH key pair-based authentication method for logon to ECS instances. The key pairs are used for authentication and encrypted communication over the SSH protocol. SSH key pairs allow you to remotely log on to ECS instances in a password-free manner.
API operation
Parameter
Description and example
RegionId
The region ID of the instance. Example: cn-hangzhou.
KeyPairName
The name of the SSH key pair. Example: sdk-key-pair.
Create an ECS instance.
ECS provides high-performance, secure, and low-cost compute capacity and is suitable for various scenarios such as website hosting, application development, and data processing. With ECS, you can quickly deploy and run applications and flexibly adjust resources in response to business changes.
API operation
Parameter
Description and example
RegionId
The ID of the region in which to create the ECS instance. Example: cn-hangzhou.
ImageId
The ID of the image. We recommend that you select the Alibaba Cloud Linux image whose ID is aliyun_3_x64_20G_scc_alibase_20220225.vhd.
InstanceType
The instance type. Example: ecs.e-c1m2.xlarge.
SecurityGroupId
The ID of the security group. Example: sg-bp1esyhwfbqeyudt****.
VSwitchId
The ID of the vSwitch. Example: vsw-bp1nzprm8h7mmnl8t****.
InstanceName
The ECS instance name. Example: sdk-test.
InstanceChargeType
The billing method of the ECS instance. To create a pay-as-you-go instance, set this parameter to PostPaid.
NoteMake sure that your account balance is sufficient.
KeyPairName
The name of the SSH key pair. Example: sdk-key-pair.
SystemDisk.Category
The disk category of the system disk. Example: cloud_essd.
Query the status of the ECS instance.
After you call the RunInstances operation to create an ECS instance, the ECS instance requires approximately 10 seconds to initialize. You can log on to the ECS instance by using a connection method to perform operations and deploy applications only when the instance is in the Running state. You can call the API operation that is described in the following table to query the status of the ECS instance.
API operation
Parameter
Description and example
RegionId
The region ID of the ECS instance. Example: cn-hangzhou.
InstanceId
The IDs of ECS instances. Example: ["i-bp17f3kzgtzzj91r****"].
Complete sample code:
import com.aliyun.ecs20140526.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.vpc20160428.models.CreateVSwitchRequest;
import com.aliyun.vpc20160428.models.CreateVSwitchResponse;
import com.aliyun.vpc20160428.models.CreateVpcRequest;
import com.aliyun.vpc20160428.models.CreateVpcResponse;
import com.aliyun.vpc20160428.models.DescribeVpcsRequest;
import java.util.ArrayList;
import java.util.List;
public class EcsDemo {
public static void main(String[] args) {
String vpcId = null;
String vSwitchId = null;
String securityGroupId = null;
String instanceId = null;
com.aliyun.vpc20160428.Client vpcClient = null;
com.aliyun.ecs20140526.Client ecsClient = null;
try {
vpcClient = createVpcClient();
ecsClient = createEcsClient();
// Create a VPC.
vpcId = createVpc(vpcClient);
System.out.println("VPC create success, vpcId :" + vpcId);
// Perform subsequent steps only when the VPC is in the Available state.
while (true) {
String status = describeVpc(vpcId, vpcClient);
if ("Available".equals(status)) {
break;
}
}
// Create a vSwitch.
vSwitchId = CreateVSwitch(vpcId, vpcClient);
System.out.println("VSwitch create success, vSwitchId :" + vSwitchId);
// Create a security group.
securityGroupId = createSecurityGroup(vpcId, ecsClient);
System.out.println("SecurityGroup create success, securityGroupId :" + securityGroupId);
// Create an inbound rule in the security group.
authorizeSecurityGroup(securityGroupId, ecsClient);
// Create an SSH key pair. You must store the SSH key pair for later logon to the ECS instance.
CreateKeyPairResponse keyPair = createKeyPair(ecsClient);
System.out.println("KeyPair create success, keyPairName :" + keyPair.body.keyPairName);
// Create an ECS instance. If the ECS instance is in the Running state, the instance is running.
instanceId = createInstance(ecsClient, vSwitchId, securityGroupId);
System.out.println("ECS create success, instanceId :" + instanceId);
while (true) {
List<String> instanceIds = new ArrayList<>();
instanceIds.add(instanceId);
DescribeInstanceStatusResponse describeInstanceStatus = describeInstanceStatus(instanceIds, ecsClient);
List<DescribeInstanceStatusResponseBody.DescribeInstanceStatusResponseBodyInstanceStatusesInstanceStatus> instanceStatusList = describeInstanceStatus.body.instanceStatuses.instanceStatus;
if (instanceStatusList != null && !instanceStatusList.isEmpty()) {
String status = instanceStatusList.get(0).status;
if ("Running".equals(status)) {
break;
}
}
}
} catch (Exception e) {
// If some resources are created but other resources fail to be created, you must add mechanisms, such logging, rollback mechanisms, and compensation mechanisms, to properly address the issue.
System.out.println(e.getMessage());
}
}
public static class Constants {
// The name.
public static final String NAME = "sdk-test";
// The region.
public static final String REGION_ID = "cn-hangzhou";
// The zone.
public static final String ZONE_ID = "cn-hangzhou-i";
// The VPC and vSwitch that you created.
public static final String CIDR_BLOCK_VPC = "192.168.0.0/16";
public static final String CIDR_BLOCK_VSWITCH = "192.168.0.0/24";
// The image.
public static final String IMAGE_ID = "aliyun_3_x64_20G_scc_alibase_20220225.vhd";
// The instance type.
public static final String INSTANCE_TYPE = "ecs.e-c1m2.xlarge";
// The disk category.
public static final String SYSTEM_DISK_CATEGORY = "cloud_essd";
// The name of the SSH key pair.
public static final String KEY_PAIR_NAME = "sdk-key-pair";
// The endpoints of the services.
public static final class ENDPOINT {
public static final String VPC = "vpc.cn-hangzhou.aliyuncs.com";
public static final String ECS = "ecs.cn-hangzhou.aliyuncs.com";
}
// The billing method of the instance.
public static final class INSTANCE_CHARGE_TYPE {
// Subscription
public static final String PRE_PAID = "PrePaid";
// Pay-as-you-go
public static final String POST_PAID = "PostPaid";
}
}
public static com.aliyun.vpc20160428.Client createVpcClient() throws Exception {
Config config = new Config();
config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = Constants.ENDPOINT.VPC;
return new com.aliyun.vpc20160428.Client(config);
}
public static com.aliyun.ecs20140526.Client createEcsClient() throws Exception {
Config config = new Config();
config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = Constants.ENDPOINT.ECS;
return new com.aliyun.ecs20140526.Client(config);
}
/**
* Create a VPC.
* This method calls an Alibaba Cloud VPC API operation to create a VPC and returns the ID of the new VPC.
*
* @param vpcClient The VPC client.
* @return The ID of the new VPC.
*/
public static String createVpc(com.aliyun.vpc20160428.Client vpcClient) {
try {
CreateVpcRequest createVpcRequest = new CreateVpcRequest()
.setRegionId(Constants.REGION_ID)
.setCidrBlock(Constants.CIDR_BLOCK_VPC)
.setVpcName(Constants.NAME);
CreateVpcResponse vpc = vpcClient.createVpc(createVpcRequest);
return vpc.body.vpcId;
} catch (Exception e) {
throw new RuntimeException("createVpc failed: " + e.getMessage());
}
}
/**
* Create a vSwitch.
* This method calls an Alibaba Cloud VPC client to create a vSwitch. The method sends a request that includes the required parameters of the vSwitch, such as the region ID, zone ID,
* CIDR block, VPC ID, and vSwitch name, and returns the ID of the new vSwitch.
*
* @param vpcId The ID of the VPC in which you want to create the vSwitch.
* @param vpcClient The VPC client.
* @return The ID of the new vSwitch.
*/
public static String CreateVSwitch(String vpcId, com.aliyun.vpc20160428.Client vpcClient) {
try {
CreateVSwitchRequest createVSwitchRequest = new CreateVSwitchRequest()
.setRegionId(Constants.REGION_ID)
.setZoneId(Constants.ZONE_ID)
.setCidrBlock(Constants.CIDR_BLOCK_VSWITCH)
.setVpcId(vpcId)
.setVSwitchName(Constants.NAME);
CreateVSwitchResponse vSwitch = vpcClient.createVSwitch(createVSwitchRequest);
return vSwitch.body.vSwitchId;
} catch (Exception e) {
throw new RuntimeException("CreateVSwitch failed: " + e.getMessage());
}
}
/**
* Create a security group.
*
* @param vpcId The ID of the VPC in which you want to create the security group.
* @param ecsClient The ECS client.
* @return The ID of the new security group.
*/
public static String createSecurityGroup(String vpcId, com.aliyun.ecs20140526.Client ecsClient) {
try {
CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest()
.setRegionId(Constants.REGION_ID)
.setVpcId(vpcId)
.setSecurityGroupName(Constants.NAME);
CreateSecurityGroupResponse securityGroup = ecsClient.createSecurityGroup(createSecurityGroupRequest);
return securityGroup.body.securityGroupId;
} catch (Exception e) {
throw new RuntimeException("createSecurityGroup failed: " + e.getMessage());
}
}
/**
* Create an inbound rule in the security group.
* For example, create an inbound rule that allows TCP access on SSH port 22 from anywhere (0.0.0.0/0).
*
* @param securityGroupId The ID of the security group in which you want to create an inbound rule.
* @param ecsClient The ECS client.
*/
public static void authorizeSecurityGroup(String securityGroupId, com.aliyun.ecs20140526.Client ecsClient) {
try {
AuthorizeSecurityGroupRequest.AuthorizeSecurityGroupRequestPermissions permission = new AuthorizeSecurityGroupRequest.AuthorizeSecurityGroupRequestPermissions()
.setIpProtocol("tcp")
.setPortRange("22/22")
.setSourceCidrIp("0.0.0.0/0");
List<AuthorizeSecurityGroupRequest.AuthorizeSecurityGroupRequestPermissions> permissions = new ArrayList<>();
permissions.add(permission);
AuthorizeSecurityGroupRequest authorizeSecurityGroupRequest = new AuthorizeSecurityGroupRequest()
.setRegionId(Constants.REGION_ID)
.setSecurityGroupId(securityGroupId)
.setPermissions(permissions);
ecsClient.authorizeSecurityGroup(authorizeSecurityGroupRequest);
} catch (Exception e) {
throw new RuntimeException("authorizeSecurityGroup failed: " + e.getMessage());
}
}
/**
* Create an ECS instance.
*
* @param ecsClient The ECS client.
* @param vSwitchId The ID of the vSwitch.
* @param securityGroupId The ID of the security group.
* @return The ID of the new ECS instance.
*/
public static String createInstance(com.aliyun.ecs20140526.Client ecsClient, String vSwitchId, String securityGroupId) {
try {
RunInstancesRequest.RunInstancesRequestSystemDisk systemDisk = new RunInstancesRequest.RunInstancesRequestSystemDisk()
.setCategory(Constants.SYSTEM_DISK_CATEGORY);
RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
.setRegionId(Constants.REGION_ID)
.setImageId(Constants.IMAGE_ID)
.setInstanceType(Constants.INSTANCE_TYPE)
.setSecurityGroupId(securityGroupId)
.setVSwitchId(vSwitchId)
.setInstanceChargeType(Constants.INSTANCE_CHARGE_TYPE.POST_PAID)
.setInstanceName(Constants.NAME)
.setInternetMaxBandwidthOut(1)
.setSystemDisk(systemDisk)
.setKeyPairName(Constants.KEY_PAIR_NAME);
RunInstancesResponse resp = ecsClient.runInstances(runInstancesRequest);
return resp.body.getInstanceIdSets().getInstanceIdSet().get(0);
} catch (Exception e) {
throw new RuntimeException("createInstance failed: " + e.getMessage());
}
}
/**
* Create an SSH key pair.
*
* @param ecsClient The ECS client.
* @return The response object for creating an SSH key pair.
*/
public static CreateKeyPairResponse createKeyPair(com.aliyun.ecs20140526.Client ecsClient) {
try {
// Create a request object for creating an SSH key pair and specify a region ID, a key pair name, and a resource group ID in the request object.
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
.setRegionId(Constants.REGION_ID)
.setKeyPairName(Constants.KEY_PAIR_NAME);
// Use the ECS client to send the request to create an SSH key pair and return a response object.
return ecsClient.createKeyPair(createKeyPairRequest);
} catch (Exception e) {
// Throw a runtime exception that includes an error message if the SSH key pair fails to be created.
throw new RuntimeException("createKeyPair failed: " + e.getMessage());
}
}
/**
* Query the status of the VPC.
*
* @param vpcId The VPC ID.
* @param vpcClient The VPC client.
* @return The status of the VPC.
*/
public static String describeVpc(String vpcId, com.aliyun.vpc20160428.Client vpcClient) {
try {
DescribeVpcsRequest request = new DescribeVpcsRequest()
.setRegionId(Constants.REGION_ID)
.setVpcId(vpcId);
return vpcClient.describeVpcs(request).body.vpcs.getVpc().get(0).status;
} catch (Exception e) {
// Throw a custom exception if an exception occurs.
throw new RuntimeException("describeVpc failed: " + e.getMessage());
}
}
/**
* Query the status of ECS instances.
*
* @param instanceIds The IDs of ECS instances.
* @param ecsClient The ECS client.
* @return The response object for querying the status of ECS instances.
*/
public static DescribeInstanceStatusResponse describeInstanceStatus(List<String> instanceIds, com.aliyun.ecs20140526.Client ecsClient) {
try {
DescribeInstanceStatusRequest request = new DescribeInstanceStatusRequest()
.setRegionId(Constants.REGION_ID)
.setInstanceId(instanceIds);
return ecsClient.describeInstanceStatus(request);
} catch (Exception e) {
throw new RuntimeException("describeInstanceStatus failed: " + e.getMessage());
}
}
}
Perform O&M without the need to log on to ECS instances
Cloud Assistant is a native automated O&M tool developed for ECS. Cloud Assistant allows you to batch run commands, such as shell, PowerShell, and batch commands, to execute various tasks on ECS instances in a password-free manner without the need to log on to the instances or use jump servers. You can use Cloud Assistant to run automated O&M scripts, poll processes, install or uninstall software, start or stop services, and install patches or security updates. For more information, see Overview.
For example, you can call the RunCommand operation to install Java and Tomcat on ECS instances by running a Cloud Assistant command.
API operation | Parameter | Description and example |
RegionId | The ID of the region. Example: cn-hangzhou. | |
Type | The language type of the command. Example: RunShellScript. | |
CommandContent | The command content. Example:
| |
Timeout | Optional. The timeout period for the command execution. Unit: seconds. Example: 60. | |
InstanceId | The IDs of ECS instances. Example: ["i-bp17f3kzgtzzj91r****"]. |
Complete sample code:
import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.RunCommandRequest;
import com.aliyun.ecs20140526.models.RunCommandResponse;
import com.aliyun.teaopenapi.models.Config;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
public class CloudAssistant {
public static void main(String[] args) throws Exception {
Client ecsClient = createEcsClient();
List<String> instanceIds = new ArrayList<>();
instanceIds.add("i-bp17f3kzgtzzj91r****");
String commandContent = "#!/bin/bash\n" +
"if cat /etc/issue|grep -i Ubuntu ; then\n" +
"\tsudo apt-get update\n" +
"\tsudo apt-get install -y default-jdk\n" +
"\tsudo apt-get install -y tomcat9\n" +
"else\n" +
" yum install -y java\n" +
"\tyum install -y tomcat\n" +
"fi";
System.out.println("commandContent: " + commandContent);
runCommand(commandContent, instanceIds, ecsClient);
}
public static class Constants {
// The region.
public static final String REGION_ID = "cn-hangzhou";
// The endpoints of the services.
public static final class ENDPOINT {
public static final String VPC = "vpc.cn-hangzhou.aliyuncs.com";
public static final String ECS = "ecs.cn-hangzhou.aliyuncs.com";
}
// The type of the command.
public static final class COMMAND_TYPE {
// Shell command, applicable to Windows instances.
public static final String RUN_SHELL_SCRIPT = "RunShellScript";
// Batch command, applicable to Windows instances.
public static final String RUN_BAT_SCRIPT = "RunBatScript";
// PowerShell command, applicable to Windows instances.
public static final String RUN_POWERSHELL_SCRIPT = "RunPowerShellScript";
}
}
public static com.aliyun.ecs20140526.Client createEcsClient() throws Exception {
Config config = new Config();
config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = Constants.ENDPOINT.ECS;
return new com.aliyun.ecs20140526.Client(config);
}
public static void runCommand(String commandContent, List<String> instanceIds, com.aliyun.ecs20140526.Client ecsClient) {
try {
RunCommandRequest request = new RunCommandRequest();
request.setRegionId(Constants.REGION_ID);
// RunShellScript: shell command, applicable to Linux instances.
request.setType(Constants.COMMAND_TYPE.RUN_SHELL_SCRIPT);
request.setCommandContent(commandContent);
request.setInstanceId(instanceIds);
request.setTimeout(60L);
RunCommandResponse runCommandResponse = ecsClient.runCommand(request);
System.out.println(new Gson().toJson(runCommandResponse));
} catch (Exception e) {
throw new RuntimeException("runCommand failed:" + e);
}
}
}
Release resources
If you no longer require the resources that you created, call API operations to release the resources.
Call API operations to release resources based on your business requirements. In the following examples, all resources that are created in the preceding section are released.
Release an ECS instance.
API operation
Parameter
Description and example
RegionId
The region ID of the ECS instance. Example: cn-hangzhou.
InstanceId
The ID of the ECS instance. Example: i-bp17f3kzgtzzj91r****.
Delete an SSH key pair.
API operation
Parameter
Description and example
RegionId
The region ID of the SSH key pair. Example: cn-hangzhou.
KeyPairNames
The name of the SSH key pair. Example: ["sdk-key-pair"].
Delete a security group.
API operation
Parameter
Description and example
RegionId
The region ID of the security group. Example: cn-hangzhou.
SecurityGroupId
The ID of the security group. Example: sg-bp1esyhwfbqeyudt****.
Delete a vSwitch.
API operation
Parameter
Description and example
RegionId
The region ID of the vSwitch. Example: cn-hangzhou.
VSwitchId
The ID of the vSwitch. Example: vsw-bp1nzprm8h7mmnl8t****.
Delete a VPC.
API operation
Parameter
Description and example
RegionId
The region ID of the VPC. Example: cn-hangzhou.
VpcId
The ID of the VPC. Example: vpc-bp1aag0sb9s4i92i3****.
Sample code:
import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.vpc20160428.models.DeleteVSwitchRequest;
import com.aliyun.vpc20160428.models.DeleteVpcRequest;
import com.google.gson.Gson;
import java.util.Collections;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DeleteResources {
public static void main(String[] args) {
String vpcId = "vpc-bp1aag0sb9s4i92i3****";
String vSwitchId = "vsw-bp1nzprm8h7mmnl8t****";
String securityGroupId = "sg-bp1esyhwfbqeyudt****";
String instanceId = "i-bp17f3kzgtzzj91r****";
String keyPairName = "sdk-key-pair";
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
try {
com.aliyun.ecs20140526.Client ecsClient = createEcsClient();
com.aliyun.vpc20160428.Client vpcClient = createVpcClient();
// Delete an ECS instance.
executorService.schedule(() -> deleteInstance(instanceId, ecsClient), 1, TimeUnit.SECONDS);
// Delete an SSH key pair.
executorService.schedule(() -> deleteKeyPairs(keyPairName, ecsClient), 1, TimeUnit.SECONDS);
// Delete a security group.
executorService.schedule(() -> deleteSecurityGroup(securityGroupId, ecsClient), 60, TimeUnit.SECONDS);
// Delete a vSwitch.
executorService.schedule(() -> deleteVSwitch(vSwitchId, vpcClient), 60, TimeUnit.SECONDS);
// Delete a VPC.
executorService.schedule(() -> deleteVpc(vpcId, vpcClient), 65, TimeUnit.SECONDS);
} catch (Exception e) {
System.err.println("An error occurred: " + e.getMessage());
// Handle exceptions. Some resources may fail to be deleted. Add mechanisms to properly handle the deletion failures.
} finally {
executorService.shutdown();
}
}
public static class Constants {
// The endpoints of the services.
public static final class ENDPOINT {
public static final String VPC = "vpc.cn-hangzhou.aliyuncs.com";
public static final String ECS = "ecs.cn-hangzhou.aliyuncs.com";
}
// The region.
public static final String REGION_ID = "cn-hangzhou";
}
public static com.aliyun.vpc20160428.Client createVpcClient() throws Exception {
Config config = new Config();
config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = Constants.ENDPOINT.VPC;
return new com.aliyun.vpc20160428.Client(config);
}
public static com.aliyun.ecs20140526.Client createEcsClient() throws Exception {
Config config = new Config();
config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = Constants.ENDPOINT.ECS;
return new com.aliyun.ecs20140526.Client(config);
}
/**
* Delete a VPC.
*
* @param vpcId The ID of the VPC that you want to delete.
* @param vpcClient The VPC client.
*/
public static void deleteVpc(String vpcId, com.aliyun.vpc20160428.Client vpcClient) {
try {
System.out.println("VPC is deleting, please wait...");
DeleteVpcRequest deleteVpcRequest = new DeleteVpcRequest()
.setRegionId(Constants.REGION_ID)
.setVpcId(vpcId);
vpcClient.deleteVpc(deleteVpcRequest);
} catch (Exception e) {
throw new RuntimeException("DeleteVpc failed: " + e.getMessage());
}
}
/**
* Delete a vSwitch.
*
* @param vSwitchId The ID of the vSwitch.
* @param vpcClient The VPC client.
*/
public static void deleteVSwitch(String vSwitchId, com.aliyun.vpc20160428.Client vpcClient) {
System.out.println("VSwitch is deleting, please wait...");
try {
DeleteVSwitchRequest deleteVSwitchRequest = new DeleteVSwitchRequest()
.setRegionId(Constants.REGION_ID)
.setVSwitchId(vSwitchId);
vpcClient.deleteVSwitch(deleteVSwitchRequest);
} catch (Exception e) {
throw new RuntimeException("DeleteVSwitch failed: " + e.getMessage());
}
}
/**
* Delete a security group.
*
* @param securityGroupId The ID of the security group that you want to delete.
* @param ecsClient The ECS client.
*/
public static void deleteSecurityGroup(String securityGroupId, Client ecsClient) {
System.out.println("SecurityGroup is deleting, please wait...");
try {
DeleteSecurityGroupRequest deleteSecurityGroupRequest = new DeleteSecurityGroupRequest()
.setRegionId(Constants.REGION_ID)
.setSecurityGroupId(securityGroupId);
ecsClient.deleteSecurityGroup(deleteSecurityGroupRequest);
} catch (Exception e) {
throw new RuntimeException("DeleteSecurityGroup failed: " + e.getMessage());
}
}
/**
* Delete an ECS instance.
*
* @param instanceId The ID of the ECS instance that you want to delete.
* @param ecsClient The ECS client.
*/
public static void deleteInstance(String instanceId, Client ecsClient) {
System.out.println("ECS instance is deleting, please wait...");
try {
DeleteInstanceRequest request = new DeleteInstanceRequest()
.setForce(true)
.setInstanceId(instanceId);
ecsClient.deleteInstance(request);
} catch (Exception e) {
throw new RuntimeException("DeleteInstance failed: " + e.getMessage());
}
}
/**
* Delete an SSH key pair.
*
* @param keyPairName The name of the SSH key pair.
* @param ecsClient The ECS client.
*/
public static void deleteKeyPairs(String keyPairName, Client ecsClient) {
System.out.println("KeyPair is deleting, please wait...");
try {
// Create a request to delete an SSH key pair and specify the region ID and the name of the SSH key pair in the request.
DeleteKeyPairsRequest deleteKeyPairsRequest = new DeleteKeyPairsRequest()
.setRegionId(Constants.REGION_ID)
.setKeyPairNames(new Gson().toJson(Collections.singletonList(keyPairName)));
ecsClient.deleteKeyPairs(deleteKeyPairsRequest);
} catch (Exception e) {
// Throw an exception that includes an error message if the SSH key pair fails to be deleted.
throw new RuntimeException("DeleteKeyPairs failed: " + e.getMessage());
}
}
}