Alibaba Cloud Elastic Compute Service (ECS) provides various APIs and software development kits (SDKs) that you can use to programmatically create and manage ECS instances. This improves business efficiency and enables system automation. This topic describes how to use the V2.0 Java SDK to create an ECS instance, run a script using Cloud Assistant, and release resources.
Preparations
-
An AccessKey of an Alibaba Cloud account provides full permissions for all resources. A leaked AccessKey poses a high security risk. We recommend that you use the AccessKey of a Resource Access Management (RAM) user with the minimum required permissions. For more information, see Create an AccessKey.
-
Grant the RAM user permissions to manage Elastic Compute Service (ECS) and virtual private cloud (VPC) resources. The sample code in this topic creates resources such as instances, VPCs, and vSwitches. Grant the following permissions:
Cloud Products
Grant permissions
Virtual Private Cloud (VPC)
This example uses the system policy: AliyunVPCFullAccess
Elastic Compute Service (ECS)
This example uses the system policy: AliyunECSFullAccess
-
The sample code in this topic reads the AccessKey from system environment variables to use as credentials for accessing Alibaba Cloud services. For more information, see Configure environment variables on Linux, macOS, and Windows.
-
Obtain the ECS SDK and VPC SDK. This topic describes how to install the SDKs by adding Maven dependencies. For more information about other installation methods, see Install the ECS Java SDK and Install the VPC Java SDK.
Create an ECS instance
When you create an ECS instance, you must specify many required parameters, such as the vSwitch ID, security group, and image. You can use the IDs of existing resources or call the following OpenAPI operations to create the resources.
-
Create a VPC
A virtual private cloud (VPC) is a private network on the cloud that lets you configure and manage a logically isolated network area.
API
Parameter
Example value
RegionId
Region: cn-hangzhou
CidrBlock
VPC CIDR block: 192.168.0.0/16
-
Query VPC information
After you call CreateVpc, the VPC requires time to be configured. Call this OpenAPI operation to query the VPC status. Do not call subsequent OpenAPI operations until the VPC status changes to Available.
API
Parameter
Example value
RegionId
Region: cn-hangzhou
VpcId
VPC ID: vpc-bp1aag0sb9s4i92i3****
-
Create a vSwitch
A vSwitch is a network switch device used in a virtualization environment. It simulates the functions of a physical switch to enable communication between virtual machines (VMs) and between VMs and the physical network.
API
Parameter
Example value
RegionId
Region: cn-hangzhou
ZoneId
Zone: cn-hangzhou-i
VpcId
VPC ID: vpc-bp1aag0sb9s4i92i3****
CidrBlock
vSwitch CIDR block: 192.168.0.0/24
-
Create a security group
A security group is a virtual firewall that controls inbound and outbound traffic for ECS instances.
API
Parameter
Example value
RegionId
Region: cn-hangzhou
VpcId
VPC ID: vpc-bp1aag0sb9s4i92i3****
-
Add a rule to the security group
API
Parameter
Example value
RegionId
Region: cn-hangzhou
SecurityGroupId
Security group ID: sg-bp1esyhwfbqeyudt****
IpProtocol
Protocol: tcp
SourceCidrIp
Source CIDR block: 0.0.0.0/0
PortRange
Port range:
-
For a Linux instance: 22/22
-
For a Windows instance: 3389/3389
-
-
Create an SSH key pair
An Alibaba Cloud SSH key pair is a secure and convenient logon authentication method that is used for identity verification and encrypted communication in the Secure Shell Protocol (SSH). You can use an SSH key pair for passwordless remote logon.
API
Parameter
Example value
RegionId
Region: cn-hangzhou
KeyPairName
Key pair name: sdk-key-pair
-
Create an ECS instance
ECS lets you quickly deploy and run applications, flexibly scale resources to meet business changes, and benefit from high-performance, secure, and cost-effective computing. ECS is suitable for various scenarios, such as website hosting, application development, and data processing.
API
Parameter
Example value
RegionId
Region: cn-hangzhou
ImageId
Image: Use the Alibaba Cloud Linux image aliyun_3_x64_20G_scc_alibase_20220225.vhd.
InstanceType
Instance type: ecs.e-c1m2.xlarge.
SecurityGroupId
Security group ID: sg-bp1esyhwfbqeyudt****
VSwitchId
vSwitch ID: vsw-bp1nzprm8h7mmnl8t****
InstanceName
Instance name: sdk-test
InstanceChargeType
Billing method: The instance is billed on a pay-as-you-go basis (PostPaid).
NoteMake sure that your account balance is sufficient for the payment.
KeyPairName
Key pair name: sdk-key-pair
SystemDisk.Category
System disk type: cloud_essd
-
Query the ECS instance status
After you call RunInstances, the ECS instance requires time to start. You can perform operations, such as remote connections and application deployments, only after the instance enters the Running state. You can call this OpenAPI operation to query the status of the ECS instance.
API
Parameter
Example value
RegionId
Region: cn-hangzhou
InstanceId
Instance IDs: ["i-bp17f3kzgtzzj91r****"]
The following code provides a complete example:
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);
// Proceed to the next step only after 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);
// Add an inbound rule to the security group.
authorizeSecurityGroup(securityGroupId, ecsClient);
// Create a key pair. Note: Save the key pair information to log on to the ECS instance.
CreateKeyPairResponse keyPair = createKeyPair(ecsClient);
System.out.println("KeyPair create success, keyPairName :" + keyPair.body.keyPairName);
// Create an instance. The instance is running when its status 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 others fail, add a proper handling mechanism, such as logging, rollback, or compensation.
System.out.println(e.getMessage());
}
}
public static class Constants {
// Name
public static final String NAME = "sdk-test";
// Region
public static final String REGION_ID = "cn-hangzhou";
// Zone
public static final String ZONE_ID = "cn-hangzhou-i";
// The CIDR blocks of the VPC and vSwitch to be 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";
// Image
public static final String IMAGE_ID = "aliyun_3_x64_20G_scc_alibase_20220225.vhd";
// Instance type
public static final String INSTANCE_TYPE = "ecs.e-c1m2.xlarge";
// Disk type
public static final String SYSTEM_DISK_CATEGORY = "cloud_essd";
// Key pair name
public static final String KEY_PAIR_NAME = "sdk-key-pair";
// Endpoint
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";
}
// Billing method
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);
}
/**
* Creates a virtual private cloud (VPC) network.
* This method calls the API of the VPC service to create a VPC network and returns the ID of the new VPC.
*
* @param vpcClient The VPC client.
* @return Returns 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());
}
}
/**
* Creates a vSwitch.
* This method creates a new vSwitch using the Alibaba Cloud VPC client. It configures the required request parameters, such as the region ID, zone ID,
* CIDR block, VPC ID, and vSwitch name, then sends the request and returns the ID of the new vSwitch.
*
* @param vpcId The ID of the VPC in which to create the vSwitch.
* @param vpcClient The VPC client.
* @return Returns 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());
}
}
/**
* Creates a security group.
*
* @param vpcId The ID of the VPC.
* @param ecsClient The ECS client.
* @return The ID of the created 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());
}
}
/**
* Authorizes a security group rule to allow specific inbound traffic.
* For example, allow access from any IP address (0.0.0.0/0) over TCP on port 22 (SSH).
*
* @param securityGroupId The ID of the security group for which to authorize the 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());
}
}
/**
* Creates an ECS instance.
*
* @param ecsClient The ECS client.
* @param vSwitchId The vSwitch ID.
* @param securityGroupId The security group ID.
* @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());
}
}
/**
* Creates a key pair using the specified security group ID.
*
* @param ecsClient The ECS client.
* @return Returns the response object for creating the key pair.
*/
public static CreateKeyPairResponse createKeyPair(com.aliyun.ecs20140526.Client ecsClient) {
try {
// Create a request object to create a key pair, and set the region ID and key pair name.
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
.setRegionId(Constants.REGION_ID)
.setKeyPairName(Constants.KEY_PAIR_NAME);
// Send the request to create the key pair using the ECS client and return the response object.
return ecsClient.createKeyPair(createKeyPairRequest);
} catch (Exception e) {
// If the key pair fails to be created, throw a runtime exception that contains the error message.
throw new RuntimeException("createKeyPair failed: " + e.getMessage());
}
}
/**
* Queries the VPC status.
*
* @param vpcId The ID of the VPC.
* @param vpcClient The VPC client.
* @return Returns 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) {
// If an exception occurs, throw a custom exception.
throw new RuntimeException("describeVpc failed: " + e.getMessage());
}
}
/**
* Queries ECS instance information based on a list of instance IDs.
*
* @param instanceIds A list of instance IDs.
* @param ecsClient The ECS client.
* @return Returns the response object that contains the instance status information.
*/
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());
}
}
}
Passwordless O&M
You can use Cloud Assistant, a native automated O&M tool provided by Elastic Compute Service (ECS), to run batch commands (such as Shell, PowerShell, and Batch) without requiring passwords, logons, or jump servers. This lets you perform tasks such as running automated O&M scripts, polling processes, installing or uninstalling software, starting or stopping services, and installing patches or security updates. For more information, see Overview of Cloud Assistant.
For example, to install Java and Tomcat on an ECS instance, you can call the RunCommand operation:
|
API |
Parameter |
Example value |
|
RegionId |
Region: cn-hangzhou |
|
|
Type |
Language type of the O&M command: RunShellScript |
|
|
CommandContent |
Command content:
|
|
|
Timeout |
Optional. The timeout period for running the command. Unit: seconds. Example: 60 |
|
|
InstanceId |
ECS instance IDs: ["i-bp17f3kzgtzzj91r****"] |
The following code provides a complete example:
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 {
// Region
public static final String REGION_ID = "cn-hangzhou";
// Endpoint
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";
}
// Command type
public static final class COMMAND_TYPE {
// A shell command for a Linux instance.
public static final String RUN_SHELL_SCRIPT = "RunShellScript";
// A batch command for a Windows instance.
public static final String RUN_BAT_SCRIPT = "RunBatScript";
// A PowerShell command for a Windows instance.
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 specifies a shell command for a Linux instance.
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
When you no longer need the resources, you can call the following OpenAPI operations to release them.
Call the appropriate OpenAPI operations to release resources as needed. This example releases all resources created in the preceding steps.
-
Release the ECS instance
API
Parameter
Example value
RegionId
Region: cn-hangzhou
InstanceId
Instance ID: i-bp17f3kzgtzzj91r****
-
Delete the SSH key pair
API
Parameter
Example value
RegionId
Region: cn-hangzhou
KeyPairNames
SSH key pair name: ["sdk-key-pair"]
-
Delete the security group
API
Parameter
Example value
RegionId
Region: cn-hangzhou
SecurityGroupId
Security group ID: sg-bp1esyhwfbqeyudt****
-
Delete the vSwitch
API
Parameter
Example value
RegionId
Region: cn-hangzhou
VSwitchId
vSwitch ID: vsw-bp1nzprm8h7mmnl8t****
-
Delete the VPC
API
Parameter
Example value
RegionId
Region: cn-hangzhou
VpcId
VPC ID: vpc-bp1aag0sb9s4i92i3****
The following code provides an example:
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 the ECS instance.
executorService.schedule(() -> deleteInstance(instanceId, ecsClient), 1, TimeUnit.SECONDS);
// Delete the key pair.
executorService.schedule(() -> deleteKeyPairs(keyPairName, ecsClient), 1, TimeUnit.SECONDS);
// Delete the security group.
executorService.schedule(() -> deleteSecurityGroup(securityGroupId, ecsClient), 60, TimeUnit.SECONDS);
// Delete the vSwitch.
executorService.schedule(() -> deleteVSwitch(vSwitchId, vpcClient), 60, TimeUnit.SECONDS);
// Delete the VPC.
executorService.schedule(() -> deleteVpc(vpcId, vpcClient), 65, TimeUnit.SECONDS);
} catch (Exception e) {
System.err.println("An error occurred: " + e.getMessage());
// Handle exceptions. Releasing an instance takes time. Some resources may be deleted while others are not. Add a proper mechanism to handle data for failed deletions.
} finally {
executorService.shutdown();
}
}
public static class Constants {
// Endpoint
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";
}
// 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);
}
/**
* Deletes the specified virtual private cloud (VPC) resource.
*
* @param vpcId The ID of the VPC 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());
}
}
/**
* Deletes the specified 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());
}
}
/**
* Deletes the specified security group.
*
* @param securityGroupId The ID of the security group 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());
}
}
/**
* Deletes the ECS instance.
*
* @param instanceId The ID of the ECS instance 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());
}
}
/**
* Deletes the key pair using the specified ECS client.
*
* @param keyPairName The key pair name.
* @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 the key pair, and set the region ID and key pair name.
DeleteKeyPairsRequest deleteKeyPairsRequest = new DeleteKeyPairsRequest()
.setRegionId(Constants.REGION_ID)
.setKeyPairNames(new Gson().toJson(Collections.singletonList(keyPairName)));
ecsClient.deleteKeyPairs(deleteKeyPairsRequest);
} catch (Exception e) {
// If the key pair fails to be deleted, throw a runtime exception that contains the error message.
throw new RuntimeException("DeleteKeyPairs failed: " + e.getMessage());
}
}
}