Merge pull request #8112 from milescrabill/packer-googlecompute-validate-imagename

googlecompute: fail fast when image name is invalid, replace unusable characters w/ -'s
This commit is contained in:
Megan Marsh 2019-09-17 10:00:33 -07:00 committed by GitHub
commit 35357616e0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 6 deletions

View File

@ -17,7 +17,8 @@ import (
compute "google.golang.org/api/compute/v1"
)
var reImageFamily = regexp.MustCompile(`^[a-z]([-a-z0-9]{0,61}[a-z0-9])?$`)
// used for ImageName and ImageFamily
var validImageName = regexp.MustCompile(`^[a-z]([-a-z0-9]{0,61}[a-z0-9])?$`)
// Config is the configuration structure for the GCE builder. It stores
// both the publicly settable state as well as the privately generated
@ -142,17 +143,27 @@ func NewConfig(raws ...interface{}) (*Config, []string, error) {
}
}
// used for ImageName and ImageFamily
imageErrorText := "Invalid image %s %q: The first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash"
if len(c.ImageName) > 63 {
errs = packer.MultiErrorAppend(errs,
errors.New("Invalid image name: Must not be longer than 63 characters"))
}
if !validImageName.MatchString(c.ImageName) {
errs = packer.MultiErrorAppend(errs, errors.New(fmt.Sprintf(imageErrorText, "name", c.ImageName)))
}
if len(c.ImageFamily) > 63 {
errs = packer.MultiErrorAppend(errs,
errors.New("Invalid image family: Must not be longer than 63 characters"))
}
if c.ImageFamily != "" {
if !reImageFamily.MatchString(c.ImageFamily) {
errs = packer.MultiErrorAppend(errs,
errors.New("Invalid image family: The first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash"))
if !validImageName.MatchString(c.ImageFamily) {
errs = packer.MultiErrorAppend(errs, errors.New(fmt.Sprintf(imageErrorText, "family", c.ImageFamily)))
}
}
if c.InstanceName == "" {

View File

@ -156,6 +156,24 @@ func TestConfigPrepare(t *testing.T) {
"foo bar",
true,
},
{
// underscore is not allowed
"image_name",
"foo_bar",
true,
},
{
// too long
"image_name",
"foobar123xyz_abc-456-one-two_three_five_nine_seventeen_eleventy-seven",
true,
},
{
// starts with non-alphabetic character
"image_name",
"1boohoo",
true,
},
{
"image_encryption_key",
map[string]string{"kmsKeyName": "foo"},

View File

@ -20,7 +20,7 @@ func isalphanumeric(b byte) bool {
// Clean up image name by replacing invalid characters with "-"
// and converting upper cases to lower cases
func templateCleanImageName(s string) string {
if reImageFamily.MatchString(s) {
if validImageName.MatchString(s) {
return s
}
b := []byte(strings.ToLower(s))