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.
NoteIf 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
-
Go to the instance creation page and select the Custom Launch tab.
-
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.
WarningSpot 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.
NoteA spot instance in economical mode may fail to restart due to insufficient inventory or a market price above your bid.
-
-
-
Review your configuration on the right side of the page, set usage options, and click Confirm Order.
Create via SDK
Prerequisites
-
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.
-
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
-
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.
-
Install the ECS SDK
Get the ECS SDK. This example uses Maven. For other methods, see Install the ECS Java SDK.
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
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
-
alicloud_vpc: Creates a VPC.
-
alicloud_vswitch: Creates a vSwitch in the VPC for subnet segmentation.
-
alicloud_security_group: Creates a security group named default and associates it with the VPC.
-
alicloud_instance: Creates an ECS instance.
-
alicloud_security_group_rule: Defines security group rules.
Procedure
-
Open https://shell.aliyun.com and log on to Cloud Shell.
For other ways to use Cloud Shell, see Use Cloud Shell.
-
Create a project folder named terraform and enter the directory.
mkdir terraform cd terraform -
Create a configuration file named main.tf with the following content:
-
Run
terraform initto initialize the configuration.
-
Run
terraform apply. When prompted, enteryesand press Enter. If the following message appears, your spot instance is created.
-
Run
terraform showto view details of the created resources.
Clean up resources
To release resources created by Terraform, run the following command. See Common commands.
terraform destroy
References
-
For an introduction to Terraform, see Terraform overview.
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.