This topic describes how to use Alibaba Cloud SDK for Java to create an Elastic Compute Service (ECS) instance, which starts from creating a virtual private cloud (VPC).

Prerequisites

Before you begin, ensure that the following requirements are met:
  • You must have an Alibaba Cloud account and an AccessKey pair (AccessKey ID and AccessKey secret) to use Alibaba Cloud SDK for Java. You can create and view your AccessKey pair on the AccessKey Management page in the Alibaba Cloud Management Console.
  • You have installed Alibaba Cloud SDK for Java. For more information about SDK versions, see Alibaba Cloud SDK.
    <dependencies>
        <! -- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.3</version>
        </dependency>
        <! -- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-ecs-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-ecs</artifactId>
            <version>4.17.4</version>
        </dependency>
    </dependencies>

Prerequisites

Before you begin, ensure that the following requirements are met:
  • You must have an Alibaba Cloud account and an AccessKey pair (AccessKey ID and AccessKey secret) to use Alibaba Cloud SDK for Java. You can create and view your AccessKey pair on the AccessKey Management page in the Alibaba Cloud Management Console.
  • You have installed Alibaba Cloud SDK for Java. For more information about SDK versions, see Alibaba Cloud SDK.
    <dependencies>
        <! -- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.3</version>
        </dependency>
        <! -- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-ecs-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-ecs</artifactId>
            <version>4.17.4</version>
        </dependency>
        <! -- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-vpc-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-vpc</artifactId>
            <version>3.0.6</version>
        </dependency>
    </dependencies>

Sample code

This section shows the sample request code:
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.ecs.model.v20140526.RunInstancesRequest;
import com.aliyuncs.ecs.model.v20140526.RunInstancesResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vpc.model.v20160428.CreateVSwitchRequest;
import com.aliyuncs.vpc.model.v20160428.CreateVSwitchResponse;
import com.aliyuncs.vpc.model.v20160428.CreateVpcRequest;
import com.aliyuncs.vpc.model.v20160428.CreateVpcResponse;
import com.google.gson.Gson;

/**
 * CreateVpc    Creates a VPC.
 * CreateVSwitch    Creates a VSwitch.
 * RunInstances    Creates an ECS instance.
 */
public class Demo{

    public static void main(String[] args) {
        // Initialize common request parameters.
        IAcsClient client = Initialization();
        // Create a VPC.
        String VPCId = CreateVpc(client);
        Thread.sleep(5000);
        // Create a VSwitch.
        String VSwitchId = CreateVSwitch(client, VPCId);
        Thread.sleep(5000);
        // Create an ECS instance.
        RunInstances(client,VSwitchId);
    }

