github.com/phobos182/packer@v0.2.3-0.20130819023704-c84d2aeffc68/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  	return aws.GetAuth(c.AccessKey, c.SecretKey)
    22  }
    23  
    24  // Region returns the aws.Region object for access to AWS services, requesting
    25  // the region from the instance metadata if possible.
    26  func (c *AccessConfig) Region() (aws.Region, error) {
    27  	if c.RawRegion != "" {
    28  		return aws.Regions[c.RawRegion], nil
    29  	}
    30  
    31  	md, err := aws.GetMetaData("placement/availability-zone")
    32  	if err != nil {
    33  		return aws.Region{}, err
    34  	}
    35  
    36  	region := strings.TrimRightFunc(string(md), unicode.IsLetter)
    37  	return aws.Regions[region], nil
    38  }
    39  
    40  func (c *AccessConfig) Prepare(t *packer.ConfigTemplate) []error {
    41  	if t == nil {
    42  		var err error
    43  		t, err = packer.NewConfigTemplate()
    44  		if err != nil {
    45  			return []error{err}
    46  		}
    47  	}
    48  
    49  	templates := map[string]*string{
    50  		"access_key": &c.AccessKey,
    51  		"secret_key": &c.SecretKey,
    52  		"region":     &c.RawRegion,
    53  	}
    54  
    55  	errs := make([]error, 0)
    56  	for n, ptr := range templates {
    57  		var err error
    58  		*ptr, err = t.Process(*ptr, nil)
    59  		if err != nil {
    60  			errs = append(
    61  				errs, fmt.Errorf("Error processing %s: %s", n, err))
    62  		}
    63  	}
    64  
    65  	if c.RawRegion != "" {
    66  		if _, ok := aws.Regions[c.RawRegion]; !ok {
    67  			errs = append(errs, fmt.Errorf("Unknown region: %s", c.RawRegion))
    68  		}
    69  	}
    70  
    71  	if len(errs) > 0 {
    72  		return errs
    73  	}
    74  
    75  	return nil
    76  }