diff --git a/builder/googlecompute/config.go b/builder/googlecompute/config.go index add586483..fcead5cfe 100644 --- a/builder/googlecompute/config.go +++ b/builder/googlecompute/config.go @@ -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,29 @@ func NewConfig(raws ...interface{}) (*Config, []string, error) { } } + // used for ImageName and ImageFamily + imageErrorText := "Invalid image %s: 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")) + } + + // replaces invalid characters with hyphens + c.ImageName = templateCleanImageName(c.ImageName) + if !validImageName.MatchString(c.ImageName) { + errs = packer.MultiErrorAppend(errs, errors.New(fmt.Sprintf(imageErrorText, "name"))) + } + 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"))) } - } if c.InstanceName == "" { diff --git a/builder/googlecompute/template_funcs.go b/builder/googlecompute/template_funcs.go index 14d1c4b2f..bf57f3d96 100644 --- a/builder/googlecompute/template_funcs.go +++ b/builder/googlecompute/template_funcs.go @@ -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))