    /**
     * RunInstances    Creates an ECS instance.
     */
    private static void RunInstances(IAcsClient client, String vSwitchId) {
        RunInstancesRequest request = new RunInstancesRequest();
        // The ID of the image used to create the instance. For Alibaba Cloud Marketplace images, you can view the ID of a specific image on its Product Details page at Alibaba Cloud Marketplace.
        request.setImageId("centos_7_06_64_20G_alibase_20190711.vhd");
        // The name of the instance. It must be 2 to 128 characters in length. It must start with a letter and cannot start with http:// or https://. It can contain digits, colons (:), hyphens (-), and underscores (_). If this parameter is not specified, the name is set to the instance ID by default.
        request.setInstanceName("DOM_ECS_TEST");
        // The resource type of the instance. For more information, see Instance families or call the DescribeInstanceTypes operation to query the most recent instance type list.
        request.setInstanceType("ecs.g5.large");
        // The ID of the security group to which the instance belongs. Instances in the same security group can communicate with each other.
        request.setSecurityGroupId("sg-uf6h7bxba3d1zelb0619");
        // The network billing method. Valid values:
        // PayByBandwidth: Pay by bandwidth.
        // PayByTraffic (default): Pay by traffic.
        request.setInternetChargeType("PayByBandwidth");
        // The maximum inbound bandwidth from the Internet. Unit: Mbit/s. Valid values: 1 to 200.
        // Default value: 200.
        request.setInternetMaxBandwidthIn(100);
        // The maximum outbound bandwidth to the Internet. Unit: Mbit/s. Valid values: 0 to 100.
        // Default value: 0.
        request.setInternetMaxBandwidthOut(1);
        // The hostname of the ECS instance.
        // It cannot start or end with a period (.) or a hyphen (-). It cannot contain consecutive periods (.) or hyphens (-).
        // For Windows instances, the hostname must be 2 to 15 characters in length, and can contain letters, digits, and hyphens (-). The hostname cannot contain periods (.) or only contain digits.
        // For instances running other operating systems such as Linux, the hostname must be 2 to 64 characters in length. You can use periods (.) to separate a name into multiple segments. Each segment can contain letters, digits, and hyphens (-).
        request.setHostName("LocalHost");
        // The password of the instance. The password must be 8 to 30 characters in length. It must contain at least three of the following character types: uppercase letters, lowercase letters, digits, and special characters. Special characters include
        //          ()`~! @#$%^&*-_+=|{}[]:;'<>,.? /
        // For Windows instances, the password cannot start with a forward slash (/).
        // Note: For security reasons, we recommend that you use HTTPS to send requests if the Password parameter is specified.
        request.setPassword("EcsV587!") ;
        // The ID of the zone to which the instance belongs. For more information, call the DescribeZones operation to query the most recent zones.
        // This parameter is empty by default. If you do not specify a zone, the system randomly selects a zone.
        request.setZoneId("cn-shanghai-f");
        // The billing method of the instance. Valid values:
        // PrePaid: subscription. If you set this parameter to PrePaid, ensure that you have sufficient balance in your account. Otherwise, an InvalidPayMethod error is returned.
        // PostPaid (default): pay-as-you-go.
        request.setInstanceChargeType("PostPaid");
        // The size of the system disk. Unit: GiB. Valid values: 20 to 500.
        // The value of this parameter must be at least 20 and greater than or equal to the size of the image.
        // The default value is 40 GiB or the size of the image, depending on whichever is greater.
        request.setSystemDiskSize("40");
        // The category of the system disk. For non-I/O optimized instances of phased-out instance types, the default value is cloud. For other instances, the default value is cloud_efficiency. Valid values:
        // cloud: basic disk
        // cloud_efficiency: ultra disk
        // cloud_ssd: solid-state disk (SSD)
        // ephemeral_ssd: local SSD
        // cloud_essd: enhanced SSD (ESSD)
        request.setSystemDiskCategory("cloud_ssd");
        // The name of the system disk. It must be 2 to 128 characters in length. It must start with a letter and cannot start with http:// or https://. It can contain letters, digits, colons(:), underscores (_), and hyphens (-). This parameter is empty by default.
        request.setSystemDiskDiskName("SystemDisk");
        // The description of the system disk. It must be 2 to 256 characters in length and cannot start with http:// or https://. This parameter is empty by default.
        request.setSystemDiskDescription("SystemDisk_test");
        // The description of the instance. It must be 2 to 256 characters in length and cannot start with http:// or https://. This parameter is empty by default.
        request.setDescription("Testing...") ;
        // The ID of the VSwitch. This parameter is required when you create an instance in a VPC.
        request.setVSwitchId(vSwitchId);
        try {
            RunInstancesResponse response = client.getAcsResponse(request);
            System.out.println("--------------------The ECS instance was created.--------------------");
            System.out.println(new Gson().toJson(response));
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            throw new RuntimeException();
        }
    }

