All Products
Search
Document Center

Elastic Compute Service:Create and manage an ECS instance by using an SDK

Last Updated:Dec 19, 2023

If you are a developer, you can create an Elastic Compute Service (ECS) instance by using an SDK. This topic describes how to use ECS SDK for Java to create an ECS instance.

Prepare an ECS SDK for Java environment

Before you use ECS SDK for Java to create an instance, you must configure the ECS SDK for Java environment and add the aliyun-java-sdk-core, aliyun-java-sdk-ecs, aliyun-java-sdk-vpc, and fastjson dependencies to the pom.xml file in the Maven project. For more information, see Install ECS SDK for Java.

The following sample code provides an example on how to add the aliyun-java-sdk-vpc dependency to the pom.xml file:

<dependencies>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-ecs</artifactId>
            <version>4.17.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-vpc</artifactId>
            <version>3.0.9</version>
        </dependency>
    </dependencies>

Obtain an AccessKey pair

For information about how to create an AccessKey pair, see Create an AccessKey pair.

Note

To protect the AccessKey pair of your Alibaba Cloud account, we recommend that you create a Resource Access Management (RAM) user, grant the RAM user permissions to access ECS instances, and then use the AccessKey pair of the RAM user to call ECS SDK for Java. For more information, see Control access to resources by using RAM users.

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.

Note

If a VPC and a security group already exist, you can purchase an 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.

  1. 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.

    Operation

    Parameter

    Description and example

    CreateVpc

    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.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.profile.DefaultProfile;
    import com.google.gson.Gson;
    import com.aliyuncs.vpc.model.v20160428.*;
    
    public class CreateVpc {
    
        public static void main(String[] args) {
            // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime. 
            // If the project code is leaked, the AccessKey pair may be leaked and security issues may occur on all resources of your account. The following sample code provides an example on how to use environment variables to obtain an AccessKey pair and use the AccessKey pair to call API operations. We recommend that you use Security Token Service (STS) tokens, which provide higher security. 
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            IAcsClient client = new DefaultAcsClient(profile);
    
            CreateVpcRequest request = new CreateVpcRequest();
            request.setRegionId("cn-hangzhou");
            request.setCidrBlock("192.168.0.0/16");
    
            try {
                CreateVpcResponse response = client.getAcsResponse(request);
                System.out.println(new Gson().toJson(response));
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                System.out.println("ErrCode:" + e.getErrCode());
                System.out.println("ErrMsg:" + e.getErrMsg());
                System.out.println("RequestId:" + e.getRequestId());
            }
    
        }
    }

    Sample response:

    {
        "requestId":"5BE6AEA4-347F-46A9-9808-B429EF02****",
        "vpcId":"vpc-bp1h99qfh290thxml****",
        "vRouterId":"vrt-bp1cbum5ozelljyet****",
        "routeTableId":"vtb-bp1qm6p3yoww2cv10****",
        "resourceGroupId":"rg-acfmzw2jz2z****"
    }
  2. Create a vSwitch.

    Create a vSwitch in the VPC and specify 192.168.0.0/24 as the CIDR block of the vSwitch.

    Operation

    Parameter

    Description and example

    CreateVSwitch

    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-bp1h99qfh290thxml****.

    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.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.profile.DefaultProfile;
    import com.google.gson.Gson;
    import java.util.*;
    import com.aliyuncs.vpc.model.v20160428.*;
    
    public class CreateVSwitch {
    
        public static void main(String[] args) {
            // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime. 
            // If the project code is leaked, the AccessKey pair may be leaked and security issues may occur on all resources of your account. The following sample code provides an example on how to use environment variables to obtain an AccessKey pair and use the AccessKey pair to call API operations. We recommend that you use STS tokens, which provide higher security. 
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            IAcsClient client = new DefaultAcsClient(profile);
    
            CreateVSwitchRequest request = new CreateVSwitchRequest();
            request.setRegionId("cn-hangzhou");
            request.setCidrBlock("192.168.0.0/24");
            request.setVpcId("vpc-bp1h99qfh290thxml****");
            request.setZoneId("cn-hangzhou-i");
    
            try {
                CreateVSwitchResponse response = client.getAcsResponse(request);
                System.out.println(new Gson().toJson(response));
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                System.out.println("ErrCode:" + e.getErrCode());
                System.out.println("ErrMsg:" + e.getErrMsg());
                System.out.println("RequestId:" + e.getRequestId());
            }
    
        }
    }

    Sample response:

    {
        "requestId": "BAFBC8C4-3C65-427B-B470-3D257288****",
        "vSwitchId": "vsw-bp1mihse903i05oxn****"
    }
  3. Create a security group.

    Operation

    Parameter

    Description and example

    CreateSecurityGroup

    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-bp1h99qfh290thxml****.

    The following sample code provides an example on how to create a security group:

    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.profile.DefaultProfile;
    import com.google.gson.Gson;
    import java.util.*;
    import com.aliyuncs.ecs.model.v20140526.*;
    
    public class CreateSecurityGroup {
    
        public static void main(String[] args) {
            // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime. 
            // If the project code is leaked, the AccessKey pair may be leaked and security issues may occur on all resources of your account. The following sample code provides an example on how to use environment variables to obtain an AccessKey pair and use the AccessKey pair to call API operations. We recommend that you use STS tokens, which provide higher security. 
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            IAcsClient client = new DefaultAcsClient(profile);
    
            CreateSecurityGroupRequest request = new CreateSecurityGroupRequest();
            request.setRegionId("cn-hangzhou");
            request.setVpcId("vpc-bp1h99qfh290thxml****");
    
            try {
                CreateSecurityGroupResponse response = client.getAcsResponse(request);
                System.out.println(new Gson().toJson(response));
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                System.out.println("ErrCode:" + e.getErrCode());
                System.out.println("ErrMsg:" + e.getErrMsg());
                System.out.println("RequestId:" + e.getRequestId());
            }
    
        }
    }

    Sample response:

    {
        "requestId": "718D29C6-6183-4196-AD76-A53F6A6E****",
        "securityGroupId": "sg-bp1dve08xy2c8y9g****"
    }
  4. Add an inbound rule to the security group.

    Operation

    Parameter

    Description and example

    AuthorizeSecurityGroup

    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-bp1dve08xy2c8y9g****.

    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.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.profile.DefaultProfile;
    import com.google.gson.Gson;
    import java.util.*;
    import com.aliyuncs.ecs.model.v20140526.*;
    
    public class AuthorizeSecurityGroup {
    
        public static void main(String[] args) {
            // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime. 
            // If the project code is leaked, the AccessKey pair may be leaked and security issues may occur on all resources of your account. The following sample code provides an example on how to use environment variables to obtain an AccessKey pair and use the AccessKey pair to call API operations. We recommend that you use STS tokens, which provide higher security. 
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            IAcsClient client = new DefaultAcsClient(profile);
    
            AuthorizeSecurityGroupRequest request = new AuthorizeSecurityGroupRequest();
            request.setRegionId("cn-hangzhou");
            request.setSecurityGroupId("sg-bp1dve08xy2c8y9g****");
            request.setIpProtocol("tcp");
            request.setPortRange("22/22");
            request.setSourceCidrIp("0.0.0.0/0");
    
            try {
                AuthorizeSecurityGroupResponse response = client.getAcsResponse(request);
                System.out.println(new Gson().toJson(response));
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                System.out.println("ErrCode:" + e.getErrCode());
                System.out.println("ErrMsg:" + e.getErrMsg());
                System.out.println("RequestId:" + e.getRequestId());
            }
    
        }
    }

    Sample response:

    {
        "requestId": "7052E70F-4678-4400-81CF-E0133CCB****"
    }

