2019-10-14 16:43:59 +02:00
//go:generate mapstructure-to-hcl2 -type ImageDestination
2019-10-12 16:46:21 +08:00
package common
2019-06-13 15:16:49 +08:00
import (
"fmt"
"regexp"
2019-10-14 16:43:59 +02:00
"github.com/hashicorp/packer/template/interpolate"
2019-06-13 15:16:49 +08:00
)
type ImageDestination struct {
ProjectId string ` mapstructure:"project_id" `
Region string ` mapstructure:"region" `
Name string ` mapstructure:"name" `
Description string ` mapstructure:"description" `
}
type ImageConfig struct {
2019-10-18 14:52:20 +08:00
ImageName string ` mapstructure:"image_name" `
ImageDescription string ` mapstructure:"image_description" `
ImageDestinations [ ] ImageDestination ` mapstructure:"image_copy_to_mappings" `
WaitImageReadyTimeout int ` mapstructure:"wait_image_ready_timeout" `
2019-06-13 15:16:49 +08:00
}
2019-10-18 14:52:20 +08:00
var ImageNamePattern = regexp . MustCompile ( ` ^[A-Za-z0-9\p { Han}-_\[\]:,.] { 1,63}$ ` )
2019-06-13 15:16:49 +08:00
func ( c * ImageConfig ) Prepare ( ctx * interpolate . Context ) [ ] error {
var errs [ ] error
imageName := c . ImageName
if imageName == "" {
errs = append ( errs , fmt . Errorf ( "%q must be set" , "image_name" ) )
2019-10-18 14:52:20 +08:00
} else if ! ImageNamePattern . MatchString ( imageName ) {
2019-06-13 15:16:49 +08:00
errs = append ( errs , fmt . Errorf ( "expected %q to be 1-63 characters and only support chinese, english, numbers, '-_,.:[]', got %q" , "image_name" , imageName ) )
}
if len ( c . ImageDestinations ) > 0 {
for _ , imageDestination := range c . ImageDestinations {
if imageDestination . Name == "" {
imageDestination . Name = imageName
}
2019-06-19 21:32:33 +08:00
2019-06-13 15:16:49 +08:00
errs = append ( errs , imageDestination . validate ( ) ... )
}
}
2019-10-18 14:52:20 +08:00
if c . WaitImageReadyTimeout <= 0 {
2019-10-24 17:10:48 +08:00
c . WaitImageReadyTimeout = DefaultCreateImageTimeout
2019-10-18 14:52:20 +08:00
}
2019-06-13 15:16:49 +08:00
if len ( errs ) > 0 {
return errs
}
return nil
}
func ( imageDestination * ImageDestination ) validate ( ) [ ] error {
var errs [ ] error
if imageDestination . Region == "" {
errs = append ( errs , fmt . Errorf ( "%q must be set" , "image_copy_region" ) )
}
if imageDestination . ProjectId == "" {
errs = append ( errs , fmt . Errorf ( "%q must be set" , "image_copy_project" ) )
}
2019-10-18 14:52:20 +08:00
if imageDestination . Name != "" && ! ImageNamePattern . MatchString ( imageDestination . Name ) {
2019-06-13 15:16:49 +08:00
errs = append ( errs , fmt . Errorf ( "expected %q to be 1-63 characters and only support chinese, english, numbers, '-_,.:[]', got %q" , "image_copy_name" , imageDestination . Name ) )
}
return errs
}