googlecompute: fail fast when image name is invalid, replace unusable characters w/ -'s

This commit is contained in:
Miles Crabill 2019-09-16 10:10:37 -07:00
parent 2e58b807de
commit c11a444f77
No known key found for this signature in database
GPG Key ID: 931A9CF57AEAC02D
2 changed files with 19 additions and 6 deletions

View File

@ -17,7 +17,8 @@ import (
compute "google.golang.org/api/compute/v1" 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 // Config is the configuration structure for the GCE builder. It stores
// both the publicly settable state as well as the privately generated // 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 { if len(c.ImageFamily) > 63 {
errs = packer.MultiErrorAppend(errs, errs = packer.MultiErrorAppend(errs,
errors.New("Invalid image family: Must not be longer than 63 characters")) errors.New("Invalid image family: Must not be longer than 63 characters"))
} }
if c.ImageFamily != "" { if c.ImageFamily != "" {
if !reImageFamily.MatchString(c.ImageFamily) { if !validImageName.MatchString(c.ImageFamily) {
errs = packer.MultiErrorAppend(errs, errs = packer.MultiErrorAppend(errs, errors.New(fmt.Sprintf(imageErrorText, "family")))
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 c.InstanceName == "" { if c.InstanceName == "" {

View File

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