Developers can create an Elastic Compute Service (ECS) instance by using SDKs. This topic describes how to create an ECS instance by using SDK for Java 2.0.
Preparations
Install ECS SDK for Java and VPC SDK for Java.
Install ECS SDK for Java and VPC SDK for Java that are required to create an ECS instance. This section describes how to install the SDKs by adding Maven dependencies. For information about other installation methods, see Install ECS SDK for Java and Install VPC SDK for Java.
Configure access credentials.
Obtain an AccessKey pair. If no AccessKey pair is available, create an AccessKey pair. For more information, see Obtain an AccessKey pair.
ImportantUsing the AccessKey pair of an Alibaba Cloud account to perform operations is a high-risk operation. We recommend that you create a Resource Access Management (RAM) user, grant the RAM user permissions to access ECS resources, and then use the AccessKey pair of the RAM user to call ECS SDK for Java. For more information, see Grant RAM users permissions to use ECS resources.
Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime environment. For more information, see Configure environment variables in Linux, macOS, and Windows.
Create the resources required to create an instance
Before you create an ECS instance, you must create a virtual private cloud (VPC) and a security group.
If a VPC and a security group already exist, you can purchase an ECS instance after you obtain a vSwitch ID and the security group ID. For more information, see the Create an ECS instance section of this topic.
Create a VPC.
Create a VPC in the China (Hangzhou) region and specify 192.168.0.0/16 as the CIDR block of the VPC.
API
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.
The following sample code provides an example on how to create a VPC:
import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; import com.aliyun.vpc20160428.Client; import com.aliyun.vpc20160428.models.CreateVpcRequest; import com.aliyun.vpc20160428.models.CreateVpcResponse; import com.google.gson.Gson; public class CreateVpc { /** * Use your AccessKey ID and AccessKey secret to initialize the client. * In this example, the system reads the AccessKey pair from environment variables to authenticate the API request. You can modify the sample code based on your production environment. * Do not store critical information, such as AccessKey IDs and AccessKey secrets, in plaintext in the code. * @return Client * @throws Exception */ public static Client createClient() throws Exception { Config config = new Config() // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); config.endpoint = "vpc.cn-hangzhou.aliyuncs.com"; return new Client(config); } public static void main(String[] args) throws Exception { Client client = CreateVpc.createClient(); CreateVpcRequest createVpcRequest = new CreateVpcRequest() .setRegionId("cn-hangzhou") .setCidrBlock("192.168.0.0/16"); RuntimeOptions runtime = new RuntimeOptions(); try { CreateVpcResponse resp = client.createVpcWithOptions(createVpcRequest, runtime); System.out.println(new Gson().toJson(resp.getBody())); } catch (Exception error) { // Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only. // Print error messages. System.out.println(error.getMessage()); } } }
Sample response:
{ "requestId": "C58D1B4D-E419-5DB3-BB04-6B1EAF7D****", "resourceGroupId": "rg-acfmzw2jz2z****", "routeTableId": "vtb-bp1u3bc01p5oo4iry****", "VRouterId": "vrt-bp1ul3501gkdsyivs****", "vpcId": "vpc-bp1aag0sb9s4i92i3****" }
Create a vSwitch.
Create a vSwitch in the VPC and specify 192.168.0.0/24 as the CIDR block of the vSwitch.
API
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. Set the value to the vpcId value returned in Step 1.
Example: vpc-bp1aag0sb9s4i92i3****.
CidrBlock
The CIDR block of the vSwitch. Example: 192.168.0.0/24.
The following sample code provides an example on how to create a vSwitch:
import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; import com.aliyun.vpc20160428.Client; import com.aliyun.vpc20160428.models.CreateVSwitchRequest; import com.aliyun.vpc20160428.models.CreateVSwitchResponse; import com.google.gson.Gson; public class CreateVSwitch { /** * Use your AccessKey ID and AccessKey secret to initialize the client. * In this example, the system reads the AccessKey pair from environment variables to authenticate the API request. You can modify the sample code based on your production environment. * Do not store critical information, such as AccessKey IDs and AccessKey secrets, in plaintext in the code. * @return Client * @throws Exception */ public static Client createClient() throws Exception { Config config = new Config() // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); config.endpoint = "vpc.cn-hangzhou.aliyuncs.com"; return new Client(config); } public static void main(String[] args) throws Exception { Client client = CreateVSwitch.createClient(); CreateVSwitchRequest createVSwitchRequest = new CreateVSwitchRequest() .setRegionId("cn-hangzhou") .setZoneId("cn-hangzhou-i") .setCidrBlock("192.168.0.0/24") .setVpcId("vpc-bp1aag0sb9s4i92i3****"); RuntimeOptions runtime = new RuntimeOptions(); try { CreateVSwitchResponse resp = client.createVSwitchWithOptions(createVSwitchRequest, runtime); System.out.println(new Gson().toJson(resp.getBody())); } catch (Exception error) { // Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only. // Print error messages. System.out.println(error.getMessage()); } } }
Sample response:
{ "requestId": "4A48CC7D-A615-5C59-A846-53BA92CD****", "vSwitchId": "vsw-bp1nzprm8h7mmnl8t****" }
Create a security group.
API
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. Set the value to the vpcId value returned in Step 1.
Example: vpc-bp1aag0sb9s4i92i3****
The following sample code provides an example on how to create a security group:
import com.aliyun.ecs20140526.Client; import com.aliyun.ecs20140526.models.CreateSecurityGroupRequest; import com.aliyun.ecs20140526.models.CreateSecurityGroupResponse; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; import com.google.gson.Gson; public class CreateSecurityGroup { /** * Use your AccessKey ID and AccessKey secret to initialize the client. * In this example, the system reads the AccessKey pair from environment variables to authenticate the API request. You can modify the sample code based on your production environment. * Do not store critical information, such as AccessKey IDs and AccessKey secrets, in plaintext in the code. * @return Client * @throws Exception */ public static Client createClient() throws Exception { Config config = new Config() // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); config.endpoint = "ecs-cn-hangzhou.aliyuncs.com"; return new Client(config); } public static void main(String[] args) throws Exception { Client client = CreateSecurityGroup.createClient(); CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest() .setRegionId("cn-hangzhou") .setVpcId("vpc-bp1aag0sb9s4i92i3****"); RuntimeOptions runtime = new RuntimeOptions(); try { CreateSecurityGroupResponse resp = client.createSecurityGroupWithOptions(createSecurityGroupRequest, runtime); System.out.println(new Gson().toJson(resp.getBody())); } catch (Exception error) { // Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only. // Print error messages. System.out.println(error.getMessage()); } } }
Sample response:
{ "requestId": "15CE54BA-A181-5A8A-9895-DB13C035****", "securityGroupId": "sg-bp1esyhwfbqeyudt****" }
Add an inbound rule to the security group.
API
Parameter
Description and example
RegionId
The region ID of the security group. Example: cn-hangzhou.
SecurityGroupId
The ID of the security group. Set the value to the securityGroupId value returned in Step 3.
Example: sg-bp1esyhwfbqeyudt****
IpProtocol
The protocol. Example: tcp.
SourceCidrIp
The source CIDR block. Example: 0.0.0.0/0.
PortRange
The port range. Examples:
Linux instances: 22/22.
Windows instances: 3389/3389.
The following sample code provides an example on how to add an inbound rule to the security group:
import com.aliyun.ecs20140526.Client; import com.aliyun.ecs20140526.models.AuthorizeSecurityGroupRequest; import com.aliyun.ecs20140526.models.AuthorizeSecurityGroupRequest.AuthorizeSecurityGroupRequestPermissions; import com.aliyun.ecs20140526.models.AuthorizeSecurityGroupResponse; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; import com.google.gson.Gson; import static java.util.Arrays.asList; public class AuthorizeSecurityGroup { /** * Use your AccessKey ID and AccessKey secret to initialize the client. * In this example, the system reads the AccessKey pair from environment variables to authenticate the API request. You can modify the sample code based on your production environment. * Do not store critical information, such as AccessKey IDs and AccessKey secrets, in plaintext in the code. * @return Client * @throws Exception */ public static Client createClient() throws Exception { Config config = new Config() // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); config.endpoint = "ecs-cn-hangzhou.aliyuncs.com"; return new Client(config); } public static void main(String[] args) throws Exception { Client client = AuthorizeSecurityGroup.createClient(); AuthorizeSecurityGroupRequestPermissions permissions0 = new AuthorizeSecurityGroupRequestPermissions() .setIpProtocol("tcp") .setPortRange("22/22") .setSourceCidrIp("0.0.0.0/0"); AuthorizeSecurityGroupRequest authorizeSecurityGroupRequest = new AuthorizeSecurityGroupRequest() .setRegionId("cn-hangzhou") .setSecurityGroupId("sg-bp1esyhwfbqeyudt****") .setPermissions(asList( permissions0 )); RuntimeOptions runtime = new RuntimeOptions(); try { AuthorizeSecurityGroupResponse authoSGresponse = client.authorizeSecurityGroupWithOptions(authorizeSecurityGroupRequest, runtime); System.out.println(new Gson().toJson(authoSGresponse.getBody())); } catch (Exception error) { // Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only. // Print error messages. System.out.println(error.getMessage()); } } }
Sample response:
{ "requestId": "437D588F-EEB4-59C9-9133-B7021000****" }
Create an ECS instance
Create a pay-as-you-go ECS instance.
API | Parameter | Description and example |
RegionId | The ID of the region in which to create the 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.g7.large. | |
SecurityGroupId | The ID of the security group. Set the value to the securityGroupId value returned in Step 3. Example: sg-bp1esyhwfbqeyudt****. | |
VSwitchId | The ID of the vSwitch. Set the value to the vSwitchId value returned in Step 2. Example: vsw-bp1nzprm8h7mmnl8t****. | |
InstanceName | The name of the instance. Example: ecs_sdk_demo. | |
InstanceChargeType | The billing method of the instance. To create a pay-as-you-go instance, set this parameter to PostPaid. Note Make sure that your account balance is sufficient. | |
InternetMaxBandwidthOut | The maximum outbound public bandwidth. Example: 1 Mbit/s. | |
Password | The logon password of the instance. Example: <yourPassword>. Note To ensure instance security, specify a complex password. | |
SystemDisk.Category | The disk category of the system disk. Example: cloud_essd. |
The following sample code provides an example on how to create a pay-as-you-go ECS instance:
import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.RunInstancesRequest;
import com.aliyun.ecs20140526.models.RunInstancesRequest.RunInstancesRequestSystemDisk;
import com.aliyun.ecs20140526.models.RunInstancesResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;
public class RunInstances {
/**
* Use your AccessKey ID and AccessKey secret to initialize the client.
* In this example, the system reads the AccessKey pair from environment variables to authenticate the API request. You can modify the sample code based on your production environment.
* Do not store critical information, such as AccessKey IDs and AccessKey secrets, in plaintext in the code.
* @return Client
* @throws Exception
*/
public static Client createClient() throws Exception {
Config config = new Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "ecs-cn-hangzhou.aliyuncs.com";
return new Client(config);
}
public static void main(String[] args) throws Exception {
Client client = RunInstances.createClient();
RunInstancesRequestSystemDisk systemDisk = new RunInstancesRequestSystemDisk().setCategory("cloud_essd");
RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
.setRegionId("cn-hangzhou")
.setInstanceType("ecs.g7.large")
.setImageId("aliyun_3_x64_20G_scc_alibase_20220225.vhd")
.setSecurityGroupId("sg-bp1esyhwfbqeyudt****")
.setInstanceName("ecs_sdk_demo")
.setVSwitchId("vsw-bp1nzprm8h7mmnl8t****")
.setInstanceChargeType("PostPaid")
.setInternetMaxBandwidthOut(1)
.setSystemDisk(systemDisk)
.setPassword("<yourPassword>");
RuntimeOptions runtime = new RuntimeOptions();
try {
RunInstancesResponse resp = client.runInstancesWithOptions(runInstancesRequest, runtime);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception error) {
// Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only.
// Print error messages.
System.out.println(error.getMessage());
}
}
}
Sample response:
{
"instanceIdSets": {
"instanceIdSet": [
"i-bp17f3kzgtzzj91r****"
]
},
"requestId": "14CFCA1B-5A0C-59BA-B4C5-9D8B4B00****"
}
Connect to an ECS instance
The following section describes how to connect to a Linux instance by using Cloud Shell. To log on to the Cloud Shell console, enter https://shell.aliyun.com in the address bar of your browser. For information about how to connect to a Windows instance, see Connect to a Windows instance by using a username and password.
The first time you connect to Cloud Shell, a virtual machine (VM) is created. The creation process requires up to 40 seconds. If you open multiple Cloud Shell windows, all windows are connected to the same VM. The number of VMs does not increase when you open a new Cloud Shell window.
Query the public IP address of the instance.
API
Parameter
Description and example
RegionId
The region ID of the instance. Example: cn-hangzhou.
InstanceIds
The ID of the instance. Set the value to the instance ID returned in the Create an ECS instance section of this topic.
Example: '["i-bp17f3kzgtzzj91r****"]'.
The following sample code provides an example on how to query the public IP address of an instance:
aliyun ecs DescribeInstances \ --RegionId cn-hangzhou \ --InstanceIds '["i-bp17f3kzgtzzj91r****"]'
Find the following public IP address in the response.
Log on to the ECS instance by using SSH.
Stop an ECS instance
Stop a pay-as-you-go ECS instance.
API | Parameter | Description and example |
InstanceId | The ID of the instance. Example: i-bp17f3kzgtzzj91r****. |
The following sample code provides an example on how to stop a pay-as-you-go ECS instance:
import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.StopInstanceRequest;
import com.aliyun.ecs20140526.models.StopInstanceResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;
public class StopInstance {
/**
* Use your AccessKey ID and AccessKey secret to initialize the client.
* In this example, the system reads the AccessKey pair from environment variables to authenticate the API request. You can modify the sample code based on your production environment.
* Do not store critical information, such as AccessKey IDs and AccessKey secrets, in plaintext in the code.
* @return Client
* @throws Exception
*/
public static Client createClient() throws Exception {
Config config = new Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "ecs-cn-hangzhou.aliyuncs.com";
return new Client(config);
}
public static void main(String[] args) throws Exception {
Client client = StopInstance.createClient();
StopInstanceRequest stopInstanceRequest = new StopInstanceRequest().setInstanceId("i-bp17f3kzgtzzj91r****");
RuntimeOptions runtime = new RuntimeOptions();
try {
StopInstanceResponse resp = client.stopInstanceWithOptions(stopInstanceRequest, runtime);
System.out.println(new Gson().toJson(resp.getBody()));
}catch (Exception error) {
// Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only.
// Print error messages.
System.out.println(error.getMessage());
}
}
}
Sample response:
{
"requestId": "41CDB15C-5ADC-50BB-B6F8-0D824162****"
}
Release an ECS instance
Release a pay-as-you-go ECS instance.
You can directly release a subscription instance after it expires. To release a subscription instance before it expires, you must change the billing method of the instance to pay-as-you-go. For more information, see Change the billing method of an instance from subscription to pay-as-you-go and Release an instance.
API | Parameter | Description and example |
InstanceId | The ID of the instance. Example: i-bp17f3kzgtzzj91r****. |
The following sample code provides an example on how to release a pay-as-you-go ECS instance:
import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DeleteInstanceRequest;
import com.aliyun.ecs20140526.models.DeleteInstanceResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;
public class DeleteInstance {
/**
* Use your AccessKey ID and AccessKey secret to initialize the client.
* In this example, the system reads the AccessKey pair from environment variables to authenticate the API request. You can modify the sample code based on your production environment.
* Do not store critical information, such as AccessKey IDs and AccessKey secrets, in plaintext in the code.
* @return Client
* @throws Exception
*/
public static Client createClient() throws Exception {
Config config = new Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "ecs-cn-hangzhou.aliyuncs.com";
return new Client(config);
}
public static void main(String[] args) throws Exception {
Client client = DeleteInstance.createClient();
DeleteInstanceRequest deleteInstanceRequest = new DeleteInstanceRequest().setInstanceId("i-bp17f3kzgtzzj91r****");
RuntimeOptions runtime = new RuntimeOptions();
try {
DeleteInstanceResponse resp = client.deleteInstanceWithOptions(deleteInstanceRequest, runtime);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception error) {
// Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only.
// Print error messages.
System.out.println(error.getMessage());
}
}
}
Sample response:
{
"requestId": "557E2DE0-64F8-53C6-B3AB-7080B950****"
}