Resource: awsSpotFleetRequest
Provides an EC2 Spot Fleet Request resource. This allows a fleet of Spot instances to be requested on the Spot market.
Example Usage
Using launch specifications
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.spotFleetRequest.SpotFleetRequest(this, "cheap_compute", {
allocationStrategy: "diversified",
iamFleetRole: "arn:aws:iam::12345678:role/spot-fleet",
launchSpecification: [
{
ami: "ami-1234",
iamInstanceProfileArn: "${aws_iam_instance_profile.example.arn}",
instanceType: "m4.10xlarge",
placementTenancy: "dedicated",
spotPrice: "2.793",
},
{
ami: "ami-5678",
availabilityZone: "us-west-1a",
iamInstanceProfileArn: "${aws_iam_instance_profile.example.arn}",
instanceType: "m4.4xlarge",
keyName: "my-key",
rootBlockDevice: [
{
volumeSize: "300",
volumeType: "gp2",
},
],
spotPrice: "1.117",
subnetId: "subnet-1234",
tags: {
name: "spot-fleet-example",
},
weightedCapacity: 35,
},
],
spotPrice: "0.03",
targetCapacity: 6,
validUntil: "2019-11-04T20:44:20Z",
});
Using launch templates
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsLaunchTemplateFoo = new aws.launchTemplate.LaunchTemplate(
this,
"foo",
{
imageId: "ami-516b9131",
instanceType: "m1.small",
keyName: "some-key",
name: "launch-template",
}
);
const awsSpotFleetRequestFoo = new aws.spotFleetRequest.SpotFleetRequest(
this,
"foo_1",
{
depends_on: ["${aws_iam_policy_attachment.test-attach}"],
iamFleetRole: "arn:aws:iam::12345678:role/spot-fleet",
launchTemplateConfig: [
{
launchTemplateSpecification: {
id: awsLaunchTemplateFoo.id,
version: awsLaunchTemplateFoo.latestVersion,
},
},
],
spotPrice: "0.005",
targetCapacity: 2,
validUntil: "2019-11-04T20:44:20Z",
}
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsSpotFleetRequestFoo.overrideLogicalId("foo");
\~> NOTE: Terraform does not support the functionality where multiple subnetId
or availabilityZone
parameters can be specified in the same launch configuration block. If you want to specify multiple values, then separate launch configuration blocks should be used or launch template overrides should be configured, one per subnet:
Using multiple launch specifications
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.spotFleetRequest.SpotFleetRequest(this, "foo", {
iamFleetRole: "arn:aws:iam::12345678:role/spot-fleet",
launchSpecification: [
{
ami: "ami-d06a90b0",
availabilityZone: "us-west-2a",
instanceType: "m1.small",
keyName: "my-key",
},
{
ami: "ami-d06a90b0",
availabilityZone: "us-west-2a",
instanceType: "m5.large",
keyName: "my-key",
},
],
spotPrice: "0.005",
targetCapacity: 2,
validUntil: "2019-11-04T20:44:20Z",
});
-> In this example, we use a dynamic
block to define zero or more launchSpecification
blocks, producing one for each element in the list of subnet ids.
import * as cdktf from "cdktf";
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
/*Terraform Variables are not always the best fit for getting inputs in the context of Terraform CDK.
You can read more about this at https://cdk.tf/variables*/
const awsSpotFleetRequestExample = new aws.spotFleetRequest.SpotFleetRequest(
this,
"example",
{
allocationStrategy: "lowestPrice",
launch_specification: [],
fleetType: "request",
iamFleetRole: "arn:aws:iam::12345678:role/spot-fleet",
targetCapacity: 3,
terminateInstancesWithExpiration: "true",
validUntil: "2019-11-04T20:44:20Z",
waitForFulfillment: "true",
}
);
/*In most cases loops should be handled in the programming language context and
not inside of the Terraform context. If you are looping over something external, e.g. a variable or a file input
you should consider using a for loop. If you are looping over something only known to Terraform, e.g. a result of a data source
you need to keep this like it is.*/
awsSpotFleetRequestExample.addOverride("launch_specification", {
for_each: ["${[for s in var.subnets : {\n subnet_id = s[1]\n }]}"],
content: [
{
ami: "ami-1234",
instance_type: "m4.4xlarge",
root_block_device: [
{
delete_on_termination: "true",
volume_size: "8",
volume_type: "gp2",
},
],
subnet_id: "${launch_specification.value.subnet_id}",
tags: {
Name: "Spot Node",
tag_builder: "builder",
},
vpc_security_group_ids: "sg-123456",
},
],
});
Using multiple launch configurations
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsLaunchTemplateFoo = new aws.launchTemplate.LaunchTemplate(
this,
"foo",
{
imageId: "ami-516b9131",
instanceType: "m1.small",
keyName: "some-key",
name: "launch-template",
}
);
const awsSpotFleetRequestFoo = new aws.spotFleetRequest.SpotFleetRequest(
this,
"foo_1",
{
depends_on: ["${aws_iam_policy_attachment.test-attach}"],
iamFleetRole: "arn:aws:iam::12345678:role/spot-fleet",
launchTemplateConfig: [
{
launchTemplateSpecification: {
id: awsLaunchTemplateFoo.id,
version: awsLaunchTemplateFoo.latestVersion,
},
overrides: [
{
subnetId: "${data.aws_subnets.example.ids[0]}",
},
{
subnetId: "${data.aws_subnets.example.ids[1]}",
},
{
subnetId: "${data.aws_subnets.example.ids[2]}",
},
],
},
],
spotPrice: "0.005",
targetCapacity: 2,
validUntil: "2019-11-04T20:44:20Z",
}
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsSpotFleetRequestFoo.overrideLogicalId("foo");
new aws.dataAwsSubnetIds.DataAwsSubnetIds(this, "example", {
vpcId: "${var.vpc_id}",
});
Argument Reference
Most of these arguments directly correspond to the official API.
-
iamFleetRole
- (Required) Grants the Spot fleet permission to terminate Spot instances on your behalf when you cancel its Spot fleet request using CancelSpotFleetRequests or when the Spot fleet request expires, if you set terminateInstancesWithExpiration. -
replaceUnhealthyInstances
- (Optional) Indicates whether Spot fleet should replace unhealthy instances. Defaultfalse
. -
launchSpecification
- (Optional) Used to define the launch configuration of the spot-fleet request. Can be specified multiple times to define different bids across different markets and instance types. Conflicts withlaunchTemplateConfig
. At least one oflaunchSpecification
orlaunchTemplateConfig
is required.Note: This takes in similar but not identical inputs as
awsInstance
. There are limitations on what you can specify. See the list of officially supported inputs in the reference documentation. Any normalawsInstance
parameter that corresponds to those inputs may be used and it have a additional parameteriamInstanceProfileArn
takesawsIamInstanceProfile
attributearn
as input. -
launchTemplateConfig
- (Optional) Launch template configuration block. See Launch Template Configs below for more details. Conflicts withlaunchSpecification
. At least one oflaunchSpecification
orlaunchTemplateConfig
is required. -
spotMaintenanceStrategies
- (Optional) Nested argument containing maintenance strategies for managing your Spot Instances that are at an elevated risk of being interrupted. Defined below. -
spotPrice
- (Optional; Default: On-demand price) The maximum bid price per unit hour. -
waitForFulfillment
- (Optional; Default: false) If set, Terraform will wait for the Spot Request to be fulfilled, and will throw an error if the timeout of 10m is reached. -
targetCapacity
- The number of units to request. You can choose to set the target capacity in terms of instances or a performance characteristic that is important to your application workload, such as vCPUs, memory, or I/O. -
targetCapacityUnitType
- (Optional) The unit for the target capacity. This can only be done withinstanceRequirements
defined -
allocationStrategy
- Indicates how to allocate the target capacity across the Spot pools specified by the Spot fleet request. Valid values:lowestPrice
,diversified
,capacityOptimized
,capacityOptimizedPrioritized
, andpriceCapacityOptimized
. The default islowestPrice
. -
instancePoolsToUseCount
- (Optional; Default: 1) The number of Spot pools across which to allocate your target Spot capacity. Valid only whenallocationStrategy
is set tolowestPrice
. Spot Fleet selects the cheapest Spot pools and evenly allocates your target Spot capacity across the number of Spot pools that you specify. -
excessCapacityTerminationPolicy
- Indicates whether running Spot instances should be terminated if the target capacity of the Spot fleet request is decreased below the current size of the Spot fleet. -
terminateInstancesWithExpiration
- (Optional) Indicates whether running Spot instances should be terminated when the Spot fleet request expires. -
terminateInstancesOnDelete
- (Optional) Indicates whether running Spot instances should be terminated when the resource is deleted (and the Spot fleet request cancelled). If no value is specified, the value of theterminateInstancesWithExpiration
argument is used. -
instanceInterruptionBehaviour
- (Optional) Indicates whether a Spot instance stops or terminates when it is interrupted. Default isterminate
. -
fleetType
- (Optional) The type of fleet request. Indicates whether the Spot Fleet only requests the target capacity or also attempts to maintain it. Default ismaintain
. -
validUntil
- (Optional) The end date and time of the request, in UTC RFC3339 format(for example, YYYY-MM-DDTHH:MM:SSZ). At this point, no new Spot instance requests are placed or enabled to fulfill the request. -
validFrom
- (Optional) The start date and time of the request, in UTC RFC3339 format(for example, YYYY-MM-DDTHH:MM:SSZ). The default is to start fulfilling the request immediately. -
loadBalancers
(Optional) A list of elastic load balancer names to add to the Spot fleet. -
targetGroupArns
(Optional) A list ofawsAlbTargetGroup
ARNs, for use with Application Load Balancing. -
onDemandAllocationStrategy
- The order of the launch template overrides to use in fulfilling On-Demand capacity. the possible values are:lowestPrice
andprioritized
. the default islowestPrice
. -
onDemandMaxTotalPrice
- The maximum amount per hour for On-Demand Instances that you're willing to pay. When the maximum amount you're willing to pay is reached, the fleet stops launching instances even if it hasn’t met the target capacity. -
onDemandTargetCapacity
- The number of On-Demand units to request. If the request type ismaintain
, you can specify a target capacity of 0 and add capacity later. -
tags
- (Optional) A map of tags to assign to the resource. If configured with a providerdefaultTags
configuration block present, tags with matching keys will overwrite those defined at the provider-level.
Launch Template Configs
The launchTemplateConfig
block supports the following:
launchTemplateSpecification
- (Required) Launch template specification. See Launch Template Specification below for more details.overrides
- (Optional) One or more override configurations. See Overrides below for more details.
Launch Template Specification
id
- The ID of the launch template. Conflicts withname
.name
- The name of the launch template. Conflicts withid
.-
version
- (Optional) Template version. Unlike the autoscaling equivalent, does not support$latest
or$default
, so use the launch_template resource's attribute, e.g.,"${awsLaunchTemplateFooLatestVersion}"
. It will use the default version if omitted.Note: The specified launch template can specify only a subset of the inputs of
awsLaunchTemplate
. There are limitations on what you can specify as spot fleet does not support all the attributes that are supported by autoscaling groups. AWS documentation is currently sparse, but at leastinstanceInitiatedShutdownBehavior
is confirmed unsupported.
spotMaintenanceStrategies
capacityRebalance
- (Optional) Nested argument containing the capacity rebalance for your fleet request. Defined below.
capacityRebalance
replacementStrategy
- (Optional) The replacement strategy to use. Only available for spot fleets withfleetType
set tomaintain
. Valid values:launch
.
Overrides
availabilityZone
- (Optional) The availability zone in which to place the request.instanceRequirements
- (Optional) The instance requirements. See below.instanceType
- (Optional) The type of instance to request.priority
- (Optional) The priority for the launch template override. The lower the number, the higher the priority. If no number is set, the launch template override has the lowest priority.spotPrice
- (Optional) The maximum spot bid for this override request.subnetId
- (Optional) The subnet in which to launch the requested instance.weightedCapacity
- (Optional) The capacity added to the fleet by a fulfilled request.
Instance Requirements
This configuration block supports the following:
-
acceleratorCount
- (Optional) Block describing the minimum and maximum number of accelerators (GPUs, FPGAs, or AWS Inferentia chips). Default is no minimum or maximum.min
- (Optional) Minimum.max
- (Optional) Maximum. Set to0
to exclude instance types with accelerators.
-
acceleratorManufacturers
- (Optional) List of accelerator manufacturer names. Default is any manufacturer. -
acceleratorNames
- (Optional) List of accelerator names. Default is any acclerator. -
acceleratorTotalMemoryMib
- (Optional) Block describing the minimum and maximum total memory of the accelerators. Default is no minimum or maximum.min
- (Optional) Minimum.max
- (Optional) Maximum.
-
acceleratorTypes
- (Optional) List of accelerator types. Default is any accelerator type. -
allowedInstanceTypes
- (Optional) List of instance types to apply your specified attributes against. All other instance types are ignored, even if they match your specified attributes. You can use strings with one or more wild cards, represented by an asterisk (*), to allow an instance type, size, or generation. The following are examples:m58Xlarge
,c5*.*
,m5A.*
,r*
,*3*
. For example, if you specifyc5*
, you are allowing the entire C5 instance family, which includes all C5a and C5n instance types. If you specifym5A.*
, you are allowing all the M5a instance types, but not the M5n instance types. Maximum of 400 entries in the list; each entry is limited to 30 characters. Default is all instance types.\~> NOTE: If you specify
allowedInstanceTypes
, you can't specifyexcludedInstanceTypes
. -
bareMetal
- (Optional) Indicate whether bare metal instace types should beincluded
,excluded
, orrequired
. Default isexcluded
. -
baselineEbsBandwidthMbps
- (Optional) Block describing the minimum and maximum baseline EBS bandwidth, in Mbps. Default is no minimum or maximum.min
- (Optional) Minimum.max
- (Optional) Maximum.
-
burstablePerformance
- (Optional) Indicate whether burstable performance instance types should beincluded
,excluded
, orrequired
. Default isexcluded
. -
cpuManufacturers
(Optional) List of CPU manufacturer names. Default is any manufacturer.\~> NOTE: Don't confuse the CPU hardware manufacturer with the CPU hardware architecture. Instances will be launched with a compatible CPU architecture based on the Amazon Machine Image (AMI) that you specify in your launch template.
-
excludedInstanceTypes
- (Optional) List of instance types to exclude. You can use strings with one or more wild cards, represented by an asterisk (*), to exclude an instance type, size, or generation. The following are examples:m58Xlarge
,c5*.*
,m5A.*
,r*
,*3*
. For example, if you specifyc5*
, you are excluding the entire C5 instance family, which includes all C5a and C5n instance types. If you specifym5A.*
, you are excluding all the M5a instance types, but not the M5n instance types. Maximum of 400 entries in the list; each entry is limited to 30 characters. Default is no excluded instance types.\~> NOTE: If you specify
excludedInstanceTypes
, you can't specifyallowedInstanceTypes
. -
instanceGenerations
- (Optional) List of instance generation names. Default is any generation. -
localStorage
- (Optional) Indicate whether instance types with local storage volumes areincluded
,excluded
, orrequired
. Default isincluded
. -
localStorageTypes
- (Optional) List of local storage type names. Default any storage type. -
memoryGibPerVcpu
- (Optional) Block describing the minimum and maximum amount of memory (GiB) per vCPU. Default is no minimum or maximum.min
- (Optional) Minimum. May be a decimal number, e.g.05
.max
- (Optional) Maximum. May be a decimal number, e.g.05
.
-
memoryMib
- (Optional) Block describing the minimum and maximum amount of memory (MiB). Default is no maximum.min
- (Optional) Minimum.max
- (Optional) Maximum.
-
networkBandwidthGbps
- (Optional) Block describing the minimum and maximum amount of network bandwidth, in gigabits per second (Gbps). Default is no minimum or maximum.min
- (Optional) Minimum.max
- (Optional) Maximum.
-
networkInterfaceCount
- (Optional) Block describing the minimum and maximum number of network interfaces. Default is no minimum or maximum.min
- (Optional) Minimum.max
- (Optional) Maximum.
-
onDemandMaxPricePercentageOverLowestPrice
- (Optional) The price protection threshold for On-Demand Instances. This is the maximum you’ll pay for an On-Demand Instance, expressed as a percentage higher than the cheapest M, C, or R instance type with your specified attributes. When Amazon EC2 Auto Scaling selects instance types with your attributes, we will exclude instance types whose price is higher than your threshold. The parameter accepts an integer, which Amazon EC2 Auto Scaling interprets as a percentage. To turn off price protection, specify a high value, such as 999999. Default is 20.If you set DesiredCapacityType to vcpu or memory-mib, the price protection threshold is applied based on the per vCPU or per memory price instead of the per instance price.
-
requireHibernateSupport
- (Optional) Indicate whether instance types must support On-Demand Instance Hibernation, eithertrue
orfalse
. Default isfalse
. -
spotMaxPricePercentageOverLowestPrice
- (Optional) The price protection threshold for Spot Instances. This is the maximum you’ll pay for a Spot Instance, expressed as a percentage higher than the cheapest M, C, or R instance type with your specified attributes. When Amazon EC2 Auto Scaling selects instance types with your attributes, we will exclude instance types whose price is higher than your threshold. The parameter accepts an integer, which Amazon EC2 Auto Scaling interprets as a percentage. To turn off price protection, specify a high value, such as 999999. Default is 100.If you set DesiredCapacityType to vcpu or memory-mib, the price protection threshold is applied based on the per vCPU or per memory price instead of the per instance price.
-
totalLocalStorageGb
- (Optional) Block describing the minimum and maximum total local storage (GB). Default is no minimum or maximum.min
- (Optional) Minimum. May be a decimal number, e.g.05
.max
- (Optional) Maximum. May be a decimal number, e.g.05
.
-
vcpuCount
- (Optional) Block describing the minimum and maximum number of vCPUs. Default is no maximum.min
- (Optional) Minimum.max
- (Optional) Maximum.
Attributes Reference
In addition to all arguments above, the following attributes are exported:
id
- The Spot fleet request IDspotRequestState
- The state of the Spot fleet request.tagsAll
- A map of tags assigned to the resource, including those inherited from the providerdefaultTags
configuration block.
Timeouts
create
- (Default10M
)delete
- (Default15M
)
Import
Spot Fleet Requests can be imported using id
, e.g.,