

# Spot Instances
<a name="using-spot-instances"></a>

A Spot Instance is an instance that uses spare EC2 capacity that is available for less than the On-Demand price. Because Spot Instances enable you to request unused EC2 instances at steep discounts, you can lower your Amazon EC2 costs significantly. The hourly price for a Spot Instance is called a Spot price. The Spot price of each instance type in each Availability Zone is set by Amazon EC2, and is adjusted gradually based on the long-term supply of and demand for Spot Instances. Your Spot Instance runs whenever capacity is available.

Spot Instances are a cost-effective choice if you can be flexible about when your applications run and if your applications can be interrupted. For example, Spot Instances are well-suited for data analysis, batch jobs, background processing, and optional tasks. For more information, see [Amazon EC2 Spot Instances](http://www.amazonaws.cn/ec2/spot/).

For a comparison of the different purchasing options for EC2 instances, see [Amazon EC2 billing and purchasing options](instance-purchasing-options.md).

## Concepts
<a name="spot-features"></a>

Before you get started with Spot Instances, you should be familiar with the following concepts:
+ *Spot capacity pool* – A set of unused EC2 instances with the same instance type (for example, `m5.large`) and Availability Zone.
+ *Spot price* – The current price of a Spot Instance per hour.
+ *Spot Instance request* – Requests a Spot Instance. When capacity is available, Amazon EC2 fulfills your request. A Spot Instance request is either *one-time* or *persistent*. Amazon EC2 automatically resubmits a persistent Spot Instance request after the Spot Instance associated with the request is interrupted.
+ *EC2 instance rebalance recommendation* – Amazon EC2 emits an instance rebalance recommendation signal to notify you that a Spot Instance is at an elevated risk of interruption. This signal provides an opportunity to proactively rebalance your workloads across existing or new Spot Instances without having to wait for the two-minute Spot Instance interruption notice.
+ *Spot Instance interruption* – Amazon EC2 terminates, stops, or hibernates your Spot Instance when Amazon EC2 needs the capacity back. Amazon EC2 provides a Spot Instance interruption notice, which gives the instance a two-minute warning before it is interrupted.

## Differences between Spot Instances and On-Demand Instances
<a name="key-differences-spot-on-demand"></a>

The following table lists the key differences between Spot Instances and [On-Demand Instances](ec2-on-demand-instances.md).


|  | Spot Instances | On-Demand Instances | 
| --- | --- | --- | 
|  Launch time  |  Can only be launched immediately if the Spot Instance request is active and capacity is available.  |  Can only be launched immediately if you make a manual launch request and capacity is available.  | 
|  Available capacity  |  If capacity is not available, the Spot Instance request continues to automatically make the launch request until capacity becomes available.  |  If capacity is not available when you make a launch request, you get an insufficient capacity error (ICE).  | 
|  Hourly price  |  The hourly price for Spot Instances varies based on long-term supply and demand.  |  The hourly price for On-Demand Instances is static.  | 
| Rebalance recommendation | The signal that Amazon EC2 emits for a running Spot Instance when the instance is at an elevated risk of interruption. | You determine when an On-Demand Instance is interrupted (stopped, hibernated, or terminated). | 
|  Instance interruption  |  You can stop and start an Amazon EBS-backed Spot Instance. In addition, Amazon EC2 can [interrupt](spot-interruptions.md) an individual Spot Instance if capacity is no longer available.   |  You determine when an On-Demand Instance is interrupted (stopped, hibernated, or terminated).  | 

## Pricing and savings
<a name="spot-pricing"></a>

You pay the Spot price for Spot Instances, which is set by Amazon EC2 and adjusted gradually based on the long-term supply of and demand for Spot Instances. Your Spot Instances run until you terminate them, capacity is no longer available, or your Amazon EC2 Auto Scaling group terminates them during [scale in](https://docs.amazonaws.cn/autoscaling/ec2/userguide/ec2-auto-scaling-lifecycle.html#as-lifecycle-scale-in).

If you or Amazon EC2 interrupts a running Spot Instance, you are charged for the seconds used or the full hour, or you receive no charge, depending on the operating system used and who interrupted the Spot Instance. For more information, see [Billing for interrupted Spot Instances](billing-for-interrupted-spot-instances.md).

Spot Instances are not covered by Savings Plans. If you have a Savings Plans, it does not provide additional savings on top of the savings that you already get from using Spot Instances. Furthermore, your spend on Spot Instances does not apply the commitments in your Compute Savings Plans.

### View prices
<a name="spot-pricing-view-prices"></a>

To view the current (updated every five minutes) lowest Spot price per Amazon Web Services Region and instance type, see the [Amazon EC2 Spot Instances Pricing](http://www.amazonaws.cn/ec2/spot/pricing/) page.

To view the Spot price history for the past three months, use the Amazon EC2 console or the [describe-spot-price-history](https://docs.amazonaws.cn/cli/latest/reference/ec2/describe-spot-price-history.html) command. For more information, see [View Spot Instance pricing history](using-spot-instances-history.md).

We independently map Availability Zones to codes for each Amazon Web Services account. Therefore, you can get different results for the same Availability Zone code (for example, `us-west-2a`) between different accounts.

### View savings
<a name="spot-pricing-view-savings"></a>

You can view the savings made from using Spot Instances for a single [Spot Fleet](Fleets.md) or for all Spot Instances. You can view the savings made in the last hour or the last three days, and you can view the average cost per vCPU hour and per memory (GiB) hour. Savings are estimated and may differ from actual savings because they do not include the billing adjustments for your usage. For more information about viewing savings information, see [Savings from purchasing Spot Instances](spot-savings.md).

### View billing
<a name="spot-pricing-view-billing"></a>

Your bill provides details about your service usage. For more information, see [Viewing your bill](https://docs.amazonaws.cn/awsaccountbilling/latest/aboutv2/getting-viewing-bill.html) in the *Amazon Billing User Guide*.

# Best practices for Amazon EC2 Spot
<a name="spot-best-practices"></a>

Amazon EC2 provides access to spare EC2 compute capacity in the Amazon Web Services Cloud through Spot Instances at savings of up to 90% compared to On-Demand prices. The only difference between On-Demand Instances and Spot Instances is that Spot Instances can be interrupted by Amazon EC2, with two minutes of notice, if Amazon EC2 needs to reclaim the capacity. To ensure the best experience with Spot Instances, it's important to understand and apply best practices for their use.

Spot Instances are recommended for stateless, fault-tolerant, flexible applications. For example, Spot Instances work well for big data, containerized workloads, CI/CD, stateless web servers, high performance computing (HPC), and rendering workloads.

While running, Spot Instances are exactly the same as On-Demand Instances. However, Spot does not guarantee that you can keep your running instances long enough to finish your workloads. Spot also does not guarantee that you can get immediate availability of the instances that you are looking for, or that you can always get the aggregate capacity that you requested. Moreover, Spot Instance interruptions and capacity can change over time because Spot Instance availability varies based on supply and demand, and past performance isn’t a guarantee of future results.

Spot Instances are not suitable for workloads that are inflexible, stateful, fault-intolerant, or tightly coupled between instance nodes. We do not recommend Spot Instances for workloads that are intolerant of occasional periods when the entire target capacity is not completely available. While following Spot best practices to be flexible about instance types and Availability Zones provides the best chance for high availability, there are no guarantees that capacity will be available, because surges in demand for On-Demand Instances can disrupt workloads on Spot Instances.

We strongly discourage using Spot Instances for these workloads or attempting to fail over to On-Demand Instances to handle interruptions or periods of unavailability. Failing over to On-Demand Instances can inadvertently drive interruptions for your other Spot Instances. In addition if Spot Instances for a combination of instance type and Availability Zone get interrupted, it might become difficult for you to get On-Demand Instances with that same combination.

Regardless of whether you're an experienced Spot user or new to Spot Instances, if you are currently experiencing issues with Spot Instance interruptions or availability, we recommend that you follow these best practices to have the best experience using the Spot service.

**Topics**
+ [

## Prepare individual instances for interruptions
](#prep-instances-for-interruptions)
+ [

## Be flexible about instance types and Availability Zones
](#be-instance-type-flexible)
+ [

## Use attribute-based instance type selection
](#use-attribute-based-instance-type-selection)
+ [

## Use Spot placement scores to identify optimal Regions and Availability Zones
](#use-spot-placement-scores-to-identify-optimal-regions-and-availability-zones)
+ [

## Use EC2 Auto Scaling groups or EC2 Fleet to manage your aggregate capacity
](#use-sf-asg-for-aggregate-capacity)
+ [

## Use the price and capacity optimized allocation strategy
](#use-capacity-optimized-allocation-strategy)
+ [

## Use integrated Amazon services to manage your Spot Instances
](#use-integrated-aws-services)
+ [

## Which is the best Spot request method to use?
](#which-spot-request-method-to-use)

## Prepare individual instances for interruptions
<a name="prep-instances-for-interruptions"></a>

The best way for you to gracefully handle Spot Instance interruptions is to architect your application to be fault-tolerant. To accomplish this, you can take advantage of EC2 instance rebalance recommendations and Spot Instance interruption notices.

An EC2 Instance rebalance recommendation is a signal that notifies you when a Spot Instance is at an elevated risk of interruption. The signal gives you the opportunity to proactively manage the Spot Instance in advance of the two-minute Spot Instance interruption notice. You can decide to rebalance your workload to new or existing Spot Instances that are not at an elevated risk of interruption. We've made it easy for you to use this signal by using the Capacity Rebalancing feature in Auto Scaling groups and EC2 Fleet. 

A Spot Instance interruption notice is a warning that is issued two minutes before Amazon EC2 interrupts a Spot Instance. If your workload is "time-flexible," you can configure your Spot Instances to be stopped or hibernated, instead of being terminated, when they are interrupted. Amazon EC2 automatically stops or hibernates your Spot Instances on interruption, and automatically resumes the instances when we have available capacity.

We recommend that you create a rule in [Amazon EventBridge](https://docs.amazonaws.cn/eventbridge/index.html) that captures the rebalance recommendations and interruption notifications, and then triggers a checkpoint for the progress of your workload or gracefully handles the interruption. For more information, see [Monitor rebalance recommendation signals](rebalance-recommendations.md#monitor-rebalance-recommendations). For a detailed example that walks you through how to create and use event rules, see [Taking Advantage of Amazon EC2 Spot Instance Interruption Notices](https://amazonaws-china.com/blogs/compute/taking-advantage-of-amazon-ec2-spot-instance-interruption-notices/).

For more information, see [EC2 instance rebalance recommendations](rebalance-recommendations.md) and [Spot Instance interruptions](spot-interruptions.md).

## Be flexible about instance types and Availability Zones
<a name="be-instance-type-flexible"></a>

A Spot capacity pool is a set of unused EC2 instances with the same instance type (for example, `m5.large`) and Availability Zone (for example, us-east-1a). You should be flexible about which instance types you request and in which Availability Zones you can deploy your workload. This gives Spot a better chance to find and allocate your required amount of compute capacity. For example, don't just ask for `c5.large` if you'd be willing to use larges from the c4, m5, and m4 families.

Depending on your specific needs, you can evaluate which instance types you can be flexible across to fulfill your compute requirements. If a workload can be vertically scaled, you should include larger instance types (more vCPUs and memory) in your requests. If you can only scale horizontally, you should include older generation instance types because they are less in demand from On-Demand customers.

A good rule of thumb is to be flexible across at least 10 instance types for each workload. In addition, make sure that all Availability Zones are configured for use in your VPC and selected for your workload.

## Use attribute-based instance type selection
<a name="use-attribute-based-instance-type-selection"></a>

With attribute-based instance type selection, you can specify instance attributes—such as vCPUs, memory, and storage—for the workload you want to run. EC2 Auto Scaling or EC2 Fleet will then automatically identify and launch instances that match your specified attributes. This removes the effort required to manually select specific instance types, which requires an in-depth understanding of each instance type's offering.

Moreover, attribute-based instance type selection enables you to automatically use newly released instance types as they become available. This ensures seamless access to an increasingly broad range of Spot Instance capacity.

Attribute-based instance type selection is ideal for workloads and frameworks that can be flexible about the instance types they run on, such as High Performance Computing (HPC) and big data workloads.

For more information, see [Create mixed instances group using attribute-based instance type selection](https://docs.amazonaws.cn/autoscaling/ec2/userguide/create-mixed-instances-group-attribute-based-instance-type-selection.html) in the *Amazon EC2 Auto Scaling User Guide* and [Specify attributes for instance type selection for EC2 Fleet or Spot Fleet](ec2-fleet-attribute-based-instance-type-selection.md) in this guide.

## Use Spot placement scores to identify optimal Regions and Availability Zones
<a name="use-spot-placement-scores-to-identify-optimal-regions-and-availability-zones"></a>

Spot Instances are unused EC2 capacity, and this capacity fluctuates based on EC2 supply and demand. As a result, you might not always get the exact Spot capacity that you require in a specific location at a specific time. To mitigate this unpredictability, you can use the Spot placement score feature. This feature provides recommendations for Regions or Availability Zones that are more likely to have sufficient capacity to meet your Spot capacity needs without requiring you to launch Spot Instances in those locations first.

Spot placement score is best used for workloads that can be flexible about the instance types and the Region or Availability Zone they can use. All you need to do is specify the Spot capacity that you need, your instance type requirements, and whether you want a recommendations for Regions or Availability Zones. In return, you receive a score ranging from 1 to 10 for each Region or Availability Zone, indicating the likelihood of successfully provisioning your requested Spot capacity in that location. A score of 10 indicates that your Spot request is highly likely to succeed.

It's important to note that a Spot placement score is a point-in-time recommendation, because capacity can vary over time. It does not guarantee available capacity or predict the risk of interruption.

You can use the Spot placement score feature in the Amazon EC2 console, Amazon CLI, or an SDK. For more information, see [Spot placement score](spot-placement-score.md). 

## Use EC2 Auto Scaling groups or EC2 Fleet to manage your aggregate capacity
<a name="use-sf-asg-for-aggregate-capacity"></a>

Spot enables you to think in terms of aggregate capacity—in units that include vCPUs, memory, storage, or network throughput—rather than thinking in terms of individual instances. Auto Scaling groups and EC2 Fleet enable you to launch and maintain a target capacity, and to automatically request resources to replace any that are disrupted or manually terminated. When you configure an Auto Scaling group or an EC2 Fleet, you need only specify the instance types and target capacity based on your application needs. For more information, see [Auto Scaling groups](https://docs.amazonaws.cn/autoscaling/ec2/userguide/auto-scaling-groups.html) in the *Amazon EC2 Auto Scaling User Guide* and [Create an EC2 Fleet](create-ec2-fleet.md) in this user guide.

## Use the price and capacity optimized allocation strategy
<a name="use-capacity-optimized-allocation-strategy"></a>

Allocation strategies in Auto Scaling groups help you to provision your target capacity without the need to manually look for the Spot capacity pools with spare capacity. We recommend using the `price-capacity-optimized` strategy because this strategy automatically provisions instances from the most-available Spot capacity pools that also have the lowest possible price. You can also take advantage of the `price-capacity-optimized` allocation strategy in EC2 Fleet. Because your Spot Instance capacity is sourced from pools with optimal capacity, this decreases the possibility that your Spot Instances are reclaimed. For more information, see [Allocation strategies for multiple instance types](https://docs.amazonaws.cn/autoscaling/ec2/userguide/allocation-strategies.html) in the *Amazon EC2 Auto Scaling User Guide* and [When workloads have a high cost of interruption](ec2-fleet-allocation-strategy.md#ec2-fleet-strategy-capacity-optimized) in this user guide.

## Use integrated Amazon services to manage your Spot Instances
<a name="use-integrated-aws-services"></a>

Other Amazon services integrate with Spot to reduce overall compute costs without the need to manage the individual instances or fleets. We recommend that you consider the following solutions for your applicable workloads: Amazon EMR, Amazon Elastic Container Service, Amazon Batch, Amazon Elastic Kubernetes Service, Amazon SageMaker AI, Amazon Elastic Beanstalk, and Amazon GameLift Servers. To learn more about Spot best practices with these services, see the [Amazon EC2 Spot Instances Workshops Website](https://ec2spotworkshops.com/).

## Which is the best Spot request method to use?
<a name="which-spot-request-method-to-use"></a>

Use the following table to determine which API to use when requesting Spot Instances.


****  

| API | When to use? | Use case | Should I use this API? | 
| --- | --- | --- | --- | 
|  [CreateAutoScalingGroup](https://docs.amazonaws.cn/autoscaling/ec2/APIReference/API_CreateAutoScalingGroup.html)  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/spot-best-practices.html)  |  Create an Auto Scaling group that manages the lifecycle of your instances while maintaining the desired number of instances. Supports horizontal scaling (adding more instances) between specified minimum and maximum limits.  | Yes | 
| [CreateFleet](https://docs.amazonaws.cn/AWSEC2/latest/APIReference/API_CreateFleet.html) |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/spot-best-practices.html)  |  Create a fleet of both On-Demand Instances and Spot Instances in a single request, with multiple launch specifications that vary by instance type, AMI, Availability Zone, or subnet. The Spot Instance allocation strategy defaults to `lowest-price` per unit, but you can change it to `price-capacity-optimized`, `capacity-optimized`, or `diversified`.  |  Yes – in `instant` mode if you don’t need auto scaling  | 
| [RunInstances](https://docs.amazonaws.cn/AWSEC2/latest/APIReference/API_RunInstances.html) |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/spot-best-practices.html)  |  Launch a specified number of instances using an AMI and one instance type.  |  No – because RunInstances does not allow mixed instance types in a single request  | 
| [RequestSpotFleet](https://docs.amazonaws.cn/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/spot-best-practices.html)  |  DO NOT USE. RequestSpotFleet is legacy API with no planned investment.   | No | 
| [RequestSpotInstances](https://docs.amazonaws.cn/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/spot-best-practices.html)  |  DO NOT USE. RequestSpotInstances is legacy API with no planned investment.   | No | 

# How Spot Instances work
<a name="how-spot-instances-work"></a>

To launch a Spot Instance, either you create a *Spot Instance request*, or Amazon EC2 creates a Spot Instance request on your behalf. The Spot Instance launches when the Spot Instance request is fulfilled.

You can launch a Spot Instance using several different services. For more information, see [Getting Started with Amazon EC2 Spot Instances](https://www.amazonaws.cn/ec2/spot/getting-started/). In this user guide, we describe the following ways to launch a Spot Instance using EC2:
+ You can create a Spot Instance request by using the [launch instance wizard](ec2-launch-instance-wizard.md) in the Amazon EC2 console or the [run-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/run-instances.html) command. For more information, see [Manage your Spot Instances](using-spot-instances-request.md).
+ You can create an EC2 Fleet, in which you specify the desired number of Spot Instances. Amazon EC2 creates a Spot Instance request on your behalf for every Spot Instance that is specified in the EC2 Fleet. For more information, see [Create an EC2 Fleet](create-ec2-fleet.md).
+ You can create a Spot Fleet request, in which you specify the desired number of Spot Instances. Amazon EC2 creates a Spot Instance request on your behalf for every Spot Instance that is specified in the Spot Fleet request. For more information, see [Create a Spot Fleet](create-spot-fleet.md).

Your Spot Instance launches if there is available capacity. Your Spot Instance runs until you stop or terminate it, or until Amazon EC2 interrupts it (known as a *Spot Instance interruption*). Amazon EC2 can stop, terminate, or hibernate a Spot Instance when it interrupts it.

When you use Spot Instances, you must be prepared for interruptions. Amazon EC2 can interrupt your Spot Instance when the demand for Spot Instances rises or when the supply of Spot Instances decreases. When Amazon EC2 interrupts a Spot Instance, it provides a Spot Instance interruption notice, which gives the instance a two-minute warning before Amazon EC2 interrupts it. You can't enable termination protection for Spot Instances. For more information, see [Spot Instance interruptions](spot-interruptions.md).

**Topics**
+ [

## Spot Instance request states
](#creating-spot-request-status)
+ [

## Launch Spot Instances in a launch group
](#spot-launch-group)
+ [

## Launch Spot Instances in an Availability Zone group
](#spot-az-group)
+ [

## Launch Spot Instances in a VPC
](#concepts-spot-instances-vpcs)
+ [

## Launch burstable performance instances
](#burstable-spot-instances)
+ [

## Launch on single-tenant hardware
](#spot-instance-tenancy)

## Spot Instance request states
<a name="creating-spot-request-status"></a>

A Spot Instance request can be in one of the following states:
+ `open` – The request is waiting to be fulfilled.
+ `active` – The request is fulfilled and has an associated Spot Instance.
+ `failed` – The request has one or more bad parameters.
+ `closed` – The Spot Instance was interrupted or terminated.
+ `disabled` – You stopped the Spot Instance.
+ `cancelled` – You canceled the request, or the request expired.

The following illustration represents the transitions between the request states. Notice that the transitions depend on the request type (one-time or persistent).

![\[Spot Instance request states.\]](http://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/images/spot_request_states.png)


A one-time Spot Instance request remains active until Amazon EC2 launches the Spot Instance, the request expires, or you cancel the request. If capacity is not available, your Spot Instance is terminated and the Spot Instance request is closed.

A persistent Spot Instance request remains active until it expires or you cancel it, even if the request is fulfilled. If capacity is not available, your Spot Instance is interrupted. After your instance is interrupted, when capacity becomes available again, the Spot Instance is started if stopped or resumed if hibernated. You can stop a Spot Instance and start it again if capacity is available. If the Spot Instance is terminated (irrespective of whether the Spot Instance is in a stopped or running state), the Spot Instance request is opened again and Amazon EC2 launches a new Spot Instance. For more information, see [Stop a Spot Instance](using-spot-instances-request.md#stopping-a-spot-instance), [Start a Spot Instance](using-spot-instances-request.md#starting-a-spot-instance), and [Terminate a Spot Instance](using-spot-instances-request.md#terminating-a-spot-instance).

You can track the status of your Spot Instance requests, as well as the status of the Spot Instances launched, through the status. For more information, see [Get the status of a Spot Instance request](spot-request-status.md).

## Launch Spot Instances in a launch group
<a name="spot-launch-group"></a>

Specify a launch group in your Spot Instance request to tell Amazon EC2 to launch a set of Spot Instances only if it can launch them all. In addition, if the Spot service must terminate one of the instances in a launch group, it must terminate them all. However, if you terminate one or more of the instances in a launch group, Amazon EC2 does not terminate the remaining instances in the launch group.

Although this option can be useful, adding this constraint can decrease the chances that your Spot Instance request is fulfilled and increase the chances that your Spot Instances are terminated. For example, your launch group includes instances in multiple Availability Zones. If capacity in one of these Availability Zones decreases and is no longer available, then Amazon EC2 terminates all instances for the launch group.

If you create another successful Spot Instance request that specifies the same (existing) launch group as an earlier successful request, then the new instances are added to the launch group. Subsequently, if an instance in this launch group is terminated, all instances in the launch group are terminated, which includes instances launched by the first and second requests.

## Launch Spot Instances in an Availability Zone group
<a name="spot-az-group"></a>

Specify an Availability Zone group in your Spot Instance request to tell Amazon EC2 to launch a set of Spot Instances in the same Availability Zone. Amazon EC2 need not interrupt all instances in an Availability Zone group at the same time. If Amazon EC2 must interrupt one of the instances in an Availability Zone group, the others remain running.

Although this option can be useful, adding this constraint can lower the chances that your Spot Instance request is fulfilled.

If you specify an Availability Zone group but don't specify an Availability Zone in the Spot Instance request, the result depends on the network you specified.

**Default VPC**  
Amazon EC2 uses the Availability Zone for the specified subnet. If you don't specify a subnet, it selects an Availability Zone and its default subnet, but not necessarily the lowest-priced zone. If you deleted the default subnet for an Availability Zone, then you must specify a different subnet.

**Nondefault VPC**  
Amazon EC2 uses the Availability Zone for the specified subnet.

## Launch Spot Instances in a VPC
<a name="concepts-spot-instances-vpcs"></a>

You specify a subnet for your Spot Instances the same way that you specify a subnet for your On-Demand Instances.
+ [Default VPC] If you want your Spot Instance launched in a specific low-priced Availability Zone, you must specify the corresponding subnet in your Spot Instance request. If you do not specify a subnet, Amazon EC2 selects one for you, and the Availability Zone for this subnet might not have the lowest Spot price.
+ [Nondefault VPC] You must specify the subnet for your Spot Instance.

## Launch burstable performance instances
<a name="burstable-spot-instances"></a>

The T instance types are [burstable performance instances](burstable-performance-instances.md). If you launch your Spot Instances using a burstable performance instance type, and if you plan to use your burstable performance Spot Instances immediately and for a short duration, with no idle time for accruing CPU credits, we recommend that you launch them in [Standard mode](burstable-performance-instances-standard-mode.md) to avoid paying higher costs. If you launch burstable performance Spot Instances in [Unlimited mode](burstable-performance-instances-unlimited-mode.md) and burst CPU immediately, you'll spend surplus credits for bursting. If you use the instance for a short duration, the instance doesn't have time to accrue CPU credits to pay down the surplus credits, and you are charged for the surplus credits when you terminate the instance.

Unlimited mode is suitable for burstable performance Spot Instances only if the instance runs long enough to accrue CPU credits for bursting. Otherwise, paying for surplus credits makes burstable performance Spot Instances more expensive than using other instances. For more information, see [When to use unlimited mode versus fixed CPU](burstable-performance-instances-unlimited-mode-concepts.md#when-to-use-unlimited-mode).

T2 instances, when configured in [Standard mode](burstable-performance-instances-standard-mode.md), get [launch credits](burstable-performance-instances-standard-mode-concepts.md#launch-credits). T2 instances are the only burstable performance instances that get launch credits. Launch credits are meant to provide a productive initial launch experience for T2 instances by providing sufficient compute resources to configure the instance. Repeated launches of T2 instances to access new launch credits is not permitted. If you require sustained CPU, you can earn credits (by idling over some period), use [Unlimited mode](burstable-performance-instances-unlimited-mode.md) for T2 Spot Instances, or use an instance type with dedicated CPU.

## Launch on single-tenant hardware
<a name="spot-instance-tenancy"></a>

You can run a Spot Instance on single-tenant hardware. Dedicated Spot Instances are physically isolated from instances that belong to other Amazon accounts. For more information, see [Amazon EC2 Dedicated Instances](dedicated-instance.md) and the [Amazon EC2 Dedicated Instances](http://www.amazonaws.cn/ec2/pricing/dedicated-instances/).

To run a Dedicated Spot Instance, do one of the following:
+ Specify a tenancy of `dedicated` when you create the Spot Instance request. For more information, see [Manage your Spot Instances](using-spot-instances-request.md).
+ Request a Spot Instance in a VPC with an instance tenancy of `dedicated`. For more information, see [Launch Dedicated Instances into a VPC with default tenancy](dedicatedinstancesintovpc.md). You can't request a Spot Instance with a tenancy of `default` if you request it in a VPC with an instance tenancy of `dedicated`.

All instance families support Dedicated Spot Instances except T instances. For each supported instance family, only the largest instance size or metal size supports Dedicated Spot Instances.

# View Spot Instance pricing history
<a name="using-spot-instances-history"></a>

Spot Instance prices are set by Amazon EC2 and adjust gradually based on long-term trends in supply and demand for Spot Instance capacity.

When your Spot request is fulfilled, your Spot Instances launch at the current Spot price, not exceeding the On-Demand price. You can view the Spot price history for the last 90 days, filtering by instance type, operating system, and Availability Zone.

For the *current* Spot Instance prices, see [Amazon EC2 Spot Instances Pricing](https://www.amazonaws.cn/ec2/spot/pricing/).

------
#### [ Console ]

**To view the Spot price history**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Spot Requests**.

1. Choose **Pricing history**. 

1. For **Graph**, choose to compare the price history by **Availability Zones** or by **Instance Types**.
   + If you choose **Availability Zones**, then choose the **Instance type**, operating system (**Platform**), and **Date range** for which to view the price history.
   + If you choose **Instance Types**, then choose up to five **Instance type(s)**, the **Availability Zone**, operating system (**Platform**), and **Date range** for which to view the price history.

   The following screenshot shows a price comparison for different instance types.  
![\[The Spot Instance pricing history tool in the Amazon EC2 console.\]](http://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/images/spot-instance-pricing-history.png)

1. Hover (move your pointer) over the graph to display the prices at specific times in the selected date range. The prices are displayed in the information blocks above the graph. The price displayed in the top row shows the price on a specific date. The price displayed in the second row shows the average price over the selected date range.

1. To display the price per vCPU, toggle on **Display normalized prices**. To display the price for the instance type, toggle off **Display normalized prices**.

------
#### [ Amazon CLI ]

**To view the Spot price history**  
Use the following [describe-spot-price-history](https://docs.amazonaws.cn/cli/latest/reference/ec2/describe-spot-price-history.html) command.

```
aws ec2 describe-spot-price-history \
    --instance-types c6i.xlarge \
    --product-descriptions "Linux/UNIX" \
    --start-time 2025-04-01T00:00:00 \
    --end-time 2025-04-02T00:00:0
```

------
#### [ PowerShell ]

**To view the Spot price history**  
Use the [Get-EC2SpotPriceHistory](https://docs.amazonaws.cn/powershell/latest/reference/items/Get-EC2SpotPriceHistory.html) cmdlet.

```
Get-EC2SpotPriceHistory `
    -InstanceType c6i.xlarge `
    -ProductDescription "Linux/UNIX" `
    -UtcStartTime 2025-04-01T00:00:00 `
    -UtcEndTime 2025-04-02T00:00:0
```

------

# Savings from purchasing Spot Instances
<a name="spot-savings"></a>

You can view the usage and savings information for Spot Instances at the per-fleet level, or for all running Spot Instances. At the per-fleet level, the usage and savings information includes all instances launched and terminated by the fleet. You can view this information from the last hour or the last three days.

The following screenshot from the **Savings** section shows the Spot usage and savings information for a Spot Fleet.

![\[The Savings section on the Spot Fleet details page.\]](http://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/images/spot-savings.png)


You can view the following usage and savings information:
+ **Spot Instances** – The number of Spot Instances launched and terminated by the Spot Fleet. When viewing the savings summary, the number represents all your running Spot Instances.
+ **vCPU-hours** – The number of vCPU hours used across all the Spot Instances for the selected time frame.
+ **Mem(GiB)-hours** – The number of GiB hours used across all the Spot Instances for the selected time frame.
+ **On-Demand total** – The total amount you would've paid for the selected time frame had you launched these instances as On-Demand Instances.
+ **Spot total** – The total amount to pay for the selected time frame.
+ **Savings** – The percentage that you are saving by not paying the On-Demand price.
+ **Average cost per vCPU-hour** – The average hourly cost of using the vCPUs across all the Spot Instances for the selected time frame, calculated as follows: **Average cost per vCPU-hour** = **Spot total** / **vCPU-hours**.
+ **Average cost per mem(GiB)-hour** – The average hourly cost of using the GiBs across all the Spot Instances for the selected time frame, calculated as follows: **Average cost per mem(GiB)-hour** = **Spot total** / **Mem(GiB)-hours**.
+ **Details** table – The different instance types (the number of instances per instance type is in parentheses) that comprise the Spot Fleet. When viewing the savings summary, these comprise all your running Spot Instances.

Savings information can only be viewed using the Amazon EC2 console.

**To view the savings information for a Spot Fleet**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. On the navigation pane, choose **Spot Requests**.

1. Select the ID of a Spot Fleet request and scroll to the **Savings** section.

   Alternatively, select the checkbox next to the Spot Fleet request ID and choose the **Savings** tab.

1. By default, the page displays usage and savings information for the last three days. You can choose **last hour** or the **last three days**. For Spot Fleets that were launched less than an hour ago, the page shows the estimated savings for the hour.

**To view the savings information for all running Spot Instances**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. On the navigation pane, choose **Spot Requests**.

1. Choose **Savings summary**.

# Create a Spot Instance request
<a name="spot-requests"></a>

To use Spot Instances, you create a Spot Instance request that includes the desired number of instances, the instance type, and the Availability Zone. If capacity is available, Amazon EC2 fulfills your request immediately. Otherwise, Amazon EC2 waits until your request can be fulfilled or until you cancel the request.

You can use the [launch instance wizard](ec2-launch-instance-wizard.md) in the Amazon EC2 console or the [run-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/run-instances.html) command to request a Spot Instance in the same way that you can launch an On-Demand Instance. This method is only recommended for the following reasons:
+ You're already using the [launch instance wizard](ec2-launch-instance-wizard.md) or [run-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/run-instances.html) command to launch On-Demand Instances, and you simply want to change to launching Spot Instances by changing a single parameter.
+ You do not need multiple instances with different instance types.

This method is generally not recommended for launching Spot Instances because you can't specify multiple instance types, and you can't launch Spot Instances and On-Demand Instances in the same request. For the preferred methods for launching Spot Instances, which include launching a *fleet* that includes Spot Instances and On-Demand Instances with multiple instance types, see [Which is the best Spot request method to use?](spot-best-practices.md#which-spot-request-method-to-use)

If you request multiple Spot Instances at one time, Amazon EC2 creates separate Spot Instance requests so that you can track the status of each request separately. For more information about tracking Spot Instance requests, see [Get the status of a Spot Instance request](spot-request-status.md).

------
#### [ Console ]<a name="create-spot-instance-request-console-procedure"></a>

**To create a Spot Instance request**

Steps 1–9 are the same steps you'd use to launch an On-Demand Instance. At Step 10, you configure the Spot Instance request.

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation bar at the top of the screen, select a Region.

1. From the Amazon EC2 console dashboard, choose **Launch instance**.

1. (Optional) Under **Name and tags**, you can name your instance, and tag the Spot Instance request, the instance, the volumes, and the elastic graphics. For information about tags, see [Tag your Amazon EC2 resources](Using_Tags.md).

   1. For **Name**, enter a descriptive name for your instance.

      The instance name is a tag, where the key is **Name**, and the value is the name that you specify. If you don't specify a name, the instance can be identified by its ID, which is automatically generated when you launch the instance.

   1. To tag the Spot Instance request, the instance, the volumes, and the elastic graphics, choose **Add additional tags**. Choose **Add tag**, and then enter a key and value, and select the resource type to tag. Choose **Add tag** again for each additional tag to add.

1. Under **Application and OS Images (Amazon Machine Image)**, choose the operating system (OS) for your instance, and then select an AMI. For more information, see [Application and OS Images (Amazon Machine Image)](ec2-instance-launch-parameters.md#liw-ami).

1. Under **Instance type**, select the instance type that meets your requirements for the hardware configuration and size of your instance. For more information, see [Instance type](ec2-instance-launch-parameters.md#liw-instance-type).

1. Under **Key pair (login)**, choose an existing key pair, or choose **Create new key pair** to create a new one. For more information, see [Amazon EC2 key pairs and Amazon EC2 instances](ec2-key-pairs.md).
**Important**  
If you choose the **Proceed without key pair (Not recommended)** option, you won't be able to connect to the instance unless you choose an AMI that is configured to allow users another way to log in.

1. Under **Network settings**, use the default settings, or choose **Edit** to configure the network settings as necessary.

   Security groups form part of the network settings, and define firewall rules for your instance. These rules specify which incoming network traffic is delivered to your instance.

   For more information, see [Network settings](ec2-instance-launch-parameters.md#liw-network-settings).

1. The AMI you selected includes one or more volumes of storage, including the root device volume. Under **Configure storage**, you can specify additional volumes to attach to the instance by choosing **Add new volume**. For more information, see [Configure storage](ec2-instance-launch-parameters.md#liw-storage).

1. Under **Advanced details**, configure the Spot Instance request as follows:

   1. Under **Purchasing option**, select the **Request Spot Instances** checkbox.

   1. You can either keep the default configuration for the Spot Instance request, or choose **Customize** (at the right) to specify custom settings for your Spot Instance request.

      When you choose **Customize**, the following fields appear.

      1. **Maximum price**: You can request Spot Instances at the Spot price, capped at the On-Demand price, or you can specify the maximum amount you're willing to pay.
**Warning**  
If you specify a maximum price, your instances will be interrupted more frequently than if you choose **No maximum price**.  
If you specify a maximum price, it must be more than USD \$10.001. Specifying a value below USD \$10.001 will result in a failed launch.
         + **No maximum price**: Your Spot Instance will launch at the current Spot price. The price will never exceed the On-Demand price. (Recommended)
         + **Set your maximum price (per instance/hour)**: You can specify the maximum amount you're willing pay.
           + If you specify a maximum price that is less than the current Spot price, your Spot Instance will not launch.
           + If you specify a maximum price that is more than the current Spot price, your Spot Instance will launch and be charged at the current Spot price. After your Spot Instance is running, if the Spot price rises above your maximum price, Amazon EC2 interrupts your Spot Instance.
           + Regardless of the maximum price you specify, you will always be charged the current Spot price.

           To review Spot price trends, see [View Spot Instance pricing history](using-spot-instances-history.md).

      1. **Request type**: The Spot Instance request type that you choose determines what happens if your Spot Instance is interrupted.
         + **One-time**: Amazon EC2 places a one-time request for your Spot Instance. If your Spot Instance is interrupted, the request is not resubmitted.
         + **Persistent request**: Amazon EC2 places a persistent request for your Spot Instance. If your Spot Instance is interrupted, the request is resubmitted to replenish the interrupted Spot Instance.

         If you do not specify a value, the default is a one-time request.

      1. **Valid to**: The expiration date of a *persistent* Spot Instance request.

         This field is not supported for one-time requests. A *one-time* request remains active until all the instances in the request launch or you cancel the request. 
         + **No request expiry date**: The request remains active until you cancel it.
         + **Set your request expiry date**: The persistent request remains active until the date that you specify, or until you cancel it.

      1. **Interruption behavior**: The behavior that you choose determines what happens when a Spot Instance is interrupted.
         + For persistent requests, valid values are **Stop** and **Hibernate**. When an instance is stopped, charges for EBS volume storage apply.
**Note**  
Spot Instances now use the same hibernation functionality as On-Demand Instances. To enable hibernation, you can either choose **Hibernate** here, or you can choose **Enable** from the **Stop - Hibernate behavior** field, which appears lower down in the launch instance wizard. For the hibernation prerequisites, see [Prerequisites for EC2 instance hibernation](hibernating-prerequisites.md).
         + For one-time requests, only **Terminate** is valid.

         If you do not specify a value, the default is **Terminate**, which is not valid for a persistent Spot Instance request. If you keep the default and try to launch a persistent Spot Instance request, you'll get an error.

         For more information, see [Behavior of Spot Instance interruptions](interruption-behavior.md).

1. On the **Summary** panel, for **Number of instances**, enter the number of instances to launch.
**Note**  
Amazon EC2 creates a separate request for each Spot Instance.

1. On the **Summary** panel, review the details of your instance, and make any necessary changes. After you submit your Spot Instance request, you can't change the parameters of the request. You can navigate directly to a section in the launch instance wizard by choosing its link in the **Summary** panel. For more information, see [Summary](ec2-instance-launch-parameters.md#liw-summary).

1. When you're ready to launch your instance, choose **Launch instance**. 

   If the instance fails to launch or the state immediately goes to `terminated` instead of `running`, see [Troubleshoot Amazon EC2 instance launch issues](troubleshooting-launch.md).

------
#### [ Amazon CLI ]

**To create a Spot Instance request using run-instances**  
Use the [run-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/run-instances.html) command and specify the Spot Instance options in the `--instance-market-options` parameter as follows.

```
--instance-market-options file://spot-options.json
```

The following is the data structure to specify in the JSON file. You can also specify `ValidUntil` and `InstanceInterruptionBehavior`. If you do not specify a field in the data structure, the default value is used.

The following example creates a `persistent` request.

```
{
  "MarketType": "spot",
  "SpotOptions": {
    "SpotInstanceType": "persistent"
  }
}
```

**To create a Spot Instance request using request-spot-instances**

**Note**  
We strongly discourage using the [request-spot-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/request-spot-instances.html) command to request a Spot Instance because it is a legacy API with no planned investment. For more information, see [Which is the best Spot request method to use?](spot-best-practices.md#which-spot-request-method-to-use)

Use the [request-spot-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/request-spot-instances.html) command to create a one-time request.

```
aws ec2 request-spot-instances \
    --instance-count 5 \
    --type "one-time" \
    --launch-specification file://specification.json
```

Use the [request-spot-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/request-spot-instances.html) command to create a persistent request.

```
aws ec2 request-spot-instances \
    --instance-count 5 \
    --type "persistent" \
    --launch-specification file://specification.json
```

For example launch specification files to use with these commands, see [Spot Instance request example launch specifications](spot-request-examples.md). If you download a launch specification file from the Spot Requests console, you must use the [request-spot-fleet](https://docs.amazonaws.cn/cli/latest/reference/ec2/request-spot-fleet.html) command instead (the Spot Requests console specifies a Spot Instance request using a Spot Fleet).

------
#### [ PowerShell ]

**To create a Spot Instance request**  
Use the [New-EC2Instance](https://docs.amazonaws.cn/powershell/latest/reference/items/New-EC2Instance.html) cmdlet and specify the Spot Instance options using the `-InstanceMarketOption` parameter.

```
-InstanceMarketOptions $marketOptions
```

Create the data structure for the Spot Instance options as follows.

```
$spotOptions = New-Object Amazon.EC2.Model.SpotMarketOptions
$spotOptions.SpotInstanceType="persistent"
$marketOptions = New-Object Amazon.EC2.Model.InstanceMarketOptionsRequest
$marketOptions.MarketType = "spot"
$marketOptions.SpotOptions = $spotOptions
```

------

# Spot Instance request example launch specifications
<a name="spot-request-examples"></a>

The following examples show launch configurations that you can use with the [request-spot-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/request-spot-instances.html) command to create a Spot Instance request. For more information, see [Manage your Spot Instances](using-spot-instances-request.md).

**Important**  
We strongly discourage using the [request-spot-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/request-spot-instances.html) command to request a Spot Instance because it is a legacy API with no planned investment. For more information, see [Which is the best Spot request method to use?](spot-best-practices.md#which-spot-request-method-to-use)

**Topics**
+ [

## Example 1: Launch Spot Instances
](#spot-launch-specification1)
+ [

## Example 2: Launch Spot Instances in the specified Availability Zone
](#spot-launch-specification2)
+ [

## Example 3: Launch Spot Instances in the specified subnet
](#spot-launch-specification3)
+ [

## Example 4: Launch a Dedicated Spot Instance
](#spot-launch-specification4)

## Example 1: Launch Spot Instances
<a name="spot-launch-specification1"></a>

The following example does not include an Availability Zone or subnet. Amazon EC2 selects an Availability Zone for you. Amazon EC2 launches the instances in the default subnet of the selected Availability Zone.

```
{
  "ImageId": "ami-0abcdef1234567890",
  "KeyName": "my-key-pair",
  "SecurityGroupIds": [ "sg-1a2b3c4d5e6f7g8h9" ],
  "InstanceType": "m5.medium",
  "IamInstanceProfile": {
      "Arn": "arn:aws-cn:iam::123456789012:instance-profile/my-iam-role"
  }
}
```

## Example 2: Launch Spot Instances in the specified Availability Zone
<a name="spot-launch-specification2"></a>

The following example includes an Availability Zone. Amazon EC2 launches the instances in the default subnet of the specified Availability Zone.

```
{
  "ImageId": "ami-0abcdef1234567890",
  "KeyName": "my-key-pair",
  "SecurityGroupIds": [ "sg-1a2b3c4d5e6f7g8h9" ],
  "InstanceType": "m5.medium",
  "Placement": {
    "AvailabilityZone": "us-west-2a"
  },
  "IamInstanceProfile": {
      "Arn": "arn:aws-cn:iam::123456789012:instance-profile/my-iam-role"
  }
}
```

## Example 3: Launch Spot Instances in the specified subnet
<a name="spot-launch-specification3"></a>

The following example includes a subnet. Amazon EC2 launches the instances in the specified subnet. If the VPC is a nondefault VPC, the instance does not receive a public IPv4 address by default.

```
{
  "ImageId": "ami-0abcdef1234567890",
  "SecurityGroupIds": [ "sg-1a2b3c4d5e6f7g8h9" ],
  "InstanceType": "m5.medium",
  "SubnetId": "subnet-1a2b3c4d",
  "IamInstanceProfile": {
      "Arn": "arn:aws-cn:iam::123456789012:instance-profile/my-iam-role"
  }
}
```

To assign a public IPv4 address to an instance in a nondefault VPC, specify the `AssociatePublicIpAddress` field as shown in the following example. When you specify a network interface, you must include the subnet ID and security group ID using the network interface, rather than using the `SubnetId` and `SecurityGroupIds` fields shown in the previous code block.

```
{
  "ImageId": "ami-0abcdef1234567890",
  "KeyName": "my-key-pair",
  "InstanceType": "m5.medium",
  "NetworkInterfaces": [
    {
      "DeviceIndex": 0,
      "SubnetId": "subnet-1a2b3c4d5e6f7g8h9",
      "Groups": [ "sg-1a2b3c4d5e6f7g8h9" ],
      "AssociatePublicIpAddress": true
    }
  ],
  "IamInstanceProfile": {
      "Arn": "arn:aws-cn:iam::123456789012:instance-profile/my-iam-role"
  }
}
```

## Example 4: Launch a Dedicated Spot Instance
<a name="spot-launch-specification4"></a>

The following example requests Spot Instance with a tenancy of `dedicated`. A Dedicated Spot Instance must be launched in a VPC.

```
{
  "ImageId": "ami-0abcdef1234567890",
  "KeyName": "my-key-pair",
  "SecurityGroupIds": [ "sg-1a2b3c4d5e6f7g8h9" ],
  "InstanceType": "c5.8xlarge",
  "SubnetId": "subnet-1a2b3c4d5e6f7g8h9",
  "Placement": {
    "Tenancy": "dedicated"
  }
}
```

# Get the status of a Spot Instance request
<a name="spot-request-status"></a>

To help you track your Spot Instance requests and plan your use of Spot Instances, use the request status provided by Amazon EC2. For example, the request status can provide the reason why your Spot request isn't fulfilled yet, or list the constraints that are preventing the fulfillment of your Spot request.

At each step of the process—also called the Spot request *lifecycle*—specific events determine successive request states.

The following illustration shows how Spot Instance requests work. Notice that the request type (one-time or persistent) determines whether the request is opened again when Amazon EC2 interrupts a Spot Instance or if you stop a Spot Instance. If the request is persistent, the request is opened again after your Spot Instance is interrupted. If the request is persistent and you stop your Spot Instance, the request only opens after you start your Spot Instance.

![\[How Spot Instance requests work.\]](http://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/images/spot_lifecycle.png)


**Topics**
+ [

## Get request status information
](#get-spot-instance-request-status)
+ [

## Spot request status codes
](#spot-instance-request-status-understand)
+ [

## EC2 Spot Instance Request Fulfillment event
](#spot-request-fulfillment-event)
+ [

# State changes for a Spot request
](spot-instances-request-status-lifecycle.md)

## Get request status information
<a name="get-spot-instance-request-status"></a>

You can get status information for your Spot Instance request.

------
#### [ Console ]

**To get request status information**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Spot Requests** and select the Spot request.

1. To check the status, on the **Description** tab, check the **Status** field.

------
#### [ Amazon CLI ]

**To get request status information**  
Use the following [describe-spot-instance-requests](https://docs.amazonaws.cn/cli/latest/reference/ec2/describe-spot-instance-requests.html) command.

```
aws ec2 describe-spot-instance-requests --spot-instance-request-ids sir-0e54a519c9EXAMPLE
```

------
#### [ PowerShell ]

**To get request status information**  
Use the [Get-EC2SpotInstanceRequest](https://docs.amazonaws.cn/powershell/latest/reference/items/Get-EC2SpotInstanceRequest.html) cmdlet.

```
Get-EC2SpotInstanceRequest -SpotInstanceRequestId sir-0e54a519c9EXAMPLE
```

------

## Spot request status codes
<a name="spot-instance-request-status-understand"></a>

Spot request status information is composed of a status code, the update time, and a status message. Together, these help you determine the disposition of your Spot request.

The following are the Spot request status codes:

`az-group-constraint`  
Amazon EC2 cannot launch all the instances you requested in the same Availability Zone.

`bad-parameters`  
One or more parameters for your Spot request are not valid (for example, the AMI you specified does not exist). The status message indicates which parameter is not valid.

`canceled-before-fulfillment`  
The user canceled the Spot request before it was fulfilled.

`capacity-not-available`  
There is not enough capacity available for the instances that you requested.

`constraint-not-fulfillable`  
The Spot request can't be fulfilled because one or more constraints are not valid (for example, the Availability Zone does not exist). The status message indicates which constraint is not valid.

`fulfilled`  
The Spot request is `active`, and Amazon EC2 is launching your Spot Instances.

`instance-stopped-by-price`  
Your instance was stopped because the Spot price exceeded your maximum price.

`instance-stopped-by-user`  
Your instance was stopped because a user stopped the instance or ran the shutdown command from the instance.

`instance-stopped-no-capacity`  
Your instance was stopped due to EC2 capacity management needs.

`instance-terminated-by-price`  
Your instance was terminated because the Spot price exceeded your maximum price. If your request is persistent, the process restarts, so your request is pending evaluation.

`instance-terminated-by-schedule`  
Your Spot Instance was terminated at the end of its scheduled duration.

`instance-terminated-by-service`  
Your instance was terminated from a stopped state.

`instance-terminated-by-user` or `spot-instance-terminated-by-user`  
You terminated a Spot Instance that had been fulfilled, so the request state is `closed` (unless it's a persistent request) and the instance state is `terminated`.

`instance-terminated-launch-group-constraint`  
One or more of the instances in your launch group was terminated, so the launch group constraint is no longer fulfilled.

`instance-terminated-no-capacity`  
Your instance was terminated due to standard capacity management processes.

`launch-group-constraint`  
Amazon EC2 cannot launch all the instances that you requested at the same time. All instances in a launch group are started and terminated together.

`limit-exceeded`  
The limit on the number of EBS volumes or total volume storage was exceeded. For more information, see [Quotas for Amazon EBS](https://docs.amazonaws.cn/ebs/latest/userguide/ebs-resource-quotas.html) in the *Amazon EBS User Guide*.

`marked-for-stop`  
The Spot Instance is marked for stopping.

`marked-for-termination`  
The Spot Instance is marked for termination.

`not-scheduled-yet`  
The Spot request is not evaluated until the scheduled date.

`pending-evaluation`  
After you make a Spot Instance request, it goes into the `pending-evaluation` state while the system evaluates the parameters of your request.

`pending-fulfillment`  
Amazon EC2 is trying to provision your Spot Instances.

`placement-group-constraint`  
The Spot request can't be fulfilled yet because a Spot Instance can't be added to the placement group at this time.

`price-too-low`  
The request can't be fulfilled yet because your maximum price is below the Spot price. In this case, no instance is launched and your request remains `open`.

`request-canceled-and-instance-running`  
You canceled the Spot request while the Spot Instances are still running. The request is `cancelled`, but the instances remain `running`.

`schedule-expired`  
The Spot request expired because it was not fulfilled before the specified date.

`system-error`  
There was an unexpected system error. If this is a recurring issue, please contact Amazon Web Services Support for assistance.

## EC2 Spot Instance Request Fulfillment event
<a name="spot-request-fulfillment-event"></a>

When a Spot Instance request is fulfilled, Amazon EC2 sends an EC2 Spot Instance Request Fulfillment event to Amazon EventBridge. You can create a rule to take an action whenever this event occurs, such as invoking a Lambda function or notifying an Amazon SNS topic.

The following is example data for this event.

```
{
    "version": "0",
    "id": "01234567-1234-0123-1234-012345678901",
    "detail-type": "EC2 Spot Instance Request Fulfillment",
    "source": "aws.ec2",
    "account": "123456789012",
    "time": "yyyy-mm-ddThh:mm:ssZ",
    "region": "us-west-2",
    "resources": ["arn:aws-cn:ec2:us-west-2:123456789012:instance/i-1234567890abcdef0"],
    "detail": {
        "spot-instance-request-id": "sir-0e54a519c9EXAMPLE",
        "instance-id": "i-1234567890abcdef0"
    }
}
```

For more information, see the [Amazon EventBridge User Guide](https://docs.amazonaws.cn/eventbridge/latest/userguide/).

# State changes for a Spot request
<a name="spot-instances-request-status-lifecycle"></a>

The following diagram shows you the paths that your Spot request can follow throughout its lifecycle, from submission to termination. Each step is depicted as a node, and the status code for each node describes the status of the Spot request and Spot Instance.

![\[Life cycle of a Spot Instance request.\]](http://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/images/spot-request-status-diagram.png)


**Pending evaluation**  
As soon as you create a Spot Instance request, it goes into the `pending-evaluation` state unless one or more request parameters are not valid (`bad-parameters`).


| Status code | Request state | Instance state | 
| --- | --- | --- | 
| pending-evaluation | open | Not applicable | 
| bad-parameters | closed | Not applicable | 

**Holding**  
If one or more request constraints are valid but can't be met yet, or if there is not enough capacity, the request goes into a holding state waiting for the constraints to be met. The request options affect the likelihood of the request being fulfilled. For example, if there is no capacity, your request stays in a holding state until there is available capacity. If you specify an Availability Zone group, the request stays in a holding state until the Availability Zone constraint is met.

In the event of an outage of one of the Availability Zones, there is a chance that the spare EC2 capacity available for Spot Instance requests in other Availability Zones can be affected.


| Status code | Request state | Instance state | 
| --- | --- | --- | 
| capacity-not-available | open |  Not applicable  | 
| price-too-low | open |  Not applicable  | 
| not-scheduled-yet | open |  Not applicable  | 
| launch-group-constraint | open |  Not applicable  | 
| az-group-constraint | open |  Not applicable  | 
|  placement-group-constraint  |  open  |  Not applicable  | 
|  constraint-not-fulfillable  |  open  |  Not applicable  | 

**Pending evaluation/fulfillment-terminal**  
Your Spot Instance request can go to a `terminal` state if you create a request that is valid only during a specific time period and this time period expires before your request reaches the pending fulfillment phase. It might also happen if you cancel the request, or if a system error occurs.


| Status code | Request state | Instance state | 
| --- | --- | --- | 
|  schedule-expired  |  cancelled  |  Not applicable  | 
|  canceled-before-fulfillment ¹  |  cancelled  |  Not applicable  | 
|  bad-parameters  |  failed  |  Not applicable  | 
|  system-error  |  closed  |  Not applicable  | 

¹ If you cancel the request.

**Pending fulfillment**  
When the constraints you specified (if any) are met, your Spot request goes into the `pending-fulfillment` state.

At this point, Amazon EC2 is getting ready to provision the instances that you requested. If the process stops at this point, it is likely to be because it was canceled by the user before a Spot Instance was launched. It might also be because an unexpected system error occurred.


| Status code | Request state | Instance state | 
| --- | --- | --- | 
|  pending-fulfillment  |  open  |  Not applicable  | 

**Fulfilled**  
When all the specifications for your Spot Instances are met, your Spot request is fulfilled. Amazon EC2 launches the Spot Instances, which can take a few minutes. If a Spot Instance is hibernated or stopped when interrupted, it remains in this state until the request can be fulfilled again or the request is canceled.


| Status code | Request state | Instance state | 
| --- | --- | --- | 
|  fulfilled  |  active  |  pending → running  | 
|  fulfilled  |  active  |  stopped → running  | 

If you stop a Spot Instance, your Spot request goes into the `marked-for-stop` or `instance-stopped-by-user` state until the Spot Instance can be started again or the request is cancelled. 


| Status code | Request state | Instance state | 
| --- | --- | --- | 
|  marked-for-stop  | active |  stopping  | 
|  instance-stopped-by-user ¹  |  disabled or cancelled ²  |  stopped  | 

¹ A Spot Instance goes into the `instance-stopped-by-user` state if you stop the instance or run the shutdown command from the instance. After you've stopped the instance, you can start it again. On restart, the Spot Instance request returns to the `pending-evaluation` state and then Amazon EC2 launches a new Spot Instance when the constraints are met. 

² The Spot request state is `disabled` if you stop the Spot Instance but do not cancel the request. The request state is `cancelled` if your Spot Instance is stopped and the request expires.

**Fulfilled-terminal**  
Your Spot Instances continue to run as long as there is available capacity for your instance type, and you don't terminate the instance. If Amazon EC2 must terminate your Spot Instances, the Spot request goes into a terminal state. A request also goes into the terminal state if you cancel the Spot request or terminate the Spot Instances.


| Status code | Request state | Instance state | 
| --- | --- | --- | 
|  request-canceled-and-instance-running  |  cancelled  |  running  | 
|  marked-for-stop  |  active  |  running  | 
|  marked-for-termination  |  active  |  running  | 
|  instance-stopped-by-price  |  disabled  |  stopped  | 
|  instance-stopped-by-user  |  disabled  |  stopped  | 
|  instance-stopped-no-capacity  |  disabled  |  stopped  | 
|  instance-terminated-by-price  |  closed (one-time), open (persistent)  |  terminated  | 
|  instance-terminated-by-schedule  |  closed  |  terminated  | 
|  instance-terminated-by-service  |  cancelled  |  terminated  | 
|  instance-terminated-by-user  |  closed or cancelled ¹  |  terminated  | 
|  instance-terminated-no-capacity  |  closed (one-time), open (persistent)  |  running †  | 
|  instance-terminated-no-capacity  |  closed (one-time), open (persistent)  |  terminated  | 
|  instance-terminated-launch-group-constraint  |  closed (one-time), open (persistent)  |  terminated  | 

¹ The request state is `closed` if you terminate the instance but do not cancel the request. The request state is `cancelled` if you terminate the instance and cancel the request. Even if you terminate a Spot Instance before you cancel its request, there might be a delay before Amazon EC2 detects that your Spot Instance was terminated. In this case, the request state can either be `closed` or `cancelled`.

† When Amazon EC2 interrupts a Spot Instance if it needs the capacity back *and* the instance is configured to *terminate* on interruption, the status is immediately set to `instance-terminated-no-capacity` (it is not set to `marked-for-termination`). However, the instance remains in the `running` state for 2 minutes to reflect the 2-minute period when the instance receives the Spot Instance interruption notice. After 2 minutes, the instance state is set to `terminated`.

**Interruption experiments**  
You can use Amazon Fault Injection Service to initiate a Spot Instance interruption so that you can test how the applications on your Spot Instances respond. If Amazon FIS stops a Spot Instance, your Spot request enters the `marked-for-stop-by-experiment` state and then the `instance-stopped-by-experiment` state. If Amazon FIS terminates a Spot Instance, your Spot request enters the `instance-terminated-by-experiment` state. For more information, see [Initiate a Spot Instance interruption](initiate-a-spot-instance-interruption.md).


| Status code | Request state | Instance state | 
| --- | --- | --- | 
| marked-for-stop-by-experiment | active | running | 
| instance-stopped-by-experiment | disabled | stopped | 
| instance-terminated-by-experiment | closed | terminated | 

**Persistent requests**  
When your Spot Instances are terminated (either by you or Amazon EC2), if the Spot request is a persistent request, it returns to the `pending-evaluation` state and then Amazon EC2 can launch a new Spot Instance when the constraints are met.

# Tag Spot Instance requests
<a name="concepts-spot-instances-request-tags"></a>

To help categorize and manage your Spot Instance requests, you can tag them with custom metadata. You can assign a tag to a Spot Instance request when you create it, or afterward. You can assign tags using the Amazon EC2 console or a command line tool.

When you tag a Spot Instance request, the instances and volumes that are launched by the Spot Instance request are not automatically tagged. You need to explicitly tag the instances and volumes launched by the Spot Instance request. You can assign a tag to a Spot Instance and volumes during launch, or afterward.

For more information about how tags work, see [Tag your Amazon EC2 resources](Using_Tags.md).

**Topics**
+ [

## Prerequisites
](#tag-spot-request-prereqs)
+ [

## Tag a new Spot Instance request
](#tag-new-spot-instance-request)
+ [

## Tag an existing Spot Instance request
](#tag-existing-spot-instance-request)
+ [

## View Spot Instance request tags
](#view-spot-instance-request-tags)

## Prerequisites
<a name="tag-spot-request-prereqs"></a>

Grant the user the permission to tag resources. For more information about IAM policies and example policies, see [Example: Tag resources](ExamplePolicies_EC2.md#iam-example-taggingresources).

The IAM policy you create is determined by which method you use for creating a Spot Instance request.
+ If you use the launch instance wizard or `run-instances` to request Spot Instances, see [To grant a user the permission to tag resources when using the launch instance wizard or run-instances](#iam-run-instances).
+ If you use the `request-spot-instances` command to request Spot Instances, see [To grant a user the permission to tag resources when using request-spot-instances](#iam-request-spot-instances).

**To grant a user the permission to tag resources when using the launch instance wizard or run-instances**  
Create a IAM policy that includes the following:
+ The `ec2:RunInstances` action. This grants the user permission to launch an instance.
+ For `Resource`, specify `spot-instances-request`. This allows users to create Spot Instance requests, which request Spot Instances.
+ The `ec2:CreateTags` action. This grants the user permission to create tags.
+ For `Resource`, specify `*`. This allows users to tag all resources that are created during instance launch.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowLaunchInstances",
            "Effect": "Allow",
            "Action": [
                "ec2:RunInstances"
            ],
            "Resource": [
                "arn:aws-cn:ec2:us-east-1::image/*",
                "arn:aws-cn:ec2:us-east-1:*:subnet/*",
                "arn:aws-cn:ec2:us-east-1:*:network-interface/*",
                "arn:aws-cn:ec2:us-east-1:*:security-group/*",
                "arn:aws-cn:ec2:us-east-1:*:key-pair/*",
                "arn:aws-cn:ec2:us-east-1:*:volume/*",
                "arn:aws-cn:ec2:us-east-1:*:instance/*",
                "arn:aws-cn:ec2:us-east-1:*:spot-instances-request/*"
            ]
        },
        {
            "Sid": "TagSpotInstanceRequests",
            "Effect": "Allow",
            "Action": "ec2:CreateTags",
            "Resource": "*"
        }
    ]
}
```

------

When you use the RunInstances action to create Spot Instance requests and tag the Spot Instance requests on create, you need to be aware of how Amazon EC2 evaluates the `spot-instances-request` resource in the RunInstances statement it is evaluated in the IAM policy as follows:
+ If you don't tag a Spot Instance request on create, Amazon EC2 does not evaluate the `spot-instances-request` resource in the RunInstances statement.
+ If you tag a Spot Instance request on create, Amazon EC2 evaluates the `spot-instances-request` resource in the RunInstances statement.

Therefore, for the `spot-instances-request` resource, the following rules apply to the IAM policy:
+ If you use RunInstances to create a Spot Instance request and you don't intend to tag the Spot Instance request on create, you don’t need to explicitly allow the `spot-instances-request` resource; the call will succeed.
+ If you use RunInstances to create a Spot Instance request and intend to tag the Spot Instance request on create, you must include the `spot-instances-request` resource in the RunInstances allow statement, otherwise the call will fail.
+ If you use RunInstances to create a Spot Instance request and intend to tag the Spot Instance request on create, you must specify the `spot-instances-request` resource or include a `*` wildcard in the CreateTags allow statement, otherwise the call will fail.

For example IAM policies, including policies that are not supported for Spot Instance requests, see [Work with Spot Instances](ExamplePolicies_EC2.md#iam-example-spot-instances).

**To grant a user the permission to tag resources when using request-spot-instances**  
Create a IAM policy that includes the following:
+ The `ec2:RequestSpotInstances` action. This grants the user permission to create a Spot Instance request.
+ The `ec2:CreateTags` action. This grants the user permission to create tags.
+ For `Resource`, specify `spot-instances-request`. This allows users to tag only the Spot Instance request.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "TagSpotInstanceRequest",
            "Effect": "Allow",
            "Action": [
                "ec2:RequestSpotInstances",
                "ec2:CreateTags"
            ],
            "Resource": "arn:aws-cn:ec2:us-east-1:111122223333:spot-instances-request/*"
        }
    ]
}
```

------

## Tag a new Spot Instance request
<a name="tag-new-spot-instance-request"></a>

In the Amazon CLI and PowerShell examples, configure the Spot Instance request as follows:
+ For `ResourceType`, specify `spot-instances-request`. If you specify another value, the Spot Instance request will fail.
+ For `Tags`, specify the key-value pair. You can specify more than one key-value pair.

------
#### [ Console ]

**To tag a new Spot Instance request**

1. Follow the [Manage your Spot Instances](using-spot-instances-request.md) procedure.

1. To add a tag, on the **Add Tags** page, choose **Add Tag**, and enter the key and value for the tag. Choose **Add another tag** for each additional tag.

   For each tag, you can tag the Spot Instance request, the Spot Instances, and the volumes with the same tag. To tag all three, ensure that **Instances**, **Volumes**, and **Spot Instance Requests** are selected. To tag only one or two, ensure that the resources you want to tag are selected, and the other resources are cleared.

1. Complete the required fields to create a Spot Instance request, and then choose **Launch**. For more information, see [Manage your Spot Instances](using-spot-instances-request.md).

------
#### [ Amazon CLI ]

**To tag a new Spot Instance request**  
Use the [request-spot-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/request-spot-instances.html) command with the `--tag-specification` option.

The tag specification adds two tags to the Spot Instance request: `Environment=Production` and `Cost-Center=123`.

```
aws ec2 request-spot-instances \
    --instance-count 5 \
    --type "one-time" \
    --launch-specification file://specification.json \
    --tag-specification 'ResourceType=spot-instances-request,Tags=[{Key=Environment,Value=Production},{Key=Cost-Center,Value=123}]'
```

------
#### [ PowerShell ]

**To tag a new Spot Instance request**  
Use the [Request-EC2SpotInstance](https://docs.amazonaws.cn/powershell/latest/reference/items/Request-EC2SpotInstance.html) cmdlet with the `-TagSpecification` parameter.

```
-TagSpecification $tagspec
```

The tag specification is defined as follows. It adds two tags to the Spot Instance request: `Environment=Production` and `Cost-Center=123`.

```
$tag1 = @{Key="Environment"; Value="Production"}
$tag2 = @{Key="Cost-Center"; Value="123"}
$tagspec = New-Object Amazon.EC2.Model.TagSpecification
$tagspec.ResourceType = "spot-instances-request"
$tagspec.Tags = @($tag1,$tag2)
```

------

## Tag an existing Spot Instance request
<a name="tag-existing-spot-instance-request"></a>

------
#### [ Console ]

**To tag an existing Spot Instance request**

After you have created a Spot Instance request, you can add tags to the Spot Instance request using the console.

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Spot Requests**.

1. Select your Spot Instance request.

1. Choose the **Tags** tab and choose **Create Tag**.

**To tag an existing Spot Instance using the console**  
After your Spot Instance request has launched your Spot Instance, you can add tags to the instance using the console. For more information, see [Add tags using the console](Using_Tags_Console.md#adding-or-deleting-tags).

------
#### [ Amazon CLI ]

**To tag an existing Spot Instance request or Spot Instance**  
Use the [create-tags](https://docs.amazonaws.cn/cli/latest/reference/ec2/create-tags.html) command to tag existing resources. In the following example, the existing Spot Instance request and the Spot Instance are tagged with `purpose=test`.

```
aws ec2 create-tags \
    --resources sir-0e54a519c9EXAMPLE i-1234567890abcdef0 \
    --tags Key=purpose,Value=test
```

------
#### [ PowerShell ]

**To tag an existing Spot Instance request or Spot Instance**  
Use the [New-EC2Tag](https://docs.amazonaws.cn/powershell/latest/reference/items/New-EC2Tag.html) cmdlet. The following example adds the tag `purpose=test` to the existing Spot Instance request and the Spot Instance.

```
New-EC2Tag `
    -Resource sir-0e54a519c9EXAMPLE, i-1234567890abcdef0 `
    -Tag @{Key="purpose"; Value="test"}
```

------

## View Spot Instance request tags
<a name="view-spot-instance-request-tags"></a>

------
#### [ Console ]

**To view Spot Instance request tags**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Spot Requests**.

1. Select your Spot Instance request and choose the **Tags** tab.

------
#### [ Amazon CLI ]

**To describe Spot Instance request tags**  
Use the [describe-spot-instance-requests](https://docs.amazonaws.cn/cli/latest/reference/ec2/describe-spot-instance-requests.html) command to view the configuration of the specified Spot Instance request, which includes any tags that were specified for the request.

```
aws ec2 describe-spot-instance-requests \
    --spot-instance-request-ids sir-0e54a519c9EXAMPLE \
    --query "SpotInstanceRequests[*].Tags"
```

The following is example output.

```
[
    [
        {
            "Key": "Environment",
            "Value": "Production"
        },
        {
            "Key": "Department",
            "Value": "101"
        }
    ]
]
```

------
#### [ PowerShell ]

**To describe Spot Instance request tags**  
Use the [Get-EC2SpotInstanceRequest](https://docs.amazonaws.cn/powershell/latest/reference/items/Get-EC2SpotInstanceRequest.html) cmdlet.

```
(Get-EC2SpotInstanceRequest `
    -SpotInstanceRequestId sir-0e54a519c9EXAMPLE).Tags
```

The following is example output.

```
Key         Value
---         -----
Environment Production
Department  101
```

------

# Cancel a Spot Instance request
<a name="using-spot-instances-cancel"></a>

If you no longer want your Spot Instance request, you can cancel it. You can only cancel Spot Instance requests that are `open`, `active`, or `disabled`.
+ Your Spot Instance request is `open` when your request has not yet been fulfilled and no instances have been launched.
+ Your Spot Instance request is `active` when your request has been fulfilled and Spot Instances have launched as a result. 
+ Your Spot Instance request is `disabled` when you stop your Spot Instance.

If your Spot Instance request is `active` and has an associated running Spot Instance, canceling the request does not terminate the instance. For more information about terminating a Spot Instance, see [Terminate a Spot Instance](using-spot-instances-request.md#terminating-a-spot-instance).

------
#### [ Console ]

**To cancel a Spot Instance request**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Spot Requests**.

1. Select the Spot Instance request.

1. Choose **Actions**, **Cancel request**.

1. (Optional) If you are finished with the associated Spot Instances, you can terminate them. In the **Cancel Spot request** dialog box, select **Terminate instances**, and then choose **Confirm**.

------
#### [ Amazon CLI ]

**To cancel a Spot Instance request**  
Use the following [cancel-spot-instance-requests](https://docs.amazonaws.cn/cli/latest/reference/ec2/cancel-spot-instance-requests.html) command.

```
aws ec2 cancel-spot-instance-requests --spot-instance-request-ids sir-0e54a519c9EXAMPLE
```

------
#### [ PowerShell ]

**To cancel a Spot Instance request**  
Use the [Stop-EC2SpotInstanceRequest](https://docs.amazonaws.cn/powershell/latest/reference/items/Stop-EC2SpotInstanceRequest.html) cmdlet.

```
Stop-EC2SpotInstanceRequest -SpotInstanceRequestId sir-0e54a519c9EXAMPLE
```

------

# Manage your Spot Instances
<a name="using-spot-instances-request"></a>

Amazon EC2 launches a Spot Instance when capacity is available. A Spot Instance runs until it is interrupted or you terminate it yourself.

**Topics**
+ [

## Find your Spot Instances
](#using-spot-instances-running)
+ [

## Find instances launched by a specific request
](#find-request-spot-instances)
+ [

## Stop a Spot Instance
](#stopping-a-spot-instance)
+ [

## Start a Spot Instance
](#starting-a-spot-instance)
+ [

## Terminate a Spot Instance
](#terminating-a-spot-instance)

## Find your Spot Instances
<a name="using-spot-instances-running"></a>

A Spot Instance appears in the **Instances** page in the console, along with On-Demand Instances. Use the following procedure to find your Spot Instances.

------
#### [ Console ]

**To find your Spot Instances**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Instances**.

1. To find all Spot Instances, in the search pane, choose **Instance lifecycle=spot**.

1. To verify that an instance is a Spot Instance, select the instance, choose the **Details** tab, and check the value of **Lifecycle**. The value for a Spot Instance is `spot` and the value for an On-Demand Instance is `normal`.

------
#### [ Amazon CLI ]

**To find your Spot Instances**  
Use the following [describe-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/describe-instances.html) command.

```
aws ec2 describe-instances --filters "Name=instance-lifecycle,Values=spot"
```

**To determine whether an instance is a Spot Instance**  
Use the following [describe-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/describe-instances.html) command.

```
aws ec2 describe-instances \
    --instance-ids i-1234567890abcdef0 \
    --query "Reservations[*].Instances[*].InstanceLifecycle" \
    --output text
```

If the output is `spot`, the instance is a Spot Instance. If there is no output, the instance is an On-Demand Instance.

------
#### [ PowerShell ]

**To find your Spot Instances**  
Use the [Get-EC2Instance](https://docs.amazonaws.cn/powershell/latest/reference/items/Get-EC2Instance.html) cmdlet.

```
Get-EC2Instance -Filter @{Name="instance-lifecycle"; Values="spot"}
```

**To determine whether an instance is a Spot Instance**  
Use the [Get-EC2Instance](https://docs.amazonaws.cn/powershell/latest/reference/items/Get-EC2Instance.html) cmdlet.

```
(Get-EC2Instance -InstanceId i-1234567890abcdef0).Instances.InstanceLifecycle
```

If the output is `Spot`, the instance is a Spot Instance. If there is no output, the instance is an On-Demand Instance.

------

## Find instances launched by a specific request
<a name="find-request-spot-instances"></a>

Use the following procedure to find the Spot Instances launched from a specific Spot Instance or Spot Fleet request.

------
#### [ Console ]

**To find the Spot Instances for a request**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Spot Requests**. The list contains both Spot Instance requests and Spot Fleet requests.

1. If a Spot Instance request is fulfilled, **Capacity** is the ID of the Spot Instance. For a Spot Fleet, **Capacity** indicates how much of the requested capacity has been fulfilled. To view the IDs of the instances in a Spot Fleet, choose the expand arrow, or select the fleet and choose **Instances**.

1. For a Spot Fleet, **Capacity** indicates how much of the requested capacity is fulfilled. To view the IDs of the instances in a Spot Fleet, choose the fleet ID to open its details page and locate the **Instances** pane.

------
#### [ Amazon CLI ]

**To find the Spot Instances for a request**  
Use the following [describe-spot-instance-requests](https://docs.amazonaws.cn/cli/latest/reference/ec2/describe-spot-instance-requests.html) command.

```
aws ec2 describe-spot-instance-requests \
    --spot-instance-request-ids sir-0e54a519c9EXAMPLE \
    --query "SpotInstanceRequests[*].{ID:InstanceId}"
```

The following is example output:

```
[
    {
        "ID": "i-1234567890abcdef0"
    },
    {
        "ID": "i-0598c7d356eba48d7"
    }
]
```

------
#### [ PowerShell ]

**To find the Spot Instances for a request**  
Use the [Get-EC2SpotInstanceRequest](https://docs.amazonaws.cn/powershell/latest/reference/items/Get-EC2SpotInstanceRequest.html) cmdlet.

```
(Get-EC2SpotInstanceRequest -SpotInstanceRequestId sir-0e54a519c9EXAMPLE).InstanceId
```

------

## Stop a Spot Instance
<a name="stopping-a-spot-instance"></a>

If you don't need your Spot Instances now, but you want to restart them later without losing the data persisted in the Amazon EBS volume, you can stop them. The steps for stopping a Spot Instance are similar to the steps for stopping an On-Demand Instance.

**Note**  
While a Spot Instance is stopped, you can modify some of its instance attributes, but not the instance type.   
We don't charge usage for a stopped Spot Instance, or data transfer fees, but we do charge for the storage for any Amazon EBS volumes.

**Limitations**
+ You can only stop a Spot Instance if the Spot Instance was launched from a `persistent` Spot Instance request.
+ You can't stop a Spot Instance if the associated Spot Instance request is cancelled. When the Spot Instance request is cancelled, you can only terminate the Spot Instance.
+ You can't stop a Spot Instance if it is part of a fleet or launch group, or Availability Zone group.

------
#### [ Console ]

**To stop a Spot Instance**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Instances**.

1. Select the Spot Instance. If you didn't save the instance ID of the Spot Instance, see [Find your Spot Instances](#using-spot-instances-running).

1. Choose **Instance state**, **Stop instance**.

1. When prompted for confirmation, choose **Stop**.

------
#### [ Amazon CLI ]

**To stop a Spot Instance**  
Use the [stop-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/stop-instances.html) command to manually stop your Spot Instances.

```
aws ec2 stop-instances --instance-ids i-1234567890abcdef0
```

------
#### [ PowerShell ]

**To stop a Spot Instance**  
Use the [Stop-EC2Instance](https://docs.amazonaws.cn/powershell/latest/reference/items/Stop-EC2Instance.html) cmdlet.

```
Stop-EC2Instance -InstanceId i-1234567890abcdef0
```

------

## Start a Spot Instance
<a name="starting-a-spot-instance"></a>

You can start a Spot Instance that you previously stopped.

**Prerequisites**

You can only start a Spot Instance if:
+ You manually stopped the Spot Instance.
+ The Spot Instance is an EBS-backed instance.
+ Spot Instance capacity is available.
+ The Spot price is lower than your maximum price.

**Limitations**
+ You can't start a Spot Instance if it is part of fleet or launch group, or Availability Zone group.

The steps for starting a Spot Instance are similar to the steps for starting an On-Demand Instance.

------
#### [ Console ]

**To start a Spot Instance**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Instances**.

1. Select the Spot Instance. If you didn't save the instance ID of the Spot Instance, see [Find your Spot Instances](#using-spot-instances-running).

1. Choose **Instance state**, **Start instance**.

------
#### [ Amazon CLI ]

**To start a Spot Instance**  
Use the [start-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/start-instances.html) command to manually start your Spot Instances.

```
aws ec2 start-instances --instance-ids i-1234567890abcdef0
```

------
#### [ PowerShell ]

**To start a Spot Instance**  
Use the [Start-EC2Instance](https://docs.amazonaws.cn/powershell/latest/reference/items/Start-EC2Instance.html) cmdlet.

```
Start-EC2Instance -InstanceId i-1234567890abcdef0
```

------

## Terminate a Spot Instance
<a name="terminating-a-spot-instance"></a>

**Warning**  
**Terminating an instance is permanent and irreversible.**  
After you terminate an instance, you can no longer connect to it, and it can't be recovered. All attached Amazon EBS volumes that are configured to be deleted on termination are also permanently deleted and can't be recovered. All data stored on instance store volumes is permanently lost. For more information, see [How instance termination works](how-ec2-instance-termination-works.md).  
Before you terminate an instance, ensure that you have backed up all data that you need to retain after the termination to persistent storage.

If you terminate a running or stopped Spot Instance that was launched by a persistent Spot Instance request, the Spot Instance request transitions to the `open` state so that a new Spot Instance can be launched. To ensure that no new Spot Instance is launched, you must first cancel the Spot Instance request.

If you cancel an `active` Spot Instance request that has a running Spot Instance, the running Spot Instance is not automatically terminated; you must manually terminate the Spot Instance.

If you cancel a `disabled` Spot Instance request that has a stopped Spot Instance, the stopped Spot Instance is automatically terminated by the Amazon EC2 Spot service. There might be a short lag between when you cancel the Spot Instance request and when the Spot service terminates the Spot Instance.

For more information, see [Cancel a Spot Instance request](using-spot-instances-cancel.md).

------
#### [ Console ]

**To manually terminate a Spot Instance**

1. Before you terminate an instance, verify that you won't lose any data by checking that your Amazon EBS volumes won't be deleted on termination and that you've copied any data that you need from your instance store volumes to persistent storage, such as Amazon EBS or Amazon S3.

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Instances**.

1. Select the Spot Instance. If you didn't save the instance ID of the Spot Instance, see [Find your Spot Instances](#using-spot-instances-running).

1. Choose **Instance state**, **Terminate (delete) instance**.

1. Choose **Terminate (delete)** when prompted for confirmation.

------
#### [ Amazon CLI ]

**To manually terminate a Spot Instance**  
Use the [terminate-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/terminate-instances.html) command to manually terminate your Spot Instances.

```
aws ec2 terminate-instances --instance-ids i-1234567890abcdef0 i-0598c7d356eba48d7
```

------
#### [ PowerShell ]

**To manually terminate a Spot Instance**  
Use the [Remove-EC2Instance](https://docs.amazonaws.cn/powershell/latest/reference/items/Remove-EC2Instance.html) cmdlet.

```
Remove-EC2Instance -InstanceId i-1234567890abcdef0
```

------

# Spot Instance interruptions
<a name="spot-interruptions"></a>

You can launch Spot Instances on spare EC2 capacity for steep discounts in exchange for returning them when Amazon EC2 needs the capacity back. When Amazon EC2 reclaims a Spot Instance, we call this event a *Spot Instance interruption*.

Demand for Spot Instances can vary significantly from moment to moment, and the availability of Spot Instances can also vary significantly depending on how many unused EC2 instances are available. It is always possible that your Spot Instance might be interrupted. The following are the possible reasons that Amazon EC2 might interrupt your Spot Instances:

**Capacity**  
Amazon EC2 can interrupt your Spot Instance when it needs it back. EC2 reclaims your instance mainly to repurpose capacity, but it can also occur for other reasons such as host maintenance or hardware decommission.

**Price**  
The Spot price is higher than your maximum price.  
You can specify the maximum price in your Spot request. However, if you specify a maximum price, your instances will be interrupted more frequently than if you do not specify it.

**Constraints**  
If your Spot request includes a constraint such as a launch group or an Availability Zone group, the Spot Instances are terminated as a group when the constraint can no longer be met.

When Amazon EC2 interrupts a Spot Instance, it either terminates, stops, or hibernates the instance, depending on the interruption behavior that you specified when you created the Spot request.

**Topics**
+ [Interruption behavior](interruption-behavior.md)
+ [Prepare for interruptions](prepare-for-interruptions.md)
+ [Initiate an interruption](initiate-a-spot-instance-interruption.md)
+ [

# Spot Instance interruption notices
](spot-instance-termination-notices.md)
+ [

# Find interrupted Spot Instances
](finding-an-interrupted-Spot-Instance.md)
+ [

# Determine whether Amazon EC2 terminated a Spot Instance
](BidEvictedEvent.md)
+ [Billing](billing-for-interrupted-spot-instances.md)

# Behavior of Spot Instance interruptions
<a name="interruption-behavior"></a>

When you create a Spot request, you can specify the interruption behavior. The following are the possible interruption behaviors:
+ [Stop](#stop-spot-instances)
+ [Hibernate](#hibernate-spot-instances)
+ [Terminate](#terminate-interrupted-spot-instances)

The default behavior is that Amazon EC2 terminates Spot Instances when they are interrupted.

## Stop interrupted Spot Instances
<a name="stop-spot-instances"></a>

You can specify that Amazon EC2 stops your Spot Instances when they are interrupted. The Spot Instance request type must be `persistent`. You can't specify a launch group in the Spot Instance request. For EC2 Fleet or Spot Fleet, the request type must be `maintain`.

**Considerations**
+ Only Amazon EC2 can restart an interrupted stopped Spot Instance.
+ For a Spot Instance launched by a `persistent` Spot Instance request: Amazon EC2 restarts the stopped instance when capacity is available in the same Availability Zone and for the same instance type as the stopped instance (the same launch specification must be used).
+ While a Spot Instance is stopped, you can modify some of its instance attributes, but not the instance type. If you detach or delete an EBS volume, it is not attached when the Spot Instance is started. If you detach the root volume and Amazon EC2 attempts to start the Spot Instance, the instance will fail to start and Amazon EC2 will terminate the stopped instance.
+ You can terminate a Spot Instance while it is stopped.
+ If you cancel a Spot Instance request, an EC2 Fleet, or a Spot Fleet, Amazon EC2 terminates any associated Spot Instances that are stopped.
+ While an interrupted Spot Instance is stopped, you are charged only for the EBS volumes, which are preserved. With EC2 Fleet and Spot Fleet, if you have many stopped instances, you can exceed the limit on the number of EBS volumes for your account. For more information about how you're charged when a Spot Instance is interrupted, see [Billing for interrupted Spot Instances](billing-for-interrupted-spot-instances.md).
+ Make sure that you are familiar with the implications of stopping an instance. For information about what happens when an instance is stopped, see [Differences between instance states](ec2-instance-lifecycle.md#lifecycle-differences).

## Hibernate interrupted Spot Instances
<a name="hibernate-spot-instances"></a>

You can specify that Amazon EC2 hibernates your Spot Instances when they are interrupted. For more information, see [Hibernate your Amazon EC2 instance](Hibernate.md).

Amazon EC2 now offers the same hibernation experience for Spot Instances as is currently available for On-Demand Instances. It offers more extensive support, where the following is now supported for Spot Instance hibernation:
+ [More supported AMIs](hibernating-prerequisites.md#hibernation-prereqs-supported-amis)
+ [More supported instance families](hibernating-prerequisites.md#hibernation-prereqs-supported-instance-families)
+ [User-initiated hibernation](hibernating-instances.md)

## Terminate interrupted Spot Instances
<a name="terminate-interrupted-spot-instances"></a>

When Amazon EC2 interrupts a Spot Instance, it terminates the instance by default, unless you specify a different interruption behavior, such as stop or hibernate. For more information, see [Terminate Amazon EC2 instances](terminating-instances.md).

# Prepare for Spot Instance interruptions
<a name="prepare-for-interruptions"></a>

Demand for Spot Instances can vary significantly from moment to moment, and the availability of Spot Instances can also vary significantly depending on how many unused EC2 instances are available. It is always possible that your Spot Instance might be interrupted. Therefore, you must ensure that your application is prepared for a Spot Instance interruption.

We recommend that you follow these best practices so that you're prepared for a Spot Instance interruption.
+ Create your Spot request using an Auto Scaling group. If your Spot Instances are interrupted, the Auto Scaling group will automatically launch replacement instances. For more information, see [Auto Scaling groups with multiple instance types and purchase options](https://docs.amazonaws.cn/autoscaling/ec2/userguide/ec2-auto-scaling-mixed-instances-groups.html) in the *Amazon EC2 Auto Scaling User Guide*.
+ Ensure that your instance is ready to go as soon as the request is fulfilled by using an Amazon Machine Image (AMI) that contains the required software configuration. You can also use user data to run commands at startup.
+ Data on instance store volumes is lost when the instance is stopped or terminated. Back up any important data on instance store volumes to a more persistent storage, such as Amazon S3, Amazon EBS, or Amazon DynamoDB.
+ Store important data regularly in a place that isn't affected if the Spot Instance terminates. For example, you can use Amazon S3, Amazon EBS, or DynamoDB.
+ Divide the work into small tasks (using a Grid, Hadoop, or queue-based architecture) or use checkpoints so that you can save your work frequently.
+ Amazon EC2 emits a rebalance recommendation signal to the Spot Instance when the instance is at an elevated risk of interruption. You can rely on the rebalance recommendation to proactively manage Spot Instance interruptions without having to wait for the two-minute Spot Instance interruption notice. For more information, see [EC2 instance rebalance recommendations](rebalance-recommendations.md).
+ Use the two-minute Spot Instance interruption notices to monitor the status of your Spot Instances. For more information, see [Spot Instance interruption notices](spot-instance-termination-notices.md).
+ While we make every effort to provide these warnings as soon as possible, it is possible that your Spot Instance is interrupted before the warnings can be made available. Test your application to ensure that it handles an unexpected instance interruption gracefully, even if you are monitoring for rebalance recommendation signals and interruption notices. You can do this by running the application using an On-Demand Instance and then terminating the On-Demand Instance yourself.
+ Run a controlled fault injection experiment with Amazon Fault Injection Service to test how your application responds when your Spot Instance is interrupted. For more information, see the [Tutorial: Test Spot Instance interruptions using Amazon FIS](https://docs.amazonaws.cn/fis/latest/userguide/fis-tutorial-spot-interruptions.html) in the *Amazon Fault Injection Service User Guide*.

# Initiate a Spot Instance interruption
<a name="initiate-a-spot-instance-interruption"></a>

You can select a Spot Instance request or a Spot Fleet request in the Amazon EC2 console and initiate a Spot Instance interruption so that you can test how the applications on your Spot Instances handle being interrupted. When you initiate a Spot Instance interruption, Amazon EC2 notifies you that your Spot Instance will be interrupted in two minutes, and then, after two minutes, the instance is interrupted.

The underlying service that performs the Spot Instance interruption is Amazon Fault Injection Service (Amazon FIS). For information about Amazon FIS, see [Amazon Fault Injection Service](https://www.amazonaws.cn/fis/).

**Note**  
Interruption behaviors are `terminate`, `stop`, and `hibernate`. If you set the interruption behavior to `hibernate`, when you initiate a Spot Instance interruption, the hibernation process will begin immediately.

Initiating a Spot Instance interruption is supported in all Amazon Web Services Regions except Asia Pacific (Jakarta), Asia Pacific (Osaka), China (Beijing), China (Ningxia), and Middle East (UAE).

**Topics**
+ [

## Initiate a Spot Instance interruption
](#initiate-interruption)
+ [

## Verify the Spot Instance interruption
](#spot-interruptions-verify-result)
+ [

## Quotas
](#fis-quota-for-spot-instance-interruption)

## Initiate a Spot Instance interruption
<a name="initiate-interruption"></a>

You can use the EC2 console to quickly initiate a Spot Instance interruption. When you select a Spot Instance request, you can initiate the interruption of one Spot Instance. When you select a Spot Fleet request, you can initiate the interruption of multiple Spot Instances at once.

For more advanced experiments to test Spot Instance interruptions, you can create your own experiments using the Amazon FIS console.

**To initiate the interruption of one Spot Instance in a Spot Instance request using the EC2 console**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. From the navigation pane, choose **Spot Requests**.

1. Select a Spot Instance request, and then choose **Actions**, **Initiate interruption**. You can’t select multiple Spot Instance requests to initiate an interruption.

1. In the **Initiate Spot Instance interruption** dialog box, under **Service access**, either use the default role, or choose an existing role. To choose an existing role, choose **Use an existing service role**, and then, for **IAM role**, select the role to use.

1. When you're ready to initiate the Spot Instance interruption, choose **Initiate interruption.**

**To initiate the interruption of one or more Spot Instances in a Spot Fleet request using the EC2 console**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. From the navigation pane, choose **Spot Requests**.

1. Select a Spot Fleet request, and then choose **Actions**, **Initiate interruption**. You can’t select multiple Spot Fleet requests to initiate an interruption.

1. In the **Specify number of Spot Instances** dialog box, for **Number of instances to interrupt**, enter the number of Spot Instances to interrupt, and then choose **Confirm**.
**Note**  
The number can't exceed the number of Spot Instances in the fleet or your [quota](#fis-quota-for-spot-instance-interruption) for the number of Spot Instances that Amazon FIS can interrupt per experiment.

1. In the **Initiate Spot Instance interruption** dialog box, under **Service access**, either use the default role, or choose an existing role. To choose an existing role, choose **Use an existing service role**, and then, for **IAM role**, select the role to use.

1. When you're ready to initiate the Spot Instance interruption, choose **Initiate interruption.**

**To create more advanced experiments to test Spot Instance interruptions using the Amazon FIS console**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. From the navigation pane, choose **Spot Requests**.

1. Choose **Actions**, **Create advanced experiments**.

   The Amazon FIS console opens. For more information, see [Tutorial: Test Spot Instance interruptions using Amazon FIS](https://docs.amazonaws.cn/fis/latest/userguide/fis-tutorial-spot-interruptions.html) in the *Amazon Fault Injection Service User Guide*.

## Verify the Spot Instance interruption
<a name="spot-interruptions-verify-result"></a>

After you initiate the interruption, the following occurs:
+ The Spot Instance receives an [instance rebalance recommendation](rebalance-recommendations.md).
+ A [Spot Instance interruption notice](spot-instance-termination-notices.md) is issued two minutes before Amazon FIS interrupts your instance.
+ After two minutes, the Spot Instance is interrupted.
+ A Spot Instance that was stopped by Amazon FIS remains stopped until you restart it.

**To verify that the instance was interrupted after you initiated the interruption**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. From the navigation pane, open **Spot Requests** and **Instances** in separate browser tabs or windows.

1. For **Spot Requests**, select the Spot Instance request or Spot Fleet request. The initial status is `fulfilled`. After the instance is interrupted, the status changes as follows, depending on the interruption behavior:
   + `terminate` – The status changes to `instance-terminated-by-experiment`.
   + `stop` – The status changes to `marked-for-stop-by-experiment` and then `instance-stopped-by-experiment`.

1. For **Instances**, select the Spot Instance. The initial status is `Running`. Two minutes after you receive the Spot Instance interruption notice, the status changes as follows, depending on the interruption behavior:
   + `stop` – The status changes to `Stopping` and then `Stopped`.
   + `terminate` – The status changes to `Shutting-down` and then `Terminated`.

## Quotas
<a name="fis-quota-for-spot-instance-interruption"></a>

Your Amazon Web Services account has the following default quota for the number of Spot Instances that Amazon FIS can interrupt per experiment.


| Name | Default | Adjustable | Description | 
| --- | --- | --- | --- | 
|  Target SpotInstances for aws:ec2:send-spot-instance-interruptions  |  Each supported Region: 5  | Yes |  The maximum number of Spot Instances that aws:ec2:send-spot-instance-interruptions can target when you identify targets using tags, per experiment.  | 

You can request a quota increase. For more information, see [Requesting a quota increase](https://docs.amazonaws.cn/servicequotas/latest/userguide/request-quota-increase.html) in the *Service Quotas User Guide*.

To view all the quotas for Amazon FIS, open the [Service Quotas console](https://console.amazonaws.cn/servicequotas/home). In the navigation pane, choose **Amazon services** and select **Amazon Fault Injection Service**. You can also view all the [quotas for Amazon Fault Injection Service](https://docs.amazonaws.cn/fis/latest/userguide/fis-quotas.html) in the *Amazon Fault Injection Service User Guide*.

# Spot Instance interruption notices
<a name="spot-instance-termination-notices"></a>

A *Spot Instance interruption notice* is a warning that is issued two minutes before Amazon EC2 stops or terminates your Spot Instance. If you specify hibernation as the interruption behavior, you receive an interruption notice, but you do not receive a two-minute warning because the hibernation process begins immediately.

The best way for you to gracefully handle Spot Instance interruptions is to architect your application to be fault-tolerant. To accomplish this, you can take advantage of Spot Instance interruption notices. We recommend that you check for these interruption notices every 5 seconds. 

The interruption notices are made available as an EventBridge event and as items in the [instance metadata](ec2-instance-metadata.md) on the Spot Instance. Interruption notices are emitted on a best effort basis.

## EC2 Spot Instance Interruption Warning event
<a name="ec2-spot-instance-interruption-warning-event"></a>

When Amazon EC2 is going to interrupt your Spot Instance, it emits an event two minutes prior to the actual interruption (except for hibernation, which gets the interruption notice, but not two minutes in advance, because hibernation begins immediately). This event can be detected by Amazon EventBridge. For more information about EventBridge events, see the [Amazon EventBridge User Guide](https://docs.amazonaws.cn/eventbridge/latest/userguide/). For a detailed example that walks you through how to create and use event rules, see [Taking Advantage of Amazon EC2 Spot Instance Interruption Notices](https://www.amazonaws.cn/blogs/compute/taking-advantage-of-amazon-ec2-spot-instance-interruption-notices/).

The following is an example of the event for Spot Instance interruption. The possible values for `instance-action` are `hibernate`, `stop`, or `terminate`.

```
{
    "version": "0",
    "id": "12345678-1234-1234-1234-123456789012",
    "detail-type": "EC2 Spot Instance Interruption Warning",
    "source": "aws.ec2",
    "account": "123456789012",
    "time": "yyyy-mm-ddThh:mm:ssZ",
    "region": "us-west-2",
    "resources": ["arn:aws-cn:ec2:us-east-2a:instance/i-1234567890abcdef0"],
    "detail": {
        "instance-id": "i-1234567890abcdef0",
        "instance-action": "action"
    }
}
```

**Note**  
The ARN format of the Spot Instance interruption event is `arn:aws:ec2:availability-zone:instance/instance-id`. This format differs from the [EC2 resource ARN format](https://docs.amazonaws.cn/service-authorization/latest/reference/list_amazonec2.html#amazonec2-resources-for-iam-policies).

## instance-action
<a name="instance-action-metadata"></a>

The `instance-action` item specifies the action and the approximate time, in UTC, when the action will occur.

If your Spot Instance is marked to be stopped or terminated by Amazon EC2, the `instance-action` item is present in your [instance metadata](ec2-instance-metadata.md). Otherwise, it is not present. You can retrieve the `instance-action` using Instance Metadata Service Version 2 (IMDSv2) as follows.

------
#### [ Linux ]

```
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \
    && curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/spot/instance-action
```

------
#### [ Windows ]

```
[string]$token = Invoke-RestMethod `
    -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} `
    -Method PUT -Uri http://169.254.169.254/latest/meta-data/spot/instance-action
```

------

 The following example output indicates the time at which this instance will be stopped.

```
{"action": "stop", "time": "2017-09-18T08:22:00Z"}
```

The following example output indicates the time at which this instance will be terminated.

```
{"action": "terminate", "time": "2017-09-18T08:22:00Z"}
```

If Amazon EC2 is not preparing to stop or terminate the instance, or if you terminated the instance yourself, `instance-action` is not present in the instance metadata and you receive an HTTP 404 error when you try to retrieve it.

## termination-time
<a name="termination-time-metadata"></a>

The `termination-time` item specifies the approximate time in UTC when the instance will receive the shutdown signal. 

**Note**  
This item is maintained for backward compatibility; you should use `instance-action` instead.

If your Spot Instance is marked for termination by Amazon EC2 (either due to a Spot Instance interruption where the interruption behavior is set to `terminate`, or due to the cancellation of a persistent Spot Instance request), the `termination-time` item is present in your [instance metadata](ec2-instance-metadata.md). Otherwise, it is not present. You can retrieve the `termination-time` using IMDSv2 as follows.

------
#### [ Linux ]

```
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
if curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/spot/termination-time | grep -q .*T.*Z; then echo termination_scheduled; fi
```

------
#### [ Windows ]

```
[string]$token = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} -Method PUT -Uri http://169.254.169.254/latest/meta-data/spot/termination-time
```

------

The following is example output.

```
2015-01-05T18:02:00Z
```

If Amazon EC2 is not preparing to terminate the instance (either because there is no Spot Instance interruption or because your interruption behavior is set to `stop` or `hibernate`), or if you terminated the Spot Instance yourself, the `termination-time` item is either not present in the instance metadata (so you receive an HTTP 404 error) or contains a value that is not a time value.

If Amazon EC2 fails to terminate the instance, the request status is set to `fulfilled`. The `termination-time` value remains in the instance metadata with the original approximate time, which is now in the past.

# Find interrupted Spot Instances
<a name="finding-an-interrupted-Spot-Instance"></a>

When you describe your EC2 instances, the results include your Spot Instances. The instance lifecycle of a Spot Instance is `spot`. The instance state of a Spot Instance is either `stopped` or `terminated`, depending on the interruption behavior that you configured. For a hibernated Spot Instance, the instance state is `stopped`.

For additional details about the reason for the interruption, check the Spot request status code. For more information, see [Get the status of a Spot Instance request](spot-request-status.md).

------
#### [ Console ]

**To find an interrupted Spot Instance**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Instances**.

1. Apply the following filter: **Instance lifecycle=spot**.

1. Apply the **Instance state=stopped** or **Instance state=terminated** filter depending on the interruption behavior that you configured.

1. For each Spot Instance, on the **Details** tab, under **Instance details**, find **State transition message**. The following codes indicate that the Spot Instance was interrupted.
   + `Server.SpotInstanceShutdown`
   + `Server.SpotInstanceTermination`

------
#### [ Amazon CLI ]

**To find interrupted Spot Instances**  
Use the [describe-instances](https://docs.amazonaws.cn/cli/latest/reference/ec2/describe-instances.html) command with the `--filters` option. To list only the instance IDs in the output, include the `--query` option.

If the interruption behavior is to terminate the Spot Instances, use the following example:

```
aws ec2 describe-instances \
    --filters Name=instance-lifecycle,Values=spot \
              Name=instance-state-name,Values=terminated \
              Name=state-reason-code,Values=Server.SpotInstanceTermination \
    --query "Reservations[*].Instances[*].InstanceId"
```

If the interruption behavior is to stop the Spot Instances, use the following example:

```
aws ec2 describe-instances \
    --filters Name=instance-lifecycle,Values=spot \
              Name=instance-state-name,Values=stopped \
              Name=state-reason-code,Values=Server.SpotInstanceShutdown \
    --query "Reservations[*].Instances[*].InstanceId"
```

------
#### [ PowerShell ]

**To find interrupted Spot Instances**  
Use the [Get-EC2Instance](https://docs.amazonaws.cn/powershell/latest/reference/items/Get-EC2Instance.html) cmdlet.

If the interruption behavior is to terminate the Spot Instances, use the following example:

```
(Get-EC2Instance `
    -Filter @{Key="instance-lifecycle"; Values="spot"} `
            @{Key="instance-state-name"; Values="terminated"} `
            @{Key="state-reason-code"; Values="Server.SpotInstanceTermination"}).Instances.InstanceId
```

If the interruption behavior is to stop the Spot Instances, use the following example:

```
(Get-EC2Instance `
    -Filter @{Key="instance-lifecycle"; Values="spot"} `
            @{Key="instance-state-name"; Values="stopped"} `
            @{Key="state-reason-code"; Values="Server.SpotInstanceTermination"}).Instances.InstanceId
```

------

# Determine whether Amazon EC2 terminated a Spot Instance
<a name="BidEvictedEvent"></a>

A Spot Instance runs until Amazon EC2 terminates it in response to a Spot Instance interruption, or until you terminate it yourself. For more information, see [Behavior of Spot Instance interruptions](interruption-behavior.md).

After a Spot Instance is terminated, you can use Amazon CloudTrail to see whether Amazon EC2 terminated it. If the CloudTrail log includes a `BidEvictedEvent`, this indicates that Amazon EC2 terminated the Spot Instance. If instead you see a `TerminateInstances` event, this indicates that a user terminated the Spot Instance.

Alternatively, if you want to receive notification that Amazon EC2 is going to interrupt your Spot Instance, use Amazon EventBridge to respond to the [EC2 Spot Instance Interruption Warning event](spot-instance-termination-notices.md#ec2-spot-instance-interruption-warning-event).

**To view BidEvictedEvent events in CloudTrail**

1. Open the CloudTrail console at [https://console.amazonaws.cn/cloudtrail/](https://console.amazonaws.cn/cloudtrail/).

1. In the navigation pane, choose **Event history**.

1. From the list of filters, choose **Event name**, and then in the filter field to the right, enter **BidEvictedEvent**.

1. (Optional) Select a time range.

1. If the list is not empty, choose **BidEvictedEvent** from the resulting entry to open its details page. You can find information about the Spot Instance in the **Event record** pane, including the ID of the Spot Instance. The following is an example of the event record.

   ```
   {
       "eventVersion": "1.05",
       "userIdentity": {
           "accountId": "123456789012",
           "invokedBy": "ec2.amazonaws.com"
       },
       "eventTime": "2016-08-16T22:30:00Z",
       "eventSource": "ec2.amazonaws.com",
       "userAgent": "ec2.amazonaws.com",
       "sourceIPAddress": "ec2.amazonaws.com",
       "eventName": "BidEvictedEvent",
       "awsRegion": "us-east-2",
       "eventID": "d27a6096-807b-4bd0-8c20-a33a83375054",
       "eventType": "AwsServiceEvent",
       "recipientAccountId": "123456789012",
       "RequestParameters": null,
       "ResponseElements": null,
       "serviceEventDetails": {
           "instanceIdSet": [
             "i-1eb2ac8eEXAMPLE"
           ]
       }
   }
   ```

1. If you did not find an entry for the `BidEvictedEvent` event, enter **TerminateInstances** as the event name. For more information about the event record for `TerminateInstances`, see [Amazon EC2 API event examples](monitor-with-cloudtrail.md#cloudtrail-event-examples).

# Billing for interrupted Spot Instances
<a name="billing-for-interrupted-spot-instances"></a>

When a Spot Instance is interrupted, you're charged for instance and EBS volume usage, and you might incur other charges, as follows.

## Instance usage
<a name="billing-for-interrupted-spot-instances-instance-usage"></a>

[\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/billing-for-interrupted-spot-instances.html)

## EBS volume usage
<a name="billing-for-interrupted-spot-instances-ebs-usage"></a>

While an interrupted Spot Instance is stopped, you are charged only for the EBS volumes, which are preserved.

With EC2 Fleet and Spot Fleet, if you have many stopped instances, you can exceed the limit on the number of EBS volumes for your account. 

# EC2 instance rebalance recommendations
<a name="rebalance-recommendations"></a>

An EC2 instance *rebalance recommendation* is a signal that notifies you when a Spot Instance is at elevated risk of interruption. The signal can arrive sooner than the [two-minute Spot Instance interruption notice](spot-instance-termination-notices.md), giving you the opportunity to proactively manage the Spot Instance. You can decide to rebalance your workload to new or existing Spot Instances that are not at an elevated risk of interruption.

It is not always possible for Amazon EC2 to send the rebalance recommendation signal before the two-minute Spot Instance interruption notice. Therefore, the rebalance recommendation signal can arrive along with the two-minute interruption notice.

Rebalance recommendations are made available as a EventBridge event and as an item in the [instance metadata](ec2-instance-metadata.md) on the Spot Instance. Events are emitted on a best effort basis.

**Note**  
Rebalance recommendations are only supported for Spot Instances that are launched after November 5, 2020 00:00 UTC.

**Topics**
+ [

## Rebalance actions you can take
](#rebalancing-actions)
+ [

## Monitor rebalance recommendation signals
](#monitor-rebalance-recommendations)
+ [

## Services that use the rebalance recommendation signal
](#services-using-rebalance-rec-signal)

## Rebalance actions you can take
<a name="rebalancing-actions"></a>

These are some of the possible rebalancing actions that you can take:

Graceful shutdown  
When you receive the rebalance recommendation signal for a Spot Instance, you can start your instance shutdown procedures, which might include ensuring that processes are completed before stopping them. For example, you can upload system or application logs to Amazon Simple Storage Service (Amazon S3), you can shut down Amazon SQS workers, or you can complete deregistration from the Domain Name System (DNS). You can also save your work in external storage and resume it at a later time.

Prevent new work from being scheduled  
When you receive the rebalance recommendation signal for a Spot Instance, you can prevent new work from being scheduled on the instance, while continuing to use the instance until the scheduled work is completed.

Proactively launch new replacement instances  
You can configure Auto Scaling groups, EC2 Fleet, or Spot Fleet to automatically launch replacement Spot Instances when a rebalance recommendation signal is emitted. For more information, see [Use Capacity Rebalancing to handle Amazon EC2 Spot interruptions](https://docs.amazonaws.cn/autoscaling/ec2/userguide/ec2-auto-scaling-capacity-rebalancing.html) in the *Amazon EC2 Auto Scaling User Guide*, and [Use Capacity Rebalancing in EC2 Fleet and Spot Fleet to replace at-risk Spot Instances](ec2-fleet-capacity-rebalance.md) in this user guide.

## Monitor rebalance recommendation signals
<a name="monitor-rebalance-recommendations"></a>

You can monitor the rebalance recommendation signal so that, when it is emitted, you can take the actions that are specified in the preceding section. The rebalance recommendation signal is made available as an event that is sent to Amazon EventBridge (formerly known as Amazon CloudWatch Events) and as instance metadata on the Spot Instance.

**Topics**
+ [

### Use Amazon EventBridge
](#cp-eventbridge)
+ [

### Use instance metadata
](#cp-instance-metadata)

### Use Amazon EventBridge
<a name="cp-eventbridge"></a>

When the rebalance recommendation signal is emitted for a Spot Instance, the event for the signal is sent to Amazon EventBridge. If EventBridge detects an event pattern that matches a pattern defined in a rule, EventBridge invokes a target (or targets) specified in the rule.

The following is an example event for the rebalance recommendation signal.

```
{
    "version": "0",
    "id": "12345678-1234-1234-1234-123456789012",
    "detail-type": "EC2 Instance Rebalance Recommendation",
    "source": "aws.ec2",
    "account": "123456789012",
    "time": "yyyy-mm-ddThh:mm:ssZ",
    "region": "us-west-2",
    "resources": ["arn:aws-cn:ec2:us-west-2:123456789012:instance/i-1234567890abcdef0"],
    "detail": {
        "instance-id": "i-1234567890abcdef0"
    }
}
```

The following fields form the event pattern that is defined in the rule:

`"detail-type": "EC2 Instance Rebalance Recommendation"`  
Identifies that the event is a rebalance recommendation event

`"source": "aws.ec2"`  
Identifies that the event is from Amazon EC2

#### Create an EventBridge rule
<a name="cp-eventbridge-rule"></a>

You can write an EventBridge rule and automate what actions to take when the event pattern matches the rule.

The following example creates an EventBridge rule to send an email, text message, or mobile push notification every time Amazon EC2 emits a rebalance recommendation signal. The signal is emitted as an `EC2 Instance Rebalance Recommendation` event, which triggers the action defined by the rule.

Before creating the EventBridge rule, you must create the Amazon SNS topic for the email, text message, or mobile push notification.

**To create an EventBridge rule for a rebalance recommendation event**

1. Open the Amazon EventBridge console at [https://console.amazonaws.cn/events/](https://console.amazonaws.cn/events/).

1. Choose **Create rule**.

1. For **Define rule detail**, do the following:

   1. Enter a **Name** for the rule, and, optionally, a description.

      A rule can't have the same name as another rule in the same Region and on the same event bus.

   1. For **Event bus**, choose **default**. When an Amazon service in your account generates an event, it always goes to your account's default event bus.

   1. For **Rule type**, choose **Rule with an event pattern**.

   1. Choose **Next**.

1. For **Build event pattern**, do the following:

   1. For **Event source**, choose **Amazon events or EventBridge partner events**.

   1. For **Event pattern**, for this example you’ll specify the following event pattern to match the `EC2 Instance Rebalance Recommendation` event, and then choose **Save**.

      ```
      {
       "source": ["aws.ec2"],
       "detail-type": ["EC2 Instance Rebalance Recommendation"]
      }
      ```

      To add the event pattern, you can either use a template by choosing **Event pattern form**, or specify your own pattern by choosing **Custom pattern (JSON editor)**, as follows:

      1. To use a template to create the event pattern, do the following:

         1. Choose **Event pattern form**.

         1. For **Event source**, choose **Amazon services**.

         1. For **Amazon Service**, choose **EC2 Spot Fleet**.

         1. For **Event type**, choose **EC2 Instance Rebalance Recommendation**.

         1. To customize the template, choose **Edit pattern** and make your changes to match the example event pattern.

      1. (Alternative) To specify a custom event pattern, do the following:

         1. Choose **Custom pattern (JSON editor)**.

         1. In the **Event pattern** box, add the event pattern for this example.

   1. Choose **Next**.

1. For **Select target(s)**, do the following:

   1. For **Target types**, choose **Amazon service**.

   1. For **Select a target**, choose **SNS topic** to send an email, text message, or mobile push notification when the event occurs.

   1. For **Topic**, choose an existing topic. You first need to create an Amazon SNS topic using the Amazon SNS console. For more information, see [Using Amazon SNS for application-to-person (A2P) messaging](https://docs.amazonaws.cn//sns/latest/dg/sns-user-notifications.html) in the *Amazon Simple Notification Service Developer Guide*.

   1. (Optional) Under **Additional settings**, you can optionally configure additional settings. For more information, see [Creating Amazon EventBridge rules that react to events](https://docs.amazonaws.cn//eventbridge/latest/userguide/eb-create-rule.html) (step 16) in the *Amazon EventBridge User Guide*.

   1. Choose **Next**.

1. (Optional) For **Tags**, you can optionally assign one or more tags to your rule, and then choose **Next**.

1. For **Review and create**, do the following:

   1. Review the details of the rule and modify them as necessary.

   1. Choose **Create rule**.

For more information, see [Amazon EventBridge rules](https://docs.amazonaws.cn/eventbridge/latest/userguide/eb-rules.html) and [Amazon EventBridge event patterns](https://docs.amazonaws.cn/eventbridge/latest/userguide/eb-event-patterns.html) in the *Amazon EventBridge User Guide*

### Use instance metadata
<a name="cp-instance-metadata"></a>

The instance metadata category `events/recommendations/rebalance` provides the approximate time, in UTC, when the rebalance recommendation signal was emitted for a Spot Instance.

We recommend that you check for rebalance recommendation signals every 5 seconds so that you don't miss an opportunity to act on the rebalance recommendation.

If a Spot Instance receives a rebalance recommendation, the time that the signal was emitted is present in the instance metadata. You can retrieve the time that the signal was emitted as follows.

------
#### [ IMDSv2 ]

**Linux**  
Run the following command from your Linux instance.

**IMDSv2**

```
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \
    && curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/events/recommendations/rebalance
```

**Windows**  
Run the following cmdlet from your Windows instance

```
[string]$token = Invoke-RestMethod `
    -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} `
    -Method PUT -Uri http://169.254.169.254/latest/api/token
```

```
Invoke-RestMethod `
    -Headers @{"X-aws-ec2-metadata-token" = $token} `
    -Method GET -Uri http://169.254.169.254/latest/meta-data/events/recommendations/rebalance
```

------
#### [ IMDSv1 ]

**Linux**  
Run the following command from your Linux instance.

```
curl http://169.254.169.254/latest/meta-data/events/recommendations/rebalance
```

**Windows**  
Run the following cmdlet from your Windows instance.

```
Invoke-RestMethod -Uri http://169.254.169.254/latest/meta-data/events/recommendations/rebalance
```

------

The following is example output, which indicates the time, in UTC, that the rebalance recommendation signal was emitted for the Spot Instance.

```
{"noticeTime": "2020-10-27T08:22:00Z"}
```

If the signal has not been emitted for the instance, `events/recommendations/rebalance` is not present and you receive an HTTP 404 error when you try to retrieve it.

## Services that use the rebalance recommendation signal
<a name="services-using-rebalance-rec-signal"></a>

Amazon EC2 Auto Scaling, EC2 Fleet, and Spot Fleet use the rebalance recommendation signal to make it easy for you to maintain workload availability by proactively augmenting your fleet with a new Spot Instance before a running instance receives the two-minute Spot Instance interruption notice. You can have these services monitor and respond proactively to changes affecting the availability of your Spot Instances. For more information, see the following:
+ [Use Capacity Rebalancing to handle Amazon EC2 Spot interruptions](https://docs.amazonaws.cn/autoscaling/ec2/userguide/ec2-auto-scaling-capacity-rebalancing.html) in the *Amazon EC2 Auto Scaling User Guide*
+ [Use Capacity Rebalancing in EC2 Fleet and Spot Fleet to replace at-risk Spot Instances](ec2-fleet-capacity-rebalance.md) in the EC2 Fleet and Spot Fleet topic in this user guide

# Spot placement score
<a name="spot-placement-score"></a>

The Spot placement score feature can recommend an Amazon Region or Availability Zone based on your Spot capacity requirements. Spot capacity fluctuates, and you can't be sure that you'll always get the capacity that you need. A Spot placement score indicates how likely it is that a Spot request will succeed in a Region or Availability Zone.

**Note**  
When using the Spot placement score feature in the China (Beijing) or China (Ningxia) Regions, Amazon EC2 returns scores only for the Region, or for each Availability Zone in the Region, in which the call is made.

**Note**  
A Spot placement score does not provide any guarantees in terms of available capacity or risk of interruption. A Spot placement score serves only as a recommendation.

**Use cases**

You can use the Spot placement score feature for the following:
+ To relocate and scale Spot compute capacity in a different Region, as needed, in response to increased capacity needs or decreased available capacity in the current Region.
+ To identify the most optimal Availability Zone in which to run single-Availability Zone workloads.
+ To simulate future Spot capacity needs so that you can pick an optimal Region for the expansion of your Spot-based workloads.
+ To find an optimal combination of instance types to fulfill your Spot capacity needs.

**Topics**
+ [

## Limitations
](#sps-limitations)
+ [

## Costs
](#sps-costs)
+ [

# How Spot placement score works
](how-sps-works.md)
+ [

# Required permissions for Spot placement score
](sps-iam-permission.md)
+ [

# Calculate the Spot placement score
](work-with-spot-placement-score.md)

## Limitations
<a name="sps-limitations"></a>
+ **Target capacity limit** – Your Spot placement score target capacity limit is based on your recent Spot usage, while accounting for potential usage growth. If you have no recent Spot usage, we provide you with a low default limit aligned with your Spot request limit.
+ **Request configurations limit** – We can limit the number of new request configurations within a 24-hour period if we detect patterns not associated with the intended use of the Spot placement score feature. If you reach the limit, you can retry the request configurations that you've already used, but you can't specify new request configurations until the next 24-hour period.
+ **Minimum number of instance types** – If you specify instance types, you must specify at least three different instance types, otherwise Amazon EC2 will return a low Spot placement score. Similarly, if you specify instance attributes, they must resolve to at least three different instance types. Instance types are considered different if they have a different name. For example, m5.8xlarge, m5a.8xlarge, and m5.12xlarge are all considered different.

## Costs
<a name="sps-costs"></a>

There is no additional charge for using the Spot placement score feature.

# How Spot placement score works
<a name="how-sps-works"></a>

When you use the Spot placement score feature, you first specify your compute requirements for your Spot Instances, and then Amazon EC2 returns a score for the Region or Availability Zones where your Spot request is likely to succeed. Each Region or Availability Zone is scored on a scale from 1 to 10, with 10 indicating that your Spot request is highly likely to succeed, and 1 indicating that your Spot request is not likely to succeed.

**Topics**
+ [

## Step 1: Specify your Spot requirements
](#sps-specify-requirements)
+ [

## Step 2: Filter the Spot placement score response
](#get-sps)
+ [

## Step 3: Review the recommendations
](#sps-recommendations)
+ [

## Step 4: Use the recommendations
](#sps-use-recommendations)

## Step 1: Specify your Spot requirements
<a name="sps-specify-requirements"></a>

First, you specify your desired target Spot capacity and your compute requirements, as follows:

1. **Specify the target Spot capacity, and optionally the target capacity unit.**

   You can specify your desired target Spot capacity in terms of the number of instances or vCPUs, or in terms of the amount of memory in MiB. To specify the target capacity in number of vCPUs or amount of memory, you must specify the target capacity unit as `vcpu` or `memory-mib`. Otherwise, it defaults to number of instances.

   By specifying your target capacity in terms of the number of vCPUs or the amount of memory, you can use these units when counting the total capacity. For example, if you want to use a mix of instances of different sizes, you can specify the target capacity as a total number of vCPUs. The Spot placement score feature then considers each instance type in the request by its number of vCPUs, and counts the total number of vCPUs rather than the total number of instances when totaling up the target capacity.

   For example, say you specify a total target capacity of 30 vCPUs, and your instance type list consists of c5.xlarge (4 vCPUs), m5.2xlarge (8 vCPUs), and r5.large (2 vCPUs). To achieve a total of 30 vCPUs, you could get a mix of 2 c5.xlarge (2\$14 vCPUs), 2 m5.2xlarge (2\$18 vCPUs), and 3 r5.large (3\$12 vCPUs).

1. **Specify instance types or instance attributes.**

   You can either specify the instance types to use, or you can specify the instance attributes that you need for your compute requirements, and then let Amazon EC2 identify the instance types that have those attributes. This is known as attribute-based instance type selection.

   You can't specify both instance types and instance attributes in the same Spot placement score request.

   If you specify instance types, you must specify at least three different instance types, otherwise Amazon EC2 will return a low Spot placement score. Similarly, if you specify instance attributes, they must resolve to at least three different instance types.

For examples of different ways to specify your Spot requirements, see [Example configurations](work-with-spot-placement-score.md#sps-example-configs).

## Step 2: Filter the Spot placement score response
<a name="get-sps"></a>

Amazon EC2 calculates the Spot placement score for the Region or for each Availability Zone in the Region, and returns either the score for the Region or the scores for the Availability Zones where your Spot request is likely to succeed. The default is to return a score for the Region. If you plan to launch all of your Spot capacity into a single Availability Zone, then it's useful to request a list of scored Availability Zones.

## Step 3: Review the recommendations
<a name="sps-recommendations"></a>

The Spot placement score for each Region or Availability Zone is calculated based on the target capacity, the composition of the instance types, the historical and current Spot usage trends, and the time of the request. Because Spot capacity is constantly fluctuating, the same Spot placement score request can yield different scores when calculated at different times.

Regions and Availability Zones are scored on a scale from 1 to 10. A score of 10 indicates that your Spot request is highly likely—but not guaranteed—to succeed. A score of 1 indicates that your Spot request is not likely to succeed at all. The same score might be returned for different Regions or Availability Zones.

If low scores are returned, you can edit your compute requirements and recalculate the score. You can also request Spot placement score recommendations for the same compute requirements at different times of the day.

## Step 4: Use the recommendations
<a name="sps-use-recommendations"></a>

A Spot placement score is only relevant if your Spot request has exactly the same configuration as the Spot placement score configuration (target capacity, target capacity unit, and instance types or instance attributes), and is configured to use the `capacity-optimized` allocation strategy. Otherwise, the likelihood of getting available Spot capacity will not align with the score.

While a Spot placement score serves as a guideline, and no score guarantees that your Spot request will be fully or partially fulfilled, you can use the following information to get the best results:
+ **Use the same configuration** – The Spot placement score is relevant only if the Spot request configuration (target capacity, target capacity unit, and instance types or instance attributes) in your Auto Scaling group, EC2 Fleet, or Spot Fleet is the same as what you entered to get the Spot placement score.

  If you used attribute-based instance type selection in your Spot placement score request, you can use attribute-based instance type selection to configure your Auto Scaling group, EC2 Fleet, or Spot Fleet. For more information, see [Create mixed instances group using attribute-based instance type selection](https://docs.amazonaws.cn/autoscaling/ec2/userguide/create-mixed-instances-group-attribute-based-instance-type-selection.html) and [Specify attributes for instance type selection for EC2 Fleet or Spot Fleet](ec2-fleet-attribute-based-instance-type-selection.md).
**Note**  
If you specified your target capacity in terms of the number of vCPUs or the amount of memory, and you specified instance types in your Spot placement score configuration, note that you can’t currently create this configuration in your Auto Scaling group, EC2 Fleet, or Spot Fleet. Instead, you must manually set the instance weighting by using the `WeightedCapacity` parameter.
+ **Use the `capacity-optimized` allocation strategy** – Any score assumes that your fleet request will be configured to use all Availability Zones (for requesting capacity across the Region) or a single Availability Zone (if requesting capacity in one Availability Zone) and the `capacity-optimized` Spot allocation strategy for your request for Spot capacity to succeed. If you use other allocation strategies, such as `lowest-price`, the likelihood of getting available Spot capacity will not align with the score.
+ **Act on a score immediately** – The Spot placement score recommendation reflects the available Spot capacity at the time of the request, and the same configuration can yield different scores when calculated at different times due to Spot capacity fluctuations. While a score of 10 means that your Spot capacity request is highly likely—but not guaranteed—to succeed, for best results we recommend that you act on a score immediately. We also recommend that you get a fresh score each time you attempt a capacity request.

# Required permissions for Spot placement score
<a name="sps-iam-permission"></a>

By default, IAM identities (users, roles, or groups) don't have permission to use [Spot placement score](spot-placement-score.md). To allow IAM identities to use Spot placement score, you must create an IAM policy that grants permission to use the `ec2:GetSpotPlacementScores` EC2 API action. You then attach the policy to the IAM identities that require this permission.

The following is an example IAM policy that grants permission to use the `ec2:GetSpotPlacementScores` EC2 API action.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:GetSpotPlacementScores",
            "Resource": "*"
        }
    ]
}
```

------

For information about editing an IAM policy, see [Editing IAM policies](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_policies_manage-edit.html) in the *IAM User Guide*.

To provide access, add permissions to your users, groups, or roles:
+ Users managed in IAM through an identity provider:

  Create a role for identity federation. Follow the instructions in [Create a role for a third-party identity provider (federation)](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_roles_create_for-idp.html) in the *IAM User Guide*.
+ IAM users:
  + Create a role that your user can assume. Follow the instructions in [Create a role for an IAM user](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_roles_create_for-user.html) in the *IAM User Guide*.
  + (Not recommended) Attach a policy directly to a user or add a user to a user group. Follow the instructions in [Adding permissions to a user (console)](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console) in the *IAM User Guide*.

# Calculate the Spot placement score
<a name="work-with-spot-placement-score"></a>

You can calculate a Spot placement score based on target capacity and compute requirements. For more information, see [How Spot placement score works](how-sps-works.md).

**Required permissions**  
Ensure that you have the required permissions. For more information, see [Required permissions for Spot placement score](sps-iam-permission.md).

**Topics**
+ [

## Calculate using instance attributes
](#sps-specify-instance-attributes-console)
+ [

## Calculate using instance types
](#sps-specify-instance-types-console)
+ [

## Calculate using the Amazon CLI
](#calculate-sps-cli)

**Looking for an automated solution?** Instead of following the manual steps in this user guide, you can build a Spot placement score tracker dashboard that automatically captures and stores the scores in Amazon CloudWatch. For more information, see [Guidance for Building a Spot Placement Score Tracker Dashboard on Amazon](https://www.amazonaws.cn/solutions/guidance/building-a-spot-placement-score-tracker-dashboard-on-aws/).

## Calculate using instance attributes
<a name="sps-specify-instance-attributes-console"></a>

**To calculate a Spot placement score by specifying instance attributes**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Spot Requests**.

1. From the top navigation bar, select a Region in which to evaluate the Spot placement score.

1. Choose the down arrow next to **Request Spot Instances** and choose **Calculate Spot Placement Score**.

1. Choose **Enter requirements**.

1. For **Target capacity**, enter your desired capacity in terms of the number of **instances** or **vCPUs**, or the amount of **memory (MiB)**.

1. For **Instance type requirements**, to specify your compute requirements and let Amazon EC2 identify the optimal instance types with these requirements, choose **Specify instance attributes that match your compute requirements**.

1. For **vCPUs**, enter the desired minimum and maximum number of vCPUs. To specify no limit, select **No minimum**, **No maximum**, or both.

1. For **Memory (GiB)**, enter the desired minimum and maximum amount of memory. To specify no limit, select **No minimum**, **No maximum**, or both.

1. For **CPU architecture**, select the required instance architecture.

1. (Optional) For **Additional instance attributes**, you can optionally specify one or more attributes to express your compute requirements in more detail. Each additional attribute adds a further constraint to your request. You can omit the additional attributes; when omitted, the default values are used. For a description of each attribute and their default values, see [get-spot-placement-scores](https://docs.amazonaws.cn/cli/latest/reference/ec2/get-spot-placement-scores.html).

1. (Optional) To view the instance types with your specified attributes, expand **Preview matching instance types**. To exclude instance types from being used in the placement evaluation, select the instances and then choose **Exclude selected instance types**.

1. Choose **Load placement scores**, and review the results.

1. (Optional) To display the Spot placement score for the Availability Zones in the displayed Region, select the **Provide placement scores per Availability Zone** checkbox. A list of scored Availability Zones is useful if you want to launch all of your Spot capacity into a single Availability Zone.

1. (Optional) To edit your compute requirements and get a new placement score, choose **Edit**, make the necessary adjustments, and then choose **Calculate placement scores**.

## Calculate using instance types
<a name="sps-specify-instance-types-console"></a>

**To calculate a Spot placement score by specifying instance types**

1. Open the Amazon EC2 console at [https://console.amazonaws.cn/ec2/](https://console.amazonaws.cn/ec2/).

1. In the navigation pane, choose **Spot Requests**.

1. From the top navigation bar, select a Region in which to evaluate the Spot placement score.

1. Choose the down arrow next to **Request Spot Instances** and choose **Calculate Spot Placement Score**.

1. Choose **Enter requirements**.

1. For **Target capacity**, enter your desired capacity in terms of the number of **instances** or **vCPUs**, or the amount of **memory (MiB)**.

1. For **Instance type requirements**, to specify the instance types to use, choose **Manually select instance types**.

1. Choose **Select instance types**, select the instance types to use, and then choose **Select**. To quickly find instance types, you can use the filter bar to filter the instance types by different properties.

1. Choose **Load placement scores**, and review the results.

1. (Optional) To display the Spot placement score for the Availability Zones in the displayed Region, select the **Provide placement scores per Availability Zone** checkbox. A list of scored Availability Zones is useful if you want to launch all of your Spot capacity into a single Availability Zone.

1. (Optional) To edit the list of instance types and get a new placement score, choose **Edit**, make the necessary adjustments, and then choose **Calculate placement scores**.

## Calculate using the Amazon CLI
<a name="calculate-sps-cli"></a>

**To calculate the Spot placement score**

1. (Optional) To generate all of the possible parameters that can be specified for the Spot placement score configuration, use the [get-spot-placement-scores](https://docs.amazonaws.cn/cli/latest/reference/ec2/get-spot-placement-scores.html) command and the `--generate-cli-skeleton` parameter.

   ```
   aws ec2 get-spot-placement-scores \
       --region cn-north-1 \
       --generate-cli-skeleton
   ```

   The following is example output.

   ```
   {
       "InstanceTypes": [
           ""
       ],
       "TargetCapacity": 0,
       "TargetCapacityUnitType": "vcpu",
       "SingleAvailabilityZone": true,
       "RegionNames": [
           ""
       ],
       "InstanceRequirementsWithMetadata": {
           "ArchitectureTypes": [
               "x86_64_mac"
           ],
           "VirtualizationTypes": [
               "hvm"
           ],
           "InstanceRequirements": {
               "VCpuCount": {
                   "Min": 0,
                   "Max": 0
               },
               "MemoryMiB": {
                   "Min": 0,
                   "Max": 0
               },
               "CpuManufacturers": [
                   "amd"
               ],
               "MemoryGiBPerVCpu": {
                   "Min": 0.0,
                   "Max": 0.0
               },
               "ExcludedInstanceTypes": [
                   ""
               ],
               "InstanceGenerations": [
                   "previous"
               ],
               "SpotMaxPricePercentageOverLowestPrice": 0,
               "OnDemandMaxPricePercentageOverLowestPrice": 0,
               "BareMetal": "excluded",
               "BurstablePerformance": "excluded",
               "RequireHibernateSupport": true,
               "NetworkInterfaceCount": {
                   "Min": 0,
                   "Max": 0
               },
               "LocalStorage": "included",
               "LocalStorageTypes": [
                   "hdd"
               ],
               "TotalLocalStorageGB": {
                   "Min": 0.0,
                   "Max": 0.0
               },
               "BaselineEbsBandwidthMbps": {
                   "Min": 0,
                   "Max": 0
               },
               "AcceleratorTypes": [
                   "fpga"
               ],
               "AcceleratorCount": {
                   "Min": 0,
                   "Max": 0
               },
               "AcceleratorManufacturers": [
                   "amd"
               ],
               "AcceleratorNames": [
                   "vu9p"
               ],
               "AcceleratorTotalMemoryMiB": {
                   "Min": 0,
                   "Max": 0
               }
           }
       },
       "DryRun": true,
       "MaxResults": 0,
       "NextToken": ""
   }
   ```

1. Create a JSON configuration file using the output from the previous step, and configure it as follows:

   1. For `TargetCapacity`, enter your desired Spot capacity in terms of the number of instances or vCPUs, or the amount of memory (MiB).

   1. For `TargetCapacityUnitType`, enter the unit for the target capacity. If you omit this parameter, it defaults to `units`.

      Valid values: `units` (which translates to number of instances) \$1 `vcpu` \$1 `memory-mib`

   1. For `SingleAvailabilityZone`, specify `true` for a response that returns a list of scored Availability Zones. A list of scored Availability Zones is useful if you want to launch all of your Spot capacity into a single Availability Zone. If you omit this parameter, it defaults to `false`, and the response returns the scored Region.

   1. (Optional) For `RegionNames`, specify the Region to use as a filter. You must specify the Region code, for example, `cn-north-1`.

      With a Region filter, the response returns only the Region that you specify. If you specified `true` for `SingleAvailabilityZone`, the response returns only the Availability Zones in the specified Region.

   1. You can include either `InstanceTypes` or `InstanceRequirements`, but not both in the same configuration.

      Specify one of the following in your JSON configuration:
      + To specify a list of instance types, specify the instance types in the `InstanceTypes` parameter. Specify at least three different instance types. If you specify only one or two instance types, Spot placement score returns a low score. For the list of instance types, see [Amazon EC2 Instance Types](https://www.amazonaws.cn/ec2/instance-types/).
      + To specify the instance attributes so that Amazon EC2 will identify the instance types that match those attributes, specify the attributes that are located in the `InstanceRequirements` structure.

        You must provide values for `VCpuCount`, `MemoryMiB`, and `CpuManufacturers`. You can omit the other attributes; when omitted, the default values are used. For a description of each attribute and their default values, see [get-spot-placement-scores](https://docs.amazonaws.cn/cli/latest/reference/ec2/get-spot-placement-scores.html).

      For example configurations, see [Example configurations](#sps-example-configs).

1. To get the Spot placement score for the requirements that you specified in the JSON file, use the [get-spot-placement-scores](https://docs.amazonaws.cn/cli/latest/reference/ec2/get-spot-placement-scores.html) command, and specify the name and path to your JSON file by using the `--cli-input-json` parameter.

   ```
   aws ec2 get-spot-placement-scores \
       --region cn-north-1 \
       --cli-input-json file://file_name.json
   ```

   Example output if `SingleAvailabilityZone` is set to `false` or omitted (if omitted, it defaults to `false`) – the scored Region is returned.

   ```
   {
       "SpotPlacementScores": [
           {
               "Region": "cn-north-1",
               "Score": 9
           }
       ]
   }
   ```

   Example output if `SingleAvailabilityZone` is set to `true` – a scored list of Availability Zones is returned.

   ```
   {
       "SpotPlacementScores": [
           {
               "Region": "cn-north-1",
               "AvailabilityZoneId": "cnn1-az2",
               "Score": 9
           },
           {
               "Region": "cn-north-1",
               "AvailabilityZoneId": "cnn1-az4",
               "Score": 9
           },
           {
               "Region": "cn-north-1",
               "AvailabilityZoneId": "cnn1-az1",
               "Score": 9
           }
       ]
   }
   ```

### Example configurations
<a name="sps-example-configs"></a>

When using the Amazon CLI, you can use the following example configurations.

**Topics**
+ [

#### Example: Specify instance types and target capacity
](#example-config-instance-type-override)
+ [

#### Example: Specify instance types, and target capacity in terms of memory
](#example-config-instance-type-memory-unit-override)
+ [

#### Example: Specify attributes for attribute-based instance type selection
](#example-config-attribute-based-instance-type-selection)
+ [

#### Example: Specify attributes for attribute-based instance type selection and return a scored list of Availability Zones
](#example-config-sps-singleAZ)

#### Example: Specify instance types and target capacity
<a name="example-config-instance-type-override"></a>

The following example configuration specifies three different instance types and a target Spot capacity of 500 Spot Instances.

```
{
    "InstanceTypes": [
        "m5.4xlarge",
        "r5.2xlarge",
        "m4.4xlarge"
    ], 
    "TargetCapacity": 500
}
```

#### Example: Specify instance types, and target capacity in terms of memory
<a name="example-config-instance-type-memory-unit-override"></a>

The following example configuration specifies three different instance types and a target Spot capacity of 500,000 MiB of memory, where the number of Spot Instances to launch must provide a total of 500,000 MiB of memory.

```
{
    "InstanceTypes": [
        "m5.4xlarge",
        "r5.2xlarge",
        "m4.4xlarge"
    ], 
    "TargetCapacity": 500000,
    "TargetCapacityUnitType": "memory-mib"
}
```

#### Example: Specify attributes for attribute-based instance type selection
<a name="example-config-attribute-based-instance-type-selection"></a>

The following example configuration is configured for attribute-based instance type selection, and is followed by a text explanation of the example configuration.

```
{
    "TargetCapacity": 5000,
    "TargetCapacityUnitType": "vcpu",
    "InstanceRequirementsWithMetadata": {
        "ArchitectureTypes": ["arm64"],
        "VirtualizationTypes": ["hvm"],
        "InstanceRequirements": {
            "VCpuCount": {
                "Min": 1,
                "Max": 12
            },
            "MemoryMiB": {
                "Min": 512
            }
        }
    }
}
```

****`InstanceRequirementsWithMetadata`****  
To use attribute-based instance type selection, you must include the `InstanceRequirementsWithMetadata` structure in your configuration, and specify the desired attributes for the Spot Instances.

In the preceding example, the following required instance attributes are specified:
+ `ArchitectureTypes` – The architecture type of the instance types must be `arm64`.
+ `VirtualizationTypes` – The virtualization type of the instance types must be `hvm`.
+ `VCpuCount` – The instance types must have a minimum of 1 and a maximum of 12 vCPUs.
+ `MemoryMiB` – The instance types must have a minimum of 512 MiB of memory. By omitting the `Max` parameter, you are indicating that there is no maximum limit.

Note that there are several other optional attributes that you can specify. For the list of attributes, see [get-spot-placement-scores](https://docs.amazonaws.cn/cli/latest/reference/ec2/get-spot-placement-scores.html).

**`TargetCapacityUnitType`**  
The `TargetCapacityUnitType` parameter specifies the unit for the target capacity. In the example, the target capacity is `5000` and the target capacity unit type is `vcpu`, which together specify a desired target capacity of 5000 vCPUs, where the number of Spot Instances to launch must provide a total of 5000 vCPUs.

#### Example: Specify attributes for attribute-based instance type selection and return a scored list of Availability Zones
<a name="example-config-sps-singleAZ"></a>

The following example configuration is configured for attribute-based instance type selection. By specifying `"SingleAvailabilityZone": true`, the response will return a list of scored Availability Zones.

```
{
    "TargetCapacity": 1000,
    "TargetCapacityUnitType": "vcpu",
    "SingleAvailabilityZone": true,
    "InstanceRequirementsWithMetadata": {
        "ArchitectureTypes": ["arm64"],
        "VirtualizationTypes": ["hvm"],
        "InstanceRequirements": {
            "VCpuCount": {
                "Min": 1,
                "Max": 12
            },
            "MemoryMiB": {
                "Min": 512
            }
        }
    }
}
```

# Service-linked role for Spot Instance requests
<a name="service-linked-roles-spot-instance-requests"></a>

Amazon EC2 uses service-linked roles for the permissions that it requires to call other Amazon services on your behalf. A service-linked role is a unique type of IAM role that is linked directly to an Amazon Web Services service. Service-linked roles provide a secure way to delegate permissions to Amazon Web Services services because only the linked service can assume a service-linked role. For more information, see [Service-linked roles](https://docs.amazonaws.cn/IAM/latest/UserGuide/id_roles_create-service-linked-role.html) in the *IAM User Guide*.

Amazon EC2 uses the service-linked role named **AWSServiceRoleForEC2Spot** to launch and manage Spot Instances on your behalf.

## Permissions granted by AWSServiceRoleForEC2Spot
<a name="service-linked-role-permissions-granted-by-AWSServiceRoleForEC2Spot"></a>

Amazon EC2 uses **AWSServiceRoleForEC2Spot** to complete the following actions:
+ `ec2:DescribeInstances` – Describe Spot Instances
+ `ec2:StopInstances` – Stop Spot Instances
+ `ec2:StartInstances` – Start Spot Instances

## Create the service-linked role
<a name="service-linked-role-creating-for-spot"></a>

Under most circumstances, you don't need to manually create a service-linked role. Amazon EC2 creates the **AWSServiceRoleForEC2Spot** service-linked role the first time you request a Spot Instance using the console.

If you had an active Spot Instance request before October 2017, when Amazon EC2 began supporting this service-linked role, Amazon EC2 created the **AWSServiceRoleForEC2Spot** role in your Amazon account. For more information, see [A New Role Appeared in My Account](https://docs.amazonaws.cn/IAM/latest/UserGuide/troubleshoot_roles.html#troubleshoot_roles_new-role-appeared) in the *IAM User Guide*.

If you use the Amazon CLI or an API to request a Spot Instance, you must first ensure that this role exists.

**To create **AWSServiceRoleForEC2Spot** using the console**

1. Open the IAM console at [https://console.amazonaws.cn/iam/](https://console.amazonaws.cn/iam/).

1. In the navigation pane, choose **Roles**.

1. Choose **Create role**.

1. On the **Select type of trusted entity** page, choose **EC2**, **EC2 - Spot Instances**, **Next: Permissions**.

1. On the next page, choose **Next:Review**.

1. On the **Review** page, choose **Create role**.

**To create **AWSServiceRoleForEC2Spot** using the Amazon CLI**  
Use the [create-service-linked-role](https://docs.amazonaws.cn/cli/latest/reference/iam/create-service-linked-role.html) command as follows.

```
aws iam create-service-linked-role --aws-service-name spot.amazonaws.com
```

If you no longer need to use Spot Instances, we recommend that you delete the **AWSServiceRoleForEC2Spot** role. After this role is deleted from your account, Amazon EC2 will create the role again if you request Spot Instances.

## Grant access to customer managed keys for use with encrypted AMIs and EBS snapshots
<a name="spot-instance-service-linked-roles-access-to-cmks"></a>

If you specify an [encrypted AMI](AMIEncryption.md) or an encrypted Amazon EBS snapshot for your Spot Instances and you use a customer managed key for encryption, you must grant the **AWSServiceRoleForEC2Spot** role permission to use the customer managed key so that Amazon EC2 can launch Spot Instances on your behalf. To do this, you must add a grant to the customer managed key, as shown in the following procedure.

When providing permissions, grants are an alternative to key policies. For more information, see [Using Grants](https://docs.amazonaws.cn/kms/latest/developerguide/grants.html) and [Using Key Policies in Amazon KMS](https://docs.amazonaws.cn/kms/latest/developerguide/key-policies.html) in the *Amazon Key Management Service Developer Guide*.

**To grant the **AWSServiceRoleForEC2Spot** role permissions to use the customer managed key**
+ Use the [create-grant](https://docs.amazonaws.cn/cli/latest/reference/kms/create-grant.html) command to add a grant to the customer managed key and to specify the principal (the **AWSServiceRoleForEC2Spot** service-linked role) that is given permission to perform the operations that the grant permits. The customer managed key is specified by the `key-id` parameter and the ARN of the customer managed key. The principal is specified by the `grantee-principal` parameter and the ARN of the **AWSServiceRoleForEC2Spot** service-linked role.

  ```
  aws kms create-grant \
      --region us-east-1 \
      --key-id arn:aws:kms:us-east-1:444455556666:key/1234abcd-12ab-34cd-56ef-1234567890ab \
      --grantee-principal arn:aws:iam::111122223333:role/aws-service-role/spot.amazonaws.com/AWSServiceRoleForEC2Spot \
      --operations "Decrypt" "Encrypt" "GenerateDataKey" "GenerateDataKeyWithoutPlaintext" "CreateGrant" "DescribeKey" "ReEncryptFrom" "ReEncryptTo"
  ```

# Spot Instance quotas
<a name="using-spot-limits"></a>

There are quotas for the number of running Spot Instances and pending Spot Instance requests per Amazon Web Services account per Region. After a pending Spot Instance request is fulfilled, the request no longer counts towards the quota because the running instance is counted towards the quota.

Spot Instance quotas are managed in terms of the *number of virtual central processing units (vCPUs)* that your running Spot Instances are either using or will use pending the fulfillment of open Spot Instance requests. If you terminate your Spot Instances but do not cancel the Spot Instance requests, the requests count against your Spot Instance vCPU quota until Amazon EC2 detects the Spot Instance terminations and closes the requests.

We provide the following quota types for Spot Instances.


| Name | Default | Adjustable | 
| --- | --- | --- | 
| All DL Spot Instance Requests | 0 | [Yes](https://console.amazonaws.cn/servicequotas/home/services/ec2/quotas/L-85EED4F7) | 
| All F Spot Instance Requests | 0 | [Yes](https://console.amazonaws.cn/servicequotas/home/services/ec2/quotas/L-88CF9481) | 
| All G and VT Spot Instance Requests | 0 | [Yes](https://console.amazonaws.cn/servicequotas/home/services/ec2/quotas/L-3819A6DF) | 
| All Inf Spot Instance Requests | 0 | [Yes](https://console.amazonaws.cn/servicequotas/home/services/ec2/quotas/L-B5D1601B) | 
| All P Spot Instance Requests | 0 | [Yes](https://console.amazonaws.cn/servicequotas/home/services/ec2/quotas/L-7212CCBC) | 
| All Standard (A, C, D, H, I, M, R, T, Z) Spot Instance Requests | 5 | [Yes](https://console.amazonaws.cn/servicequotas/home/services/ec2/quotas/L-34B43A08) | 
| All Trn Spot Instance Requests | 0 | [Yes](https://console.amazonaws.cn/servicequotas/home/services/ec2/quotas/L-6B0D517C) | 
| All X Spot Instance Requests | 0 | [Yes](https://console.amazonaws.cn/servicequotas/home/services/ec2/quotas/L-E3A00192) | 

Even though Amazon EC2 automatically adjusts your Spot Instance quotas based on your usage, you can request a quota increase if necessary. For example, if you intend to launch more Spot Instances than your current quota allows, you can request a quota increase. You can also request a quota increase if you submit a Spot Instance request and you receive the error `Max spot instance count exceeded`. To request a quota increase, use the Service Quotas console described in [Amazon EC2 service quotas](ec2-resource-limits.md).

You can launch any combination of instance types that meet your changing application needs. For example, with an All Standard Spot Instance Requests quota of 256 vCPUs, you could request 32 `m5.2xlarge` Spot Instances (32 x 8 vCPUs) or 16 `c5.4xlarge` Spot Instances (16 x 16 vCPUs). 

With Amazon CloudWatch metrics integration, you can monitor EC2 usage against your quotas. You can also configure alarms to warn about approaching quotas. For more information, see [Service Quotas and Amazon CloudWatch alarms](https://docs.amazonaws.cn/servicequotas/latest/userguide/configure-cloudwatch.html) in the *Service Quotas User Guide*.