Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow customizing spot allocation strategy #481

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .web-docs/components/builder/ebs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,12 @@ JSON example:
criteria provided in `source_ami_filter`; this pins the AMI returned by the
filter, but will cause Packer to fail if the `source_ami` does not exist.

- `spot_allocation_strategy` (string) - One of `price-capacity-optimized`, `capacity-optimized`, `diversified` or `lowest-price`.
The strategy that determines how to allocate the target Spot Instance capacity
across the Spot Instance pools specified by the EC2 Fleet launch configuration.
If this option is not set, Packer will use default option provided by the SDK (currently `lowest-price`).
For more information, see [Amazon EC2 User Guide] (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-allocation-strategy.html)

- `spot_instance_types` ([]string) - a list of acceptable instance
types to run your build on. We will request a spot instance using the max
price of spot_price and the allocation strategy of "lowest price".
Expand Down
6 changes: 6 additions & 0 deletions .web-docs/components/builder/ebssurrogate/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,12 @@ JSON example:
criteria provided in `source_ami_filter`; this pins the AMI returned by the
filter, but will cause Packer to fail if the `source_ami` does not exist.

- `spot_allocation_strategy` (string) - One of `price-capacity-optimized`, `capacity-optimized`, `diversified` or `lowest-price`.
The strategy that determines how to allocate the target Spot Instance capacity
across the Spot Instance pools specified by the EC2 Fleet launch configuration.
If this option is not set, Packer will use default option provided by the SDK (currently `lowest-price`).
For more information, see [Amazon EC2 User Guide] (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-allocation-strategy.html)

- `spot_instance_types` ([]string) - a list of acceptable instance
types to run your build on. We will request a spot instance using the max
price of spot_price and the allocation strategy of "lowest price".
Expand Down
6 changes: 6 additions & 0 deletions .web-docs/components/builder/ebsvolume/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,12 @@ https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concept
criteria provided in `source_ami_filter`; this pins the AMI returned by the
filter, but will cause Packer to fail if the `source_ami` does not exist.

- `spot_allocation_strategy` (string) - One of `price-capacity-optimized`, `capacity-optimized`, `diversified` or `lowest-price`.
The strategy that determines how to allocate the target Spot Instance capacity
across the Spot Instance pools specified by the EC2 Fleet launch configuration.
If this option is not set, Packer will use default option provided by the SDK (currently `lowest-price`).
For more information, see [Amazon EC2 User Guide] (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-allocation-strategy.html)

- `spot_instance_types` ([]string) - a list of acceptable instance
types to run your build on. We will request a spot instance using the max
price of spot_price and the allocation strategy of "lowest price".
Expand Down
6 changes: 6 additions & 0 deletions .web-docs/components/builder/instance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -790,6 +790,12 @@ JSON example:
criteria provided in `source_ami_filter`; this pins the AMI returned by the
filter, but will cause Packer to fail if the `source_ami` does not exist.

- `spot_allocation_strategy` (string) - One of `price-capacity-optimized`, `capacity-optimized`, `diversified` or `lowest-price`.
The strategy that determines how to allocate the target Spot Instance capacity
across the Spot Instance pools specified by the EC2 Fleet launch configuration.
If this option is not set, Packer will use default option provided by the SDK (currently `lowest-price`).
For more information, see [Amazon EC2 User Guide] (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-allocation-strategy.html)

- `spot_instance_types` ([]string) - a list of acceptable instance
types to run your build on. We will request a spot instance using the max
price of spot_price and the allocation strategy of "lowest price".
Expand Down
15 changes: 15 additions & 0 deletions builder/common/run_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ import (
"net"
"os"
"regexp"
"slices"
"strings"
"time"

"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/packer-plugin-sdk/communicator"
"github.com/hashicorp/packer-plugin-sdk/template/config"
confighelper "github.com/hashicorp/packer-plugin-sdk/template/config"
Expand Down Expand Up @@ -402,6 +404,12 @@ type RunConfig struct {
// criteria provided in `source_ami_filter`; this pins the AMI returned by the
// filter, but will cause Packer to fail if the `source_ami` does not exist.
SourceAmiFilter AmiFilterOptions `mapstructure:"source_ami_filter" required:"false"`
// One of `price-capacity-optimized`, `capacity-optimized`, `diversified` or `lowest-price`.
// The strategy that determines how to allocate the target Spot Instance capacity
// across the Spot Instance pools specified by the EC2 Fleet launch configuration.
// If this option is not set, Packer will use default option provided by the SDK (currently `lowest-price`).
// For more information, see [Amazon EC2 User Guide] (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-allocation-strategy.html)
SpotAllocationStrategy string `mapstructure:"spot_allocation_strategy" required:"false"`
// a list of acceptable instance
// types to run your build on. We will request a spot instance using the max
// price of spot_price and the allocation strategy of "lowest price".
Expand Down Expand Up @@ -843,6 +851,13 @@ func (c *RunConfig) Prepare(ctx *interpolate.Context) []error {
}
}

if c.SpotAllocationStrategy != "" {
if !slices.Contains(ec2.SpotAllocationStrategy_Values(), c.SpotAllocationStrategy) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe both ifs can be mutualised

Suggested change
if !slices.Contains(ec2.SpotAllocationStrategy_Values(), c.SpotAllocationStrategy) {
if c.SpotAllocationStrategy != "" && !slices.Contains(ec2.SpotAllocationStrategy_Values(), c.SpotAllocationStrategy) {

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also to reply to your question in a comment from a previous review: using slices.Contains is fine by my standards! No need to make it manual, I suspect those were made this way in other cases because either the function did not exist at the time it was added, or whomever implemented it wasn't aware it existed, functionally it is essentially the same, might as well use what the library offers us.

errs = append(errs, fmt.Errorf(
"Unknown spot_allocation_strategy: %s", c.SpotAllocationStrategy))
}
}

if c.UserData != "" && c.UserDataFile != "" {
errs = append(errs, fmt.Errorf("Only one of user_data or user_data_file can be specified."))
} else if c.UserDataFile != "" {
Expand Down
10 changes: 10 additions & 0 deletions builder/common/run_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -461,3 +461,13 @@ func TestRunConfigPrepare_InvalidTenantForHost(t *testing.T) {
})
}
}

