Skip to content

Commit

Permalink
move spot_allocation_strategy check to prepare step
Browse files Browse the repository at this point in the history
  • Loading branch information
vucong2409 committed May 11, 2024
1 parent 643bd38 commit b12598c
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
9 changes: 9 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 @@ -849,6 +851,13 @@ func (c *RunConfig) Prepare(ctx *interpolate.Context) []error {
}
}

if c.SpotAllocationStrategy != "" {
if slices.Contains(ec2.SpotAllocationStrategy_Values(), c.SpotAllocationStrategy) {
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.")
}
}
3 changes: 1 addition & 2 deletions builder/common/step_run_spot_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"fmt"
"io/ioutil"
"log"
"slices"
"strings"
"time"

Expand Down Expand Up @@ -385,7 +384,7 @@ func (s *StepRunSpotInstance) Run(ctx context.Context, state multistep.StateBag)
Type: aws.String("instant"),
}

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

0 comments on commit b12598c

Please sign in to comment.