Create an ECS instance

Create a subscription ECS instance.

Operation

Parameter

Description and example

RunInstances

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 aliyun_2_1903_x64_20G_alibase_20200324.vhd Alibaba Cloud Linux image.

InstanceType

The instance type.

  • For the applications of individuals, we recommend that you select the ecs.s6-c1m2.small instance type that has 1 vCPU and 2 GiB of memory.

  • For the applications of small and medium-sized enterprises, we recommend that you select the ecs.c5.large instance type that has 2 vCPUs and 4 GiB of memory.

SecurityGroupId

The ID of the security group. Set the value to the securityGroupId value returned in Step 3.

Example: sg-bp1dve08xy2c8y9g****.

VSwitchId

The ID of the vSwitch. Set the value to the vSwitchId value returned in Step 2.

Example: vsw-bp1mihse903i05oxn****.

InstanceName

The instance name.

Example: ecs_sdk_demo.

InstanceChargeType

The billing method of the instance. To create a subscription instance, set the value to PrePaid.

Note

Make sure that you have sufficient balance in your account.

PeriodUnit

The unit of the subscription duration. Example: Month.

Period

The subscription duration. Example: 1.

InternetMaxBandwidthOut

The maximum outbound public bandwidth. Example: 1 Mbit/s.

Password

The logon password of the instance. Example: <yourPassword>.

Note

You must specify a complex password to ensure instance security.

The following sample code provides an example on how to create a subscription instance:

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import java.util.*;
import com.aliyuncs.ecs.model.v20140526.*;

public class RunInstances {

    public static void main(String[] args) {
        // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime. 
        // If the project code is leaked, the AccessKey pair may be leaked and security issues may occur on all resources of your account. The following sample code provides an example on how to use environment variables to obtain an AccessKey pair and use the AccessKey pair to call API operations. We recommend that you use STS tokens, which provide higher security. 
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        IAcsClient client = new DefaultAcsClient(profile);

        RunInstancesRequest request = new RunInstancesRequest();
        request.setRegionId("cn-hangzhou");
        request.setImageId("aliyun_2_1903_x64_20G_alibase_20200324.vhd");
        request.setInstanceType("ecs.s6-c1m2.small");
        request.setSecurityGroupId("sg-bp1dve08xy2c8y9g****");
        request.setVSwitchId("vsw-bp1mihse903i05oxn****");
        request.setInstanceName("ecs_sdk_demo");
        request.setInternetMaxBandwidthOut(1);
        request.setPassword("<yourPassword>");
        request.setPeriod(1);
        request.setPeriodUnit("Month");
        request.setInstanceChargeType("PrePaid");

        try {
            RunInstancesResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }

    }
}

Sample response:

{
    "requestId": "9582F9F2-349C-438E-A6A2-3E7B6B56****",
    "tradePrice": ****,
    "instanceIdSets": ["i-bp1hcv43i3glqxbv****"]
}

Connect to an ECS instance

This section describes how to connect to a Linux instance by using Cloud Shell. For information about how to connect to a Windows instance, see Connect to a Windows instance by using a username and password.

  1. Query the public IP address of the instance.

    Operation

    Parameter

    Description and example

    DescribeInstances

    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-bp1hcv43i3glqxbv****"]'.

    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-bp1hcv43i3glqxbv****"]'

    Find the following public IP address in the response.

    公网IP

  2. Log on to the ECS instance by using SSH.

    ssh登录

Release an instance

You can manually release a subscription instance after it expires. If you do not renew an expired instance, the instance is automatically released.