github.com/pquerna/agent@v2.1.8+incompatible/agent/s3.go (about)

     1  package agent
     2  
     3  import (
     4  	"errors"
     5  	"os"
     6  	"time"
     7  
     8  	"github.com/AdRoll/goamz/aws"
     9  )
    10  
    11  func awsS3Auth() (aws.Auth, error) {
    12  	// First try to authenticate using the BUILDKITE_ ENV variables
    13  	buildkiteAuth, buildkiteErr := buildkiteS3EnvAuth()
    14  	if buildkiteErr == nil {
    15  		return buildkiteAuth, nil
    16  	}
    17  
    18  	// Passing blank values here instructs the AWS library to look at the
    19  	// current instances meta data for the security credentials.
    20  	awsAuth, awsErr := aws.GetAuth("", "", "", time.Time{})
    21  	if awsErr == nil {
    22  		return awsAuth, nil
    23  	}
    24  
    25  	var err error
    26  
    27  	// If they attempted to use the BUILDKITE_ ENV variables, return them
    28  	// that error, otherwise default to the error from AWS
    29  	if buildkiteErr != nil && buildkiteAuth.AccessKey != "" || buildkiteAuth.SecretKey != "" {
    30  		err = buildkiteErr
    31  	} else {
    32  		err = awsErr
    33  	}
    34  
    35  	return aws.Auth{}, err
    36  }
    37  
    38  func buildkiteS3EnvAuth() (auth aws.Auth, err error) {
    39  	auth.AccessKey = os.Getenv("BUILDKITE_S3_ACCESS_KEY_ID")
    40  	if auth.AccessKey == "" {
    41  		auth.AccessKey = os.Getenv("BUILDKITE_S3_ACCESS_KEY")
    42  	}
    43  
    44  	auth.SecretKey = os.Getenv("BUILDKITE_S3_SECRET_ACCESS_KEY")
    45  	if auth.SecretKey == "" {
    46  		auth.SecretKey = os.Getenv("BUILDKITE_S3_SECRET_KEY")
    47  	}
    48  
    49  	if auth.AccessKey == "" {
    50  		err = errors.New("BUILDKITE_S3_ACCESS_KEY_ID or BUILDKITE_S3_ACCESS_KEY not found in environment")
    51  	}
    52  	if auth.SecretKey == "" {
    53  		err = errors.New("BUILDKITE_S3_SECRET_ACCESS_KEY or BUILDKITE_S3_SECRET_KEY not found in environment")
    54  	}
    55  
    56  	return
    57  }
    58  
    59  func awsS3Region() (region aws.Region, err error) {
    60  	regionName := "us-east-1"
    61  	if os.Getenv("BUILDKITE_S3_DEFAULT_REGION") != "" {
    62  		regionName = os.Getenv("BUILDKITE_S3_DEFAULT_REGION")
    63  	} else if os.Getenv("AWS_DEFAULT_REGION") != "" {
    64  		regionName = os.Getenv("AWS_DEFAULT_REGION")
    65  	}
    66  
    67  	// Check to make sure the region exists. There is a GetRegion API, but
    68  	// there doesn't seem to be a way to make it error out if the region
    69  	// doesn't exist.
    70  	region, ok := aws.Regions[regionName]
    71  	if ok == false {
    72  		err = errors.New("Unknown AWS S3 Region `" + regionName + "`")
    73  	}
    74  
    75  	return
    76  }