All Products
Search
Document Center

Elastic Compute Service:Create a spot instance with the ECS console, SDK, or Terraform

Last Updated:May 29, 2026

Create a spot instance through the ECS console, SDK, or Terraform to run fault-tolerant workloads such as data analytics at a lower cost than pay-as-you-go pricing.

Before you begin

Follow these recommendations when creating a spot instance:

  • Set a reasonable bid strategy: Factor in market price volatility. A reasonable bid increases your chance of launching successfully and reduces release risk. Ensure your bid aligns with your budget expectations.

    Note

    If you're unsure about your bid amount, use automatic bidding, which accepts the real-time market price as the billing rate.

  • Ensure data persistence: Store critical data on storage media unaffected by spot instance releases, such as independent disks (not released with the instance), OSS, or NAS.

  • Monitor instance status: Use Cloud Monitor or instance metadata to track your spot instance status. See Detect and respond to spot instance interruption events.

  • Handle interruptions: Spot instances may be released when the market price exceeds your maximum bid or inventory runs out. Test your application to ensure it handles unexpected releases gracefully.

Create a spot instance

Create via the ECS console

  1. Go to the instance creation page and select the Custom Launch tab.

  2. Configure ECS resources based on your needs and the on-screen prompts.

    Note the following parameters. For other settings, see Custom launch instances.

    • Billing Method: Select Spot Instance.

    • Instance Usage Duration:

      • 1 Hour: The instance runs uninterrupted for one hour. After that, the system monitors inventory and bid changes to determine whether you can continue using it.

      • None: No fixed duration. This option often offers better pricing.

    • Maximum hourly price per instance:

      • Use Automatic Bid: Accept the current market price as your billing rate.

      • Set a maximum price: Set the highest hourly price you are willing to pay.

    • Instance Interruption Mode:

      • Release: The instance and its compute resources (vCPU, GPU, memory), static public IP, fixed bandwidth, and disks are released.

        Warning

        Spot instances aren't suitable for storing critical data. Choosing Instance Interruption Mode as Release may cause data loss. Disable disk release with instance termination or create disk snapshots regularly to protect your data.

      • Stop in Economical Mode: Compute resources (vCPU, GPU, memory), static public IP, and fixed bandwidth are reclaimed. Disks, Elastic IP Addresses, and snapshots are retained and continue to incur charges.

        Note

        A spot instance in economical mode may fail to restart due to insufficient inventory or a market price above your bid.

  3. Review your configuration on the right side of the page, set usage options, and click Confirm Order.

Create via SDK

Prerequisites

  1. Create an AccessKey

    An Alibaba Cloud account (primary account) has full permissions to all resources, so leaking its AccessKey poses serious risks. Use a RAM user AccessKey with minimal required permissions. See Create an AccessKey.

  2. Grant ECS permissions to the RAM user

    Grant the RAM user ECS management permissions. The sample code requires instance creation privileges. Recommended permission:

    Cloud Products

    Permission

    Elastic Compute Service

    AliyunECSFullAccess

  3. Configure access credentials

    The sample code reads the AccessKey from system environment variables. For setup steps, see Configure environment variables on Linux, macOS, and Windows.

  4. Install the ECS SDK

    Get the ECS SDK. This example uses Maven. For other methods, see Install the ECS Java SDK.

    Add the Maven dependency as follows:

    <dependencies>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>ecs20140526</artifactId>
            <version>5.3.0</version>
        </dependency>
    </dependencies>

Initialize the client

The Alibaba Cloud SDK supports multiple credential types for client initialization, such as AccessKey and Security Token Service token. See Manage access credentials. This example uses an AccessKey.

import com.aliyun.ecs20140526.Client;
import com.aliyun.teaopenapi.models.Config;

public class Sample {
    private static Client createClient() throws Exception {
        Config config = new Config()
                // Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                // For Endpoint, see https://api.aliyun.com/product/Ecs
                .setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
        return new Client(config);
    }
}

Build the API request object

Check the API documentation for parameter details before building the request object.

