packer-cn/builder/oneandone/config.go

115 lines
2.5 KiB
Go
Raw Normal View History

//go:generate mapstructure-to-hcl2 -type Config
2016-11-13 17:34:36 -05:00
package oneandone
import (
2016-11-15 18:17:30 -05:00
"errors"
2018-01-22 20:21:10 -05:00
"os"
"strings"
2016-11-13 17:34:36 -05:00
"github.com/1and1/oneandone-cloudserver-sdk-go"
2017-04-04 16:39:01 -04:00
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/communicator"
"github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/template/interpolate"
2016-11-13 17:34:36 -05:00
"github.com/mitchellh/mapstructure"
)
type Config struct {
common.PackerConfig `mapstructure:",squash"`
Comm communicator.Config `mapstructure:",squash"`
2016-11-15 18:17:30 -05:00
Token string `mapstructure:"token"`
Url string `mapstructure:"url"`
SnapshotName string `mapstructure:"image_name"`
DataCenterName string `mapstructure:"data_center_name"`
DataCenterId string
Image string `mapstructure:"source_image_name"`
DiskSize int `mapstructure:"disk_size"`
Retries int `mapstructure:"retries"`
2016-11-15 18:17:30 -05:00
ctx interpolate.Context
2016-11-13 17:34:36 -05:00
}
func NewConfig(raws ...interface{}) (*Config, []string, error) {
var c Config
var md mapstructure.Metadata
err := config.Decode(&c, &config.DecodeOpts{
Metadata: &md,
Interpolate: true,
InterpolateContext: &c.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{
"run_command",
},
},
}, raws...)
if err != nil {
return nil, nil, err
}
var errs *packer.MultiError
2016-11-15 18:17:30 -05:00
if c.SnapshotName == "" {
def, err := interpolate.Render("packer-{{timestamp}}", nil)
if err != nil {
panic(err)
}
// Default to packer-{{ unix timestamp (utc) }}
c.SnapshotName = def
}
if c.Image == "" {
errs = packer.MultiErrorAppend(
errs, errors.New("1&1 'image' is required"))
}
2016-11-13 17:34:36 -05:00
if c.Token == "" {
c.Token = os.Getenv("ONEANDONE_TOKEN")
}
if c.Url == "" {
c.Url = oneandone.BaseUrl
}
if c.DiskSize == 0 {
c.DiskSize = 50
}
2016-11-15 18:17:30 -05:00
if c.Retries == 0 {
c.Retries = 600
2016-11-13 17:34:36 -05:00
}
2016-11-15 18:17:30 -05:00
if c.DataCenterName != "" {
token := oneandone.SetToken(c.Token)
//Create an API client
api := oneandone.New(token, c.Url)
dcs, err := api.ListDatacenters()
if err != nil {
errs = packer.MultiErrorAppend(
errs, err)
}
for _, dc := range dcs {
if strings.ToLower(dc.CountryCode) == strings.ToLower(c.DataCenterName) {
c.DataCenterId = dc.Id
break
}
}
2016-11-13 17:34:36 -05:00
}
if es := c.Comm.Prepare(&c.ctx); len(es) > 0 {
errs = packer.MultiErrorAppend(errs, es...)
}
if errs != nil && len(errs.Errors) > 0 {
return nil, nil, errs
}
packer.LogSecretFilter.Set(c.Token)
2016-11-13 17:34:36 -05:00
return &c, nil, nil
}