diff --git a/builder/amazon/common/ami_config.go b/builder/amazon/common/ami_config.go index 4f6cd7316..21438a50b 100644 --- a/builder/amazon/common/ami_config.go +++ b/builder/amazon/common/ami_config.go @@ -2,6 +2,7 @@ package common import ( "fmt" + "regexp" "github.com/hashicorp/packer/template/interpolate" ) @@ -68,6 +69,15 @@ func (c *AMIConfig) Prepare(ctx *interpolate.Context) []error { errs = append(errs, fmt.Errorf("Cannot share snapshot encrypted with default KMS key")) } + if len(c.AMIName) < 3 || len(c.AMIName) > 128 { + errs = append(errs, fmt.Errorf("AMIName must be between 3 and 128 characters long")) + } + + var IsValidName = regexp.MustCompile(`^[a-zA-Z().-/_]+$`).MatchString + if !IsValidName(c.AMIName) { + errs = append(errs, fmt.Errorf("AMIName should only contain letters, numbers, '(', ')', '.', '-', '/' and '_'")) + } + if len(errs) > 0 { return errs } diff --git a/builder/amazon/common/ami_config_test.go b/builder/amazon/common/ami_config_test.go index ecb88bcb4..beccb98a2 100644 --- a/builder/amazon/common/ami_config_test.go +++ b/builder/amazon/common/ami_config_test.go @@ -74,3 +74,26 @@ func TestAMIConfigPrepare_Share_EncryptedBoot(t *testing.T) { t.Fatal("shouldn't be able to share ami with encrypted boot volume") } } + +func TestAMINameValidation(t *testing.T) { + c := testAMIConfig() + + c.AMIName = "aa" + if err := c.Prepare(nil); err == nil { + t.Fatal("shouldn't be able to have an ami name with less than 3 characters") + } + + var longAmiName string + for i := 0; i < 129; i++ { + longAmiName += "a" + } + c.AMIName = longAmiName + if err := c.Prepare(nil); err == nil { + t.Fatal("shouldn't be able to have an ami name with great than 128 characters") + } + + c.AMIName = "+aaa" + if err := c.Prepare(nil); err == nil { + t.Fatal("shouldn't be able to have an ami name with invalid characters") + } +}