github.com/askholme/packer@v0.7.2-0.20140924152349-70d9566a6852/builder/amazon/common/access_config.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/goamz/aws"
     6  	"github.com/mitchellh/packer/packer"
     7  	"strings"
     8  	"unicode"
     9  )
    10  
    11  // AccessConfig is for common configuration related to AWS access
    12  type AccessConfig struct {
    13  	AccessKey string `mapstructure:"access_key"`
    14  	SecretKey string `mapstructure:"secret_key"`
    15  	RawRegion string `mapstructure:"region"`
    16  	Token     string `mapstructure:"token"`
    17  }
    18  
    19  // Auth returns a valid aws.Auth object for access to AWS services, or
    20  // an error if the authentication couldn't be resolved.
    21  func (c *AccessConfig) Auth() (aws.Auth, error) {
    22  	auth, err := aws.GetAuth(c.AccessKey, c.SecretKey)
    23  	if err == nil {
    24  		// Store the accesskey and secret that we got...
    25  		c.AccessKey = auth.AccessKey
    26  		c.SecretKey = auth.SecretKey
    27  		c.Token = auth.Token
    28  	}
    29  	if auth.Token == "" && c.Token != "" {
    30  		auth.Token = c.Token
    31  	}
    32  
    33  	return auth, err
    34  }
    35  
    36  // Region returns the aws.Region object for access to AWS services, requesting
    37  // the region from the instance metadata if possible.
    38  func (c *AccessConfig) Region() (aws.Region, error) {
    39  	if c.RawRegion != "" {
    40  		return aws.Regions[c.RawRegion], nil
    41  	}
    42  
    43  	md, err := aws.GetMetaData("placement/availability-zone")
    44  	if err != nil {
    45  		return aws.Region{}, err
    46  	}
    47  
    48  	region := strings.TrimRightFunc(string(md), unicode.IsLetter)
    49  	return aws.Regions[region], nil
    50  }
    51  
    52  func (c *AccessConfig) Prepare(t *packer.ConfigTemplate) []error {
    53  	if t == nil {
    54  		var err error
    55  		t, err = packer.NewConfigTemplate()
    56  		if err != nil {
    57  			return []error{err}
    58  		}
    59  	}
    60  
    61  	templates := map[string]*string{
    62  		"access_key": &c.AccessKey,
    63  		"secret_key": &c.SecretKey,
    64  		"region":     &c.RawRegion,
    65  	}
    66  
    67  	errs := make([]error, 0)
    68  	for n, ptr := range templates {
    69  		var err error
    70  		*ptr, err = t.Process(*ptr, nil)
    71  		if err != nil {
    72  			errs = append(
    73  				errs, fmt.Errorf("Error processing %s: %s", n, err))
    74  		}
    75  	}
    76  
    77  	if c.RawRegion != "" {
    78  		if _, ok := aws.Regions[c.RawRegion]; !ok {
    79  			errs = append(errs, fmt.Errorf("Unknown region: %s", c.RawRegion))
    80  		}
    81  	}
    82  
    83  	if len(errs) > 0 {
    84  		return errs
    85  	}
    86  
    87  	return nil
    88  }