A spot instance is a cost-effective computing resource offered by Alibaba Cloud for cost-sensitive workloads that can tolerate interruptions, such as data analysis, testing, and development. The price of a spot instance is significantly lower than that of a pay-as-you-go instance. However, a spot instance may be automatically released due to market price fluctuations or changes in resource supply and demand. This topic describes how to create a spot instance in the ECS console or using an SDK or Terraform.
Suggestions
When you create a spot instance, consider the following suggestions:
-
Choose a reasonable bidding mode: When you make a bid, take market price fluctuations into account. A reasonable bid increases the chance of successfully creating a spot instance and reduces the risk of the instance being released if your bid falls below the market price. Your bid must also align with your budget and business requirements.
NoteIf you cannot decide on a bid price, we recommend using automatic bidding. This means you accept the real-time market price as the billing price for the instance type.
-
Ensure data persistence: We recommend using a persistent storage medium to store your important data. This prevents data loss if the spot instance is released. For example, you can use standalone cloud disks (which are not released with the instance), OSS, or NAS to store data.
-
Monitor the instance status: You can use CloudMonitor or instance metadata to monitor the status of your spot instance and determine whether it has been interrupted and reclaimed. For more information, see Perceive and respond to spot instance interruption events.
-
Handle interruptions: A spot instance can be released if the market price exceeds your maximum bid or if there is insufficient stock. Test your application to ensure it can gracefully handle unexpected instance releases.
Procedure
ECS console
-
Go to the instance creation page and click the Custom Launch tab.
-
Configure the ECS resources based on your requirements and the on-screen instructions.
Note the following parameters. For information about other configurations, see Create an instance using the wizard.
-
Billing Method: Select Spot Instance.
-
Instance Usage Duration:
-
1 Hour: The instance is guaranteed to run for one hour without being automatically released. After one hour, the system monitors the inventory and your bid in real time to determine whether the instance can continue to run.
-
None: No specific usage duration is set. This option offers a lower price compared to setting a 1-hour duration.
-
-
Highest price per instance:
-
Use Automatic Bid: Select this option to accept the current market price as the billing price for the instance type.
-
Set Maximum Price: You must set a price cap for the specified instance type. This is the highest price you are willing to pay for it.
-
-
Instance Interruption Mode:
-
Release: When an interruption is triggered, your instance is released. This releases its computing resources (vCPUs, GPUs, and memory), fixed public IP address, fixed bandwidth, and cloud disks (system and data disks).
WarningSpot instances are not designed for storing critical data. If you set the Instance Interruption Mode to Release, you may lose data. We recommend disabling the feature that releases cloud disks with the instance or regularly create snapshots for your cloud disks to ensure data safety.
-
Stop in Economical Mode: When an interruption is triggered, the instance enters Stop in Economical Mode. Its computing resources (vCPUs, GPUs, and memory), fixed public IP address, and fixed bandwidth are reclaimed. Other resources, such as cloud disks (system and data disks), elastic IP addresses, and snapshots, are retained and continue to incur charges.
NoteA spot instance that is in Stop in Economical Mode may fail to restart due to insufficient inventory or if the market price exceeds your bid.
-
-
-
On the right side of the page, review the instance configuration and set options such as the usage duration. Click Confirm Order.
SDK
Prerequisites
-
Create an AccessKey pair
An Alibaba Cloud account has full permissions over all resources. Leaking the AccessKey pair of your Alibaba Cloud account puts your resources at high risk. We recommend using the AccessKey pair of a RAM user with the minimum required permissions. For more information, see Create an AccessKey pair.
-
Grant ECS-related permissions to the RAM user
Grant the RAM user the necessary permissions to manage ECS resources. The sample code in this topic creates an instance, which requires the following permission:
Cloud service
Permission
ECS
AliyunECSFullAccess
-
Configure access credentials
The sample code in this topic reads the AccessKey pair from system environment variables to authenticate with Alibaba Cloud services. For instructions, see Configure environment variables in Linux, macOS, and Windows.
-
Install the ECS SDK
Install the ECS SDK. This topic demonstrates how to install it by adding a Maven dependency. For other installation methods, see Install ECS SDK for Java.
Initialize the client
The Alibaba Cloud SDK supports various access credentials to initialize the client, such as an AccessKey pair or an STS token. For more information, see Manage access credentials in the SDK for Java. This example uses an AccessKey pair to initialize the client.
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. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
// For the endpoint, see https://api.aliyun.com/product/Ecs
.setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
return new Client(config);
}
}
Build the request object
Before building the request object, see the API documentation for parameter details.
// Build the request object.
RunInstancesRequest request = new RunInstancesRequest()
// Set the region.
.setRegionId("cn-hangzhou")
// Set the billing method to PostPaid.
.setInstanceChargeType("PostPaid")
// Set the bidding policy to SpotAsPriceGo (automatic bidding).
.setSpotStrategy("SpotAsPriceGo")
// Set a 1-hour protection period for the instance.
.setSpotDuration(1)
// Set the instance type.
.setInstanceType("instanceType")
// Set the image.
.setImageId("imageId")
// Set the security group ID.
.setSecurityGroupId("securityGroupId")
// Set the vSwitch ID.
.setVSwitchId("vSwitchId");
Initiate the call
When calling an API operation, you can set runtime parameters, such as timeout and proxy settings. For more information, see Advanced settings.
// Set runtime options.
RuntimeOptions runtime = new RuntimeOptions();
// Call the RunInstances operation.
RunInstancesResponse response = client.runInstancesWithOptions(request, runtime);
System.out.println(response.body.toMap());
Handle exceptions
The SDK for Java classifies exceptions into two main categories: TeaUnretryableException and TeaException.
-
TeaUnretryableException: This exception typically indicates a network issue and is thrown after reaching the maximum number of retries.
-
TeaException: This exception primarily indicates a service operation error.
To ensure system robustness and stability, we recommend handling exceptions appropriately by propagating them, logging them, 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. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
// For the 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 the billing method to PostPaid.
.setInstanceChargeType("PostPaid")
// Set the bidding policy to SpotAsPriceGo (automatic bidding).
.setSpotStrategy("SpotAsPriceGo")
// Set a 1-hour protection period for the instance.
.setSpotDuration(1)
// Set the instance type.
.setInstanceType("instanceType")
// Set the image.
.setImageId("imageId")
// Set the security group ID.
.setSecurityGroupId("securityGroupId")
// Set the vSwitch ID.
.setVSwitchId("vSwitchId");
// Set runtime options.
RuntimeOptions runtime = new RuntimeOptions();
// Call the RunInstances operation.
RunInstancesResponse response = client.runInstancesWithOptions(request, runtime);
System.out.println(response.body.toMap());
} catch (TeaUnretryableException ue) {
// For demonstration only. In production, always handle exceptions.
ue.printStackTrace();
// Print the error message.
System.out.println(ue.getMessage());
// Print the request log to find request information when an error occurs.
System.out.println(ue.getLastRequest());
} catch (TeaException e) {
// For demonstration only. In production, always handle exceptions.
e.printStackTrace();
// Print the error code.
System.out.println(e.getCode());
// Print the error message, which contains the RequestId.
System.out.println(e.getMessage());
// Print the specific error details returned by the server.
System.out.println(e.getData());
} catch (Exception e) {
// For demonstration only. In production, always handle exceptions.
e.printStackTrace();
}
}
}
Terraform
You can run the sample code in this section with a single click in Terraform Explorer.
Prerequisites
-
Create an AccessKey pair
An Alibaba Cloud account has full permissions over all resources. To avoid risks associated with a leaked AccessKey pair, we recommend that you use the AccessKey pair of a RAM user with the minimum required permissions. For more information, see Create a RAM user and Create an AccessKey pair.
-
Create a custom policy
Use the following example to create a custom policy for a RAM user. This policy allows the user to start ECS instances, view instance details, and view the price history of spot instances. For more information, see Create a custom policy.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": [ "ecs:RunInstances", "ecs:DescribeInstances", "ecs:DescribeSpotPriceHistory" ], "Resource": "*" } ] }
Resources used
-
alicloud_vpc: Creates a VPC.
-
alicloud_vswitch: Creates a vSwitch to provide subnet functionality for instances within the VPC.
-
alicloud_security_group: Creates a security group named default and associates it with the created VPC.
-
alicloud_instance: Creates an ECS instance.
-
alicloud_security_group_rule: Defines a security group rule.
Procedure
-
Open a browser, go to https://shell.aliyun.com, and log in to Cloud Shell.
For more ways to access and use Cloud Shell, see Use Cloud Shell.
-
Create a project directory named terraform to store your Terraform resources, and then navigate to that directory.
mkdir terraform cd terraform -
Create a configuration file named main.tf with the following content:
-
Run the
terraform initcommand to initialize the configuration.
-
Run the
terraform applycommand. When prompted, enteryesand press Enter. The following output indicates that the spot instance is created.
-
Run the
terraform showcommand to view the details of the resources that Terraform created.
Clean up resources
When you no longer need the resources created or managed by Terraform, run the following command to release them. For more information, see Common commands.
terraform destroy
References
-
For an introduction to Terraform, see What is Alibaba Cloud Terraform?.
-
If
terraform inittimes out and fails to download providers due to network latency, see Configure an acceleration solution for Terraform Init.
Other methods
To accommodate different use cases, Alibaba Cloud offers services such as Auto Scaling, Alibaba Cloud Container Service for Kubernetes (ACK), and Auto Provisioning Group to help you efficiently create resources and automate resource operations and maintenance.
Auto Scaling
Auto Scaling is suitable for scenarios that require dynamic responses to fluctuations in business workload. It automatically combines pay-as-you-go and spot instances at an adjustable ratio and automatically replenishes new instances when existing ones are released. For more information, see Use spot instances to reduce costs in a scaling group.
Container Service for Kubernetes (ACK)
ACK is suitable for stateless and fault-tolerant applications where Kubernetes clusters require low-cost node pools. You can create spot instance node pools. For more information, see Best practices for spot instance node pools.
Auto Provisioning Group
Auto Provisioning Group provides a solution for rapidly provisioning a cluster of ECS instances. After a simple configuration, it can automatically provision a fleet of instances with different billing methods (pay-as-you-go and spot instances) and instance types across multiple zones, improving the efficiency of bulk instance provisioning. For more information, see Auto Provisioning Group configuration example.