// Build the request object
RunInstancesRequest request = new RunInstancesRequest()
    // Set the region
    .setRegionId("cn-hangzhou")
    // Set billing method to pay-as-you-go
    .setInstanceChargeType("PostPaid")
    // Set bidding strategy to automatic
    .setSpotStrategy("SpotAsPriceGo")
    // Set 1-hour usage duration: guarantees the instance runs for 1 hour without release
    .setSpotDuration(1)
    // Set instance type
    .setInstanceType("instanceType")
    // Set image
    .setImageId("imageId")
    // Set security group ID
    .setSecurityGroupId("securityGroupId")
    // Set virtual switch ID
    .setVSwitchId("vSwitchId");

Make the call

Configure runtime options such as timeout and proxy settings when calling OpenAPI. See Advanced configuration.

// Set runtime options
RuntimeOptions runtime = new RuntimeOptions();
// Call the RunInstances API
RunInstancesResponse response = client.runInstancesWithOptions(request, runtime);
System.out.println(response.body.toMap());

Handle exceptions

The Java SDK categorizes exceptions into TeaUnretryableException and TeaException.

  • TeaUnretryableException: Network issues after reaching the maximum retry count.

  • TeaException: Business-related errors.

Handle exceptions properly to ensure system robustness, for example, by propagating them, logging details, or attempting recovery.

Complete example

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.RunInstancesRequest;
import com.aliyun.ecs20140526.models.RunInstancesResponse;
import com.aliyun.ecs20140526.models.RunInstancesResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaUnretryableException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.alibaba.fastjson.JSONArray;

import java.util.Arrays;

public class Sample {
    private static Client createClient() throws Exception {
        Config config = new Config()
                // Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                // For Endpoint, see https://api.aliyun.com/product/Ecs
                .setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
        return new Client(config);
    }

    public static void main(String[] args) {
        try {
            Client client = Sample.createClient();
            // Build the request object
            RunInstancesRequest request = new RunInstancesRequest()
                    // Set the region
                    .setRegionId("cn-hangzhou")
                    // Set billing method to pay-as-you-go
                    .setInstanceChargeType("PostPaid")
                    // Set bidding strategy to automatic
                    .setSpotStrategy("SpotAsPriceGo")
                    // Set 1-hour usage duration: guarantees the instance runs for 1 hour without release
                    .setSpotDuration(1)
                    // Set instance type
                    .setInstanceType("instanceType")
                    // Set image
                    .setImageId("imageId")
                    // Set security group ID
                    .setSecurityGroupId("securityGroupId")
                    // Set virtual switch ID
                    .setVSwitchId("vSwitchId");
            // Set runtime options
            RuntimeOptions runtime = new RuntimeOptions();
            // Call the RunInstances API
            RunInstancesResponse response = client.runInstancesWithOptions(request, runtime);
            System.out.println(response.body.toMap());
        } catch (TeaUnretryableException ue) {
            // This example only prints exceptions. Handle exceptions carefully in production code—never ignore them.
            ue.printStackTrace();
            // Print error message
            System.out.println(ue.getMessage());
            // Print request details for debugging
            System.out.println(ue.getLastRequest());
        } catch (TeaException e) {
            // This example only prints exceptions. Handle exceptions carefully in production code—never ignore them.
            e.printStackTrace();
            // Print error code
            System.out.println(e.getCode());
            // Print error message (includes RequestId)
            System.out.println(e.getMessage());
            // Print detailed server-side error
            System.out.println(e.getData());
        } catch (Exception e) {
            // This example only prints exceptions. Handle exceptions carefully in production code—never ignore them.
            e.printStackTrace();
        }
    }
}

Create via Terraform

Note

The following steps include ready-to-run sample code. Run now

Prerequisites

  • Create an AccessKey

    An Alibaba Cloud account (primary account) has full permissions to all resources. To prevent unauthorized use if the AccessKey leaks, use a RAM user AccessKey with minimal required permissions. See Create a RAM user and Create an AccessKey.

  • Create a custom policy

    Create a custom policy to allow launching ECS instances, viewing instance details, and checking spot price history. See Create a custom policy.

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "ecs:RunInstances",
            "ecs:DescribeInstances",
            "ecs:DescribeSpotPriceHistory"
          ],
          "Resource": "*"
        }
      ]
    }

Resources used