func TestRunConfigPrepare_EnableSpotInstanceBadSpotAllocationStrategy(t *testing.T) {
c := testConfig()
// There should be some error when Spot Allocation Strategy is invalid.
c.SpotAllocationStrategy = "very-expensive-one"
err := c.Prepare(nil)
if len(err) != 1 {
t.Fatalf("Should error if spot_allocation_strategy is invalid.")
}
}
7 changes: 7 additions & 0 deletions builder/common/step_run_spot_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ type StepRunSpotInstance struct {
InstanceType string
Region string
SourceAMI string
SpotAllocationStrategy string
SpotPrice string
SpotTags map[string]string
SpotInstanceTypes []string
Expand Down Expand Up @@ -383,6 +384,12 @@ func (s *StepRunSpotInstance) Run(ctx context.Context, state multistep.StateBag)
Type: aws.String("instant"),
}

if s.SpotAllocationStrategy != "" {
createFleetInput.SpotOptions = &ec2.SpotOptionsRequest{
AllocationStrategy: aws.String(s.SpotAllocationStrategy),
}
}

fleetTags, err := TagMap(s.FleetTags).EC2Tags(s.Ctx, s.Region, state)
if err != nil {
err := fmt.Errorf("Error generating fleet tags: %s", err)
Expand Down
5 changes: 5 additions & 0 deletions builder/common/step_run_spot_instance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ func getBasicStep() *StepRunSpotInstance {
Region: "us-east-1",
SourceAMI: "",
SpotPrice: "auto",
SpotAllocationStrategy: "price-capacity-optimized",
SpotTags: nil,
Tags: map[string]string{},
VolumeTags: nil,
Expand Down Expand Up @@ -250,6 +251,7 @@ func TestRun(t *testing.T) {
spotRequestId := aws.String("spot-id")
volumeId := aws.String("volume-id")
launchTemplateId := aws.String("launchTemplateId")
spotAllocationStrategy := aws.String("price-capacity-optimized")
ec2Mock := defaultEc2Mock(instanceId, spotRequestId, volumeId, launchTemplateId)

uiMock := packersdk.TestUi(t)
Expand Down Expand Up @@ -318,6 +320,9 @@ func TestRun(t *testing.T) {
if *ec2Mock.CreateFleetParams[0].LaunchTemplateConfigs[0].LaunchTemplateSpecification.LaunchTemplateName != *launchTemplateName {
t.Fatalf("launchTemplateName should match in createLaunchTemplate and createFleet requests")
}
if *ec2Mock.CreateFleetParams[0].SpotOptions.AllocationStrategy != *spotAllocationStrategy {
t.Fatalf("AllocationStrategy in CreateFleet request should match with spotAllocationStrategy param.")
}

fleetNameTag := ec2Mock.CreateFleetParams[0].TagSpecifications[0].Tags[0]
if *fleetNameTag.Key != "fleet-tag" || *fleetNameTag.Value != "fleet-tag-value" {
Expand Down
1 change: 1 addition & 0 deletions builder/ebs/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ func (b *Builder) Run(ctx context.Context, ui packersdk.Ui, hook packersdk.Hook)
SpotTags: b.config.SpotTags,
Tags: b.config.RunTags,
SpotInstanceTypes: b.config.SpotInstanceTypes,
SpotAllocationStrategy: b.config.RunConfig.SpotAllocationStrategy,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this setting should be replicated to other builders, assuming this is compatible with them.
Otherwise I would suggest either:

  1. moving that argument to builder/ebs/config.go so it is not common
  2. checking that it is not set in the configs for the builders that aren't compatible with it, this can be done in the Prepare function for each builder.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: if the ebs builder's the only one to support spot instances, I would suggest going with approach 1

UserData: b.config.UserData,
UserDataFile: b.config.UserDataFile,
VolumeTags: b.config.VolumeRunTags,
Expand Down
2 changes: 2 additions & 0 deletions builder/ebs/builder.hcl2spec.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions builder/ebssurrogate/builder.hcl2spec.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions builder/ebsvolume/builder.hcl2spec.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions builder/instance/builder.hcl2spec.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions docs-partials/builder/common/RunConfig-not-required.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,12 @@
criteria provided in `source_ami_filter`; this pins the AMI returned by the
filter, but will cause Packer to fail if the `source_ami` does not exist.

- `spot_allocation_strategy` (string) - One of `price-capacity-optimized`, `capacity-optimized`, `diversified` or `lowest-price`.
The strategy that determines how to allocate the target Spot Instance capacity
across the Spot Instance pools specified by the EC2 Fleet launch configuration.
If this option is not set, Packer will use default option provided by the SDK (currently `lowest-price`).
For more information, see [Amazon EC2 User Guide] (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-allocation-strategy.html)

- `spot_instance_types` ([]string) - a list of acceptable instance
types to run your build on. We will request a spot instance using the max
price of spot_price and the allocation strategy of "lowest price".
Expand Down