The example shows how to create an ECS instance by calling the CreateInstanceRequest API.

To create an ECS instance, obtain the following information:

  • Image ID

    Obtain the ID of the image to use by calling the DescribeImages API.

  • Instance types

    Select the instance type to use. For more information, see Instance type families.

Code example

Notice Running the code in this example will create an ECS instance and generate fees.
import java.util.UUID;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.ecs.model.v20140526. CreateInstanceRequest;
import com.aliyuncs.ecs.model.v20140526. CreateInstanceResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
public class Demo {
    public static void main(String[] args) {
        //Create a DefaultAcsClient instance and initialize it
        DefaultProfile profile = DefaultProfile.getProfile(
            "<your-region-id>", // your region ID
            "<your-access-key-id>", // your AccessKey ID
            "<your-access-key-secret>") // your AccessKey Secret
        IAcsClient client = new DefaultAcsClient(profile);
         // Create an API request and set parameters
        CreateInstanceRequest request = new CreateInstanceRequest();
        request.setImageId("alinux_17_01_64_20G_cloudinit_20171222.vhd");
        request.setInstanceName("MyEcsInstance");
        request.setSecurityGroupId("<your-security-group-id>");
        request.setInstanceType("ecs.t1.small");
        request.setClientToken(UUID.randomUUID().toString());
        // Initiate a request and handle the response or exceptions
        CreateInstanceResponse response;
        try {
            response = client.getAcsResponse(request);
            String instanceId = response.getInstanceId();
            System.out.println("Create instance success, instanceId = " + instanceId);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}