All Products
Search
Document Center

Elastic Compute Service:Call the RunInstances operation to create multiple ECS instances

Last Updated:Aug 09, 2024

This topic describes how to use Alibaba Cloud ECS SDK for Java 2.0 to call the RunInstances operation to create one or more Elastic Compute Service (ECS) instances.

Preparations

Before you create ECS instances, complete the following tasks:

  • Call the DescribeRegions operation to query the IDs of the regions in which you can create ECS instances and select a region. In the following example, the China (Hangzhou) region whose ID is cn-hangzhou is used.

  • Call the DescribeImages operation to query the IDs of the images that you can use to create ECS instances and select an image. In the following example, the image whose ID is aliyun_3_9_x64_20G_uefi_alibase_20231219.vhd is used.

  • Call the DescribeInstanceTypes operation to query the instance types that you can use to create ECS instances and select an instance type. In the following example, the ecs.g7.large instance type is used. For more information, see Overview of instance families.

  • Call the DescribeSecurityGroups operation to query the IDs of the security groups to which you can add ECS instances and select a security group. In the following example, the security group whose ID is sg-bp17pzrru69okvgh**** is used. The network type of the security group determines the network type of the ECS instances. For example, if you select a security group in a virtual private cloud (VPC), the new ECS instances are automatically added to the VPC.

  • Call the Virtual Private Cloud (VPC) DescribeVSwitches operation to query the IDs of the vSwitches that belong to the same VPC as the selected security group and select a vSwitch. In the following example, the vSwitch whose ID is vsw-bp1tunmso12kpu7vz**** is used.

  • Create an Alibaba Cloud account and obtain the AccessKey pair of the account.

    You must configure the AccessKey pair of your Alibaba Cloud account to use Alibaba Cloud ECS SDK for Java. For information about how to obtain an AccessKey pair, see Obtain an AccessKey pair.

  • Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. For more information, see the Step 2: Configure environment variables section of the "Get started with Alibaba Cloud Darabonba SDK for Java" topic.

  • Install ECS SDK for Java 2.0 in the development environment. For more information, see Install and use ECS SDKs.

    You must add the following dependencies to the Maven project:

    <dependencies>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>ecs20140526</artifactId>
          <version>5.1.8</version>
        </dependency>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>tea-openapi</artifactId>
          <version>0.3.2</version>
        </dependency>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>tea-console</artifactId>
          <version>0.0.1</version>
        </dependency>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>tea-util</artifactId>
          <version>0.2.21</version>
        </dependency>
    </dependencies>

Background information

The following section describes how to call the RunInstances operation to batch create and start ECS instances. For more information, see RunInstances.

Note

The RunInstances operation creates billable resources, such as ECS instances, and you are charged for the resources. If you want to only test the sample code, you can set the DryRun parameter to true in the code to perform only a dry run without creating ECS instances. The check items include whether the required parameters are specified, the request format, service limits, and available ECS instances.

Sample code

The following code provides an example on how to create pay-as-you-go ECS instances that use the pay-by-traffic billing method for network usage in a VPC:

// This file is auto-generated, don't edit it. Thanks.
package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * <b>description</b> :
     * <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
     * @return Client
     *
     * @throws Exception
     */
    public static com.aliyun.ecs20140526.Client createClient() throws Exception {
        // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. The following sample code is provided for reference only. 
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.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"));
        // Specify an endpoint. For information about endpoints, visit the following URL: https://api.aliyun.com/product/Ecs.
        config.endpoint = "ecs-cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ecs20140526.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.ecs20140526.Client client = Sample.createClient();
        com.aliyun.ecs20140526.models.RunInstancesRequest.RunInstancesRequestSystemDisk systemDisk = new com.aliyun.ecs20140526.models.RunInstancesRequest.RunInstancesRequestSystemDisk()
                .setSize("40")
                .setCategory("cloud_essd");
        com.aliyun.ecs20140526.models.RunInstancesRequest runInstancesRequest = new com.aliyun.ecs20140526.models.RunInstancesRequest()
                .setRegionId("cn-hangzhou")
                .setImageId("aliyun_3_9_x64_20G_uefi_alibase_20231219.vhd")
                .setInstanceType("ecs.g7.large")
                .setSecurityGroupId("sg-bp17pzrru69okvgh****")
                .setVSwitchId("vsw-bp1tunmso12kpu7vz****")
                .setInstanceName("s****")
                .setInstanceChargeType("PostPaid")
                .setSystemDisk(systemDisk)
                .setHostName("root")
                .setPassword("****999!!@@##")
                .setAmount(3);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, modify the code to display the response of the API operation based on your business requirements.
            client.runInstancesWithOptions(runInstancesRequest, runtime);
        } catch (TeaException 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());
            // Provide the URL that is used for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _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());
            // Provide the URL that is used for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Response

The following response is returned:

{
  "RequestId": "7F53B06E-3C1B-5C34-A97D-0CC78C609265",
  "InstanceIdSets": {
    "InstanceIdSet": [
      "i-bp1aalc7vopzddjt****",
      "i-bp1aalc7vopzddjt****",
      "i-bp1aalc7vopzddjt****"
    ]
  }
}