    /**
     * CreateVSwitch    Creates a VSwitch.
     */
    private static String CreateVSwitch(IAcsClient client, String vpcId) {
        CreateVSwitchRequest request = new CreateVSwitchRequest();
        // The ID of the VPC to which the VSwitch belongs.
        request.setVpcId(vpcId);
        // The Classless Inter-Domain Routing (CIDR block) of the VSwitch. It must meet the following requirements:
        // The subnet mask for the VSwitch must be 16 to 29 bits in length.
        // The CIDR block of the VSwitch must be within that of the VPC to which the VSwitch belongs.
        // The CIDR block of the VSwitch cannot be the same as the destination CIDR block of a route entry in the VPC but can be a subset of it.
        // If the CIDR block of the VSwitch is the same as that of the VPC, only the current VSwitch can be created for the VPC.
        request.setCidrBlock("192.168.0.0/16");
        // The ID of the zone to which the VSwitch belongs. You can call the DescribeZones operation to query the most recent zones.
        request.setZoneId("cn-shanghai-b");
        // The description of the VSwitch.
        // The description must be 2 to 256 characters in length. It must start with a letter and cannot start with http:// or https://.
        request.setDescription("DOCTestlalala");
        // The name of the VSwitch.
        // The name must be 2 to 128 characters in length. It must start with a letter and cannot start with http:// or https://.
        request.setVSwitchName("DOCTest");
        try {
            CreateVSwitchResponse response = client.getAcsResponse(request);
            System.out.println("--------------------The VSwitch was created.--------------------");
            System.out.println(new Gson().toJson(response));
            return response.getVSwitchId();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            throw new RuntimeException();
        }
    }

    /**
     * CreateVpc    Creates a VPC.
     */
    private static String CreateVpc(IAcsClient client) {
        CreateVpcRequest request = new CreateVpcRequest();
        // The CIDR block of the VPC. Set the value to one of the following CIDR blocks or their subnets:
        // 10.0.0.0/8
        // 172.16.0.0/12 (default)
        // 192.168.0.0/16
        request.setCidrBlock("192.168.0.0/16");
        // The description of the VPC.
        // The description must be 2 to 256 characters in length. It must start with a letter but cannot start with http:// or https://.
        request.setDescription("DOCTest");
        // The ID of the resource group.
        request.setResourceGroupId("rg-acfmxazb4ph6aiy");
        // The VPC name.
        // The name must be 2 to 128 characters in length and can contain letters, digits, periods (.), underscores (_), and hyphens (-). It must start with a letter but cannot start with http:// or https://.
        request.setVpcName("DOCTestlalala");
        try {
            CreateVpcResponse response = client.getAcsResponse(request);
            System.out.println("--------------------The VPC was created.--------------------");
            System.out.println(new Gson().toJson(response));
            return response.getVpcId();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            throw new RuntimeException();
        }
    }
    /**
     * Initialization  Initializes common request parameters.
     */
    private static IAcsClient Initialization() {
        // Initialize request parameters.
        DefaultProfile profile = DefaultProfile.getProfile(
                "<your-region-id>",             // The ID of the region.
                "<your-access-key-id>",         // The AccessKey ID.
                "<your-access-key-secret>");    // The AccessKey secret.
        return new DefaultAcsClient(profile);
    }
}                

Output

This section shows the sample success response:
--------------------The VPC was created.--------------------
{
    "requestId": "ED0661D9-2433-4A47-9B9B-A51C63DE87A8", 
    "vpcId": "vpc-uf6o7****", 
    "vRouterId": "vrt-uf6wgeki****", 
    "routeTableId": "vtb-uf6grhi****", 
    "resourceGroupId": "rg-acfmxa****"
}
--------------------The VSwitch was created.--------------------
{
    "RequestId":"0ED8D006-F706-4D23-88ED-E11ED28DCAC0",
    "VSwitchId":"vsw-25naue4****"
}
--------------------The ECS instance is created.--------------------
{
    "RequestId":"04F0F334-1335-436C-A1D7-6C044FE73368",
    "InstanceIdSets":{
        "InstanceIdSet":[
            "i-instanceid"
        ]
    }
}