Procedure

  1. Open https://shell.aliyun.com and log on to Cloud Shell.

    For other ways to use Cloud Shell, see Use Cloud Shell.

  2. Create a project folder named terraform and enter the directory.

    mkdir terraform
    cd terraform
  3. Create a configuration file named main.tf with the following content:

    main.tf

    provider "alicloud" {
      region = var.region
    }
    
    # Region
    variable "region" {
      type    = string
      default = "cn-beijing"
    }
    
    # VPC name
    variable "vpc_name" {
      type    = string
      default = "tf_test_fofo"
    }
    
    # VPC CIDR block
    variable "vpc_cidr_block" {
      type    = string
      default = "172.16.0.0/12"
    }
    
    # vSwitch CIDR block
    variable "vswitch_cidr_block" {
      type    = string
      default = "172.16.0.0/21"
    }
    
    # Zone
    variable "availability_zone" {
      type    = string
      default = "cn-beijing-b"
    }
    
    # Security group name
    variable "security_group_name" {
      type    = string
      default = "default"
    }
    
    # Instance type
    variable "instance_type" {
      type    = string
      default = "ecs.n2.small"
    }
    
    # System disk category
    variable "system_disk_category" {
      type    = string
      default = "cloud_efficiency"
    }
    
    # OS image
    variable "image_id" {
      type    = string
      default = "ubuntu_140405_64_40G_cloudinit_20161115.vhd"
    }
    
    # Instance name
    variable "instance_name" {
      type    = string
      default = "test_fofo"
    }
    
    # Public bandwidth
    variable "internet_max_bandwidth_out" {
      type    = number
      default = 10
    }
    
    # Billing method
    variable "instance_charge_type" {
      type    = string
      default = "PostPaid"
    }
    
    # Spot instance bidding strategy
    variable "spot_strategy" {
      type    = string
      default = "SpotAsPriceGo"
    }
    
    # Spot instance reserved duration
    variable "spot_duration" {
      type    = number
      default = 0
    }
    
    # Inbound rule port range
    variable "port_range" {
      type    = string
      default = "1/65535"
    }
    
    # Inbound rule priority
    variable "priority" {
      type    = number
      default = 1
    }
    
    # Inbound rule CIDR
    variable "cidr_ip" {
      type    = string
      default = "0.0.0.0/0"
    }
    
    resource "alicloud_vpc" "vpc" {
      vpc_name   = var.vpc_name
      cidr_block = var.vpc_cidr_block
    }
    
    resource "alicloud_vswitch" "vsw" {
      vpc_id     = alicloud_vpc.vpc.id
      cidr_block = var.vswitch_cidr_block
      zone_id    = var.availability_zone
    }
    
    resource "alicloud_security_group" "default" {
      security_group_name = var.security_group_name
      vpc_id              = alicloud_vpc.vpc.id
    }
    
    resource "alicloud_instance" "instance" {
      availability_zone          = var.availability_zone
      security_groups            = [alicloud_security_group.default.id]
      instance_type              = var.instance_type
      system_disk_category       = var.system_disk_category
      image_id                   = var.image_id
      instance_name              = var.instance_name
      vswitch_id                 = alicloud_vswitch.vsw.id
      internet_max_bandwidth_out = var.internet_max_bandwidth_out
      instance_charge_type       = var.instance_charge_type
      spot_strategy              = var.spot_strategy
      spot_duration              = var.spot_duration
    }
    
    resource "alicloud_security_group_rule" "allow_all_tcp" {
      type              = "ingress"
      ip_protocol       = "tcp"
      nic_type          = "intranet"
      policy            = "accept"
      port_range        = var.port_range
      priority          = var.priority
      security_group_id = alicloud_security_group.default.id
      cidr_ip           = var.cidr_ip
    }
  4. Run terraform init to initialize the configuration.

    image

  5. Run terraform apply. When prompted, enter yes and press Enter. If the following message appears, your spot instance is created.

    image

  6. Run terraform show to view details of the created resources.

    image

Clean up resources

To release resources created by Terraform, run the following command. See Common commands.

terraform destroy

References

Other methods

Alibaba Cloud also offers Auto Scaling, ACK, and auto provisioning groups for spot instance creation in more complex scenarios.

Auto Scaling (ESS)

Dynamically mixes pay-as-you-go and spot instances to respond to load fluctuations, and replaces released instances automatically. See Use spot instances in scaling groups to reduce costs.

ACK

Creates low-cost Kubernetes node pools for stateless, fault-tolerant applications. See Best practices for spot instance node pools.

Auto provisioning group

Provisions instance clusters across multiple zones and billing methods (pay-as-you-go and spot) with a single configuration. See Auto provisioning group configuration example.