github.com/supr/packer@v0.3.10-0.20131015195147-7b09e24ac3c1/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  }
    17  
    18  // Auth returns a valid aws.Auth object for access to AWS services, or
    19  // an error if the authentication couldn't be resolved.
    20  func (c *AccessConfig) Auth() (aws.Auth, error) {
    21  	auth, err := aws.GetAuth(c.AccessKey, c.SecretKey)
    22  	if err == nil {
    23  		// Store the accesskey and secret that we got...
    24  		c.AccessKey = auth.AccessKey
    25  		c.SecretKey = auth.SecretKey
    26  	}
    27  
    28  	return auth, err
    29  }
    30  
    31  // Region returns the aws.Region object for access to AWS services, requesting
    32  // the region from the instance metadata if possible.
    33  func (c *AccessConfig) Region() (aws.Region, error) {
    34  	if c.RawRegion != "" {
    35  		return aws.Regions[c.RawRegion], nil
    36  	}
    37  
    38  	md, err := aws.GetMetaData("placement/availability-zone")
    39  	if err != nil {
    40  		return aws.Region{}, err
    41  	}
    42  
    43  	region := strings.TrimRightFunc(string(md), unicode.IsLetter)
    44  	return aws.Regions[region], nil
    45  }
    46  
    47  func (c *AccessConfig) Prepare(t *packer.ConfigTemplate) []error {
    48  	if t == nil {
    49  		var err error
    50  		t, err = packer.NewConfigTemplate()
    51  		if err != nil {
    52  			return []error{err}
    53  		}
    54  	}
    55  
    56  	templates := map[string]*string{
    57  		"access_key": &c.AccessKey,
    58  		"secret_key": &c.SecretKey,
    59  		"region":     &c.RawRegion,
    60  	}
    61  
    62  	errs := make([]error, 0)
    63  	for n, ptr := range templates {
    64  		var err error
    65  		*ptr, err = t.Process(*ptr, nil)
    66  		if err != nil {
    67  			errs = append(
    68  				errs, fmt.Errorf("Error processing %s: %s", n, err))
    69  		}
    70  	}
    71  
    72  	if c.RawRegion != "" {
    73  		if _, ok := aws.Regions[c.RawRegion]; !ok {
    74  			errs = append(errs, fmt.Errorf("Unknown region: %s", c.RawRegion))
    75  		}
    76  	}
    77  
    78  	if len(errs) > 0 {
    79  		return errs
    80  	}
    81  
    82  	return nil
    83  }