github.com/grange74/terraform@v0.7.0-rc3.0.20160722171430-8c8803864753/builtin/providers/aws/config.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/http"
     7  	"strings"
     8  
     9  	"github.com/hashicorp/go-cleanhttp"
    10  	"github.com/hashicorp/go-multierror"
    11  	"github.com/hashicorp/terraform/helper/logging"
    12  	"github.com/hashicorp/terraform/terraform"
    13  
    14  	"crypto/tls"
    15  
    16  	"github.com/aws/aws-sdk-go/aws"
    17  	"github.com/aws/aws-sdk-go/aws/awserr"
    18  	"github.com/aws/aws-sdk-go/aws/request"
    19  	"github.com/aws/aws-sdk-go/aws/session"
    20  	"github.com/aws/aws-sdk-go/service/apigateway"
    21  	"github.com/aws/aws-sdk-go/service/autoscaling"
    22  	"github.com/aws/aws-sdk-go/service/cloudformation"
    23  	"github.com/aws/aws-sdk-go/service/cloudfront"
    24  	"github.com/aws/aws-sdk-go/service/cloudtrail"
    25  	"github.com/aws/aws-sdk-go/service/cloudwatch"
    26  	"github.com/aws/aws-sdk-go/service/cloudwatchevents"
    27  	"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
    28  	"github.com/aws/aws-sdk-go/service/codecommit"
    29  	"github.com/aws/aws-sdk-go/service/codedeploy"
    30  	"github.com/aws/aws-sdk-go/service/directoryservice"
    31  	"github.com/aws/aws-sdk-go/service/dynamodb"
    32  	"github.com/aws/aws-sdk-go/service/ec2"
    33  	"github.com/aws/aws-sdk-go/service/ecr"
    34  	"github.com/aws/aws-sdk-go/service/ecs"
    35  	"github.com/aws/aws-sdk-go/service/efs"
    36  	"github.com/aws/aws-sdk-go/service/elasticache"
    37  	"github.com/aws/aws-sdk-go/service/elasticbeanstalk"
    38  	elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice"
    39  	"github.com/aws/aws-sdk-go/service/elastictranscoder"
    40  	"github.com/aws/aws-sdk-go/service/elb"
    41  	"github.com/aws/aws-sdk-go/service/emr"
    42  	"github.com/aws/aws-sdk-go/service/firehose"
    43  	"github.com/aws/aws-sdk-go/service/glacier"
    44  	"github.com/aws/aws-sdk-go/service/iam"
    45  	"github.com/aws/aws-sdk-go/service/kinesis"
    46  	"github.com/aws/aws-sdk-go/service/kms"
    47  	"github.com/aws/aws-sdk-go/service/lambda"
    48  	"github.com/aws/aws-sdk-go/service/opsworks"
    49  	"github.com/aws/aws-sdk-go/service/rds"
    50  	"github.com/aws/aws-sdk-go/service/redshift"
    51  	"github.com/aws/aws-sdk-go/service/route53"
    52  	"github.com/aws/aws-sdk-go/service/s3"
    53  	"github.com/aws/aws-sdk-go/service/ses"
    54  	"github.com/aws/aws-sdk-go/service/simpledb"
    55  	"github.com/aws/aws-sdk-go/service/sns"
    56  	"github.com/aws/aws-sdk-go/service/sqs"
    57  	"github.com/aws/aws-sdk-go/service/sts"
    58  )
    59  
    60  type Config struct {
    61  	AccessKey     string
    62  	SecretKey     string
    63  	CredsFilename string
    64  	Profile       string
    65  	Token         string
    66  	Region        string
    67  	MaxRetries    int
    68  
    69  	AllowedAccountIds   []interface{}
    70  	ForbiddenAccountIds []interface{}
    71  
    72  	DynamoDBEndpoint string
    73  	KinesisEndpoint  string
    74  	Ec2Endpoint      string
    75  	IamEndpoint      string
    76  	ElbEndpoint      string
    77  	Insecure         bool
    78  }
    79  
    80  type AWSClient struct {
    81  	cfconn                *cloudformation.CloudFormation
    82  	cloudfrontconn        *cloudfront.CloudFront
    83  	cloudtrailconn        *cloudtrail.CloudTrail
    84  	cloudwatchconn        *cloudwatch.CloudWatch
    85  	cloudwatchlogsconn    *cloudwatchlogs.CloudWatchLogs
    86  	cloudwatcheventsconn  *cloudwatchevents.CloudWatchEvents
    87  	dsconn                *directoryservice.DirectoryService
    88  	dynamodbconn          *dynamodb.DynamoDB
    89  	ec2conn               *ec2.EC2
    90  	ecrconn               *ecr.ECR
    91  	ecsconn               *ecs.ECS
    92  	efsconn               *efs.EFS
    93  	elbconn               *elb.ELB
    94  	emrconn               *emr.EMR
    95  	esconn                *elasticsearch.ElasticsearchService
    96  	apigateway            *apigateway.APIGateway
    97  	autoscalingconn       *autoscaling.AutoScaling
    98  	s3conn                *s3.S3
    99  	sesConn               *ses.SES
   100  	simpledbconn          *simpledb.SimpleDB
   101  	sqsconn               *sqs.SQS
   102  	snsconn               *sns.SNS
   103  	stsconn               *sts.STS
   104  	redshiftconn          *redshift.Redshift
   105  	r53conn               *route53.Route53
   106  	accountid             string
   107  	region                string
   108  	rdsconn               *rds.RDS
   109  	iamconn               *iam.IAM
   110  	kinesisconn           *kinesis.Kinesis
   111  	kmsconn               *kms.KMS
   112  	firehoseconn          *firehose.Firehose
   113  	elasticacheconn       *elasticache.ElastiCache
   114  	elasticbeanstalkconn  *elasticbeanstalk.ElasticBeanstalk
   115  	elastictranscoderconn *elastictranscoder.ElasticTranscoder
   116  	lambdaconn            *lambda.Lambda
   117  	opsworksconn          *opsworks.OpsWorks
   118  	glacierconn           *glacier.Glacier
   119  	codedeployconn        *codedeploy.CodeDeploy
   120  	codecommitconn        *codecommit.CodeCommit
   121  }
   122  
   123  // Client configures and returns a fully initialized AWSClient
   124  func (c *Config) Client() (interface{}, error) {
   125  	// Get the auth and region. This can fail if keys/regions were not
   126  	// specified and we're attempting to use the environment.
   127  	var errs []error
   128  
   129  	log.Println("[INFO] Building AWS region structure")
   130  	err := c.ValidateRegion()
   131  	if err != nil {
   132  		errs = append(errs, err)
   133  	}
   134  
   135  	var client AWSClient
   136  	if len(errs) == 0 {
   137  		// store AWS region in client struct, for region specific operations such as
   138  		// bucket storage in S3
   139  		client.region = c.Region
   140  
   141  		log.Println("[INFO] Building AWS auth structure")
   142  		creds := GetCredentials(c.AccessKey, c.SecretKey, c.Token, c.Profile, c.CredsFilename)
   143  		// Call Get to check for credential provider. If nothing found, we'll get an
   144  		// error, and we can present it nicely to the user
   145  		cp, err := creds.Get()
   146  		if err != nil {
   147  			if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" {
   148  				errs = append(errs, fmt.Errorf(`No valid credential sources found for AWS Provider.
   149    Please see https://terraform.io/docs/providers/aws/index.html for more information on
   150    providing credentials for the AWS Provider`))
   151  			} else {
   152  				errs = append(errs, fmt.Errorf("Error loading credentials for AWS Provider: %s", err))
   153  			}
   154  			return nil, &multierror.Error{Errors: errs}
   155  		}
   156  
   157  		log.Printf("[INFO] AWS Auth provider used: %q", cp.ProviderName)
   158  
   159  		awsConfig := &aws.Config{
   160  			Credentials: creds,
   161  			Region:      aws.String(c.Region),
   162  			MaxRetries:  aws.Int(c.MaxRetries),
   163  			HTTPClient:  cleanhttp.DefaultClient(),
   164  		}
   165  
   166  		if logging.IsDebugOrHigher() {
   167  			awsConfig.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
   168  			awsConfig.Logger = awsLogger{}
   169  		}
   170  
   171  		if c.Insecure {
   172  			transport := awsConfig.HTTPClient.Transport.(*http.Transport)
   173  			transport.TLSClientConfig = &tls.Config{
   174  				InsecureSkipVerify: true,
   175  			}
   176  		}
   177  
   178  		// Set up base session
   179  		sess := session.New(awsConfig)
   180  		sess.Handlers.Build.PushFrontNamed(addTerraformVersionToUserAgent)
   181  
   182  		// Some services exist only in us-east-1, e.g. because they manage
   183  		// resources that can span across multiple regions, or because
   184  		// signature format v4 requires region to be us-east-1 for global
   185  		// endpoints:
   186  		// http://docs.aws.amazon.com/general/latest/gr/sigv4_changes.html
   187  		usEast1Sess := sess.Copy(&aws.Config{Region: aws.String("us-east-1")})
   188  
   189  		// Some services have user-configurable endpoints
   190  		awsEc2Sess := sess.Copy(&aws.Config{Endpoint: aws.String(c.Ec2Endpoint)})
   191  		awsElbSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.ElbEndpoint)})
   192  		awsIamSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.IamEndpoint)})
   193  		dynamoSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.DynamoDBEndpoint)})
   194  		kinesisSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.KinesisEndpoint)})
   195  
   196  		// These two services need to be set up early so we can check on AccountID
   197  		client.iamconn = iam.New(awsIamSess)
   198  		client.stsconn = sts.New(sess)
   199  
   200  		err = c.ValidateCredentials(client.stsconn)
   201  		if err != nil {
   202  			errs = append(errs, err)
   203  			return nil, &multierror.Error{Errors: errs}
   204  		}
   205  		accountId, err := GetAccountId(client.iamconn, client.stsconn, cp.ProviderName)
   206  		if err == nil {
   207  			client.accountid = accountId
   208  		}
   209  
   210  		authErr := c.ValidateAccountId(client.accountid)
   211  		if authErr != nil {
   212  			errs = append(errs, authErr)
   213  		}
   214  
   215  		client.apigateway = apigateway.New(sess)
   216  		client.autoscalingconn = autoscaling.New(sess)
   217  		client.cfconn = cloudformation.New(sess)
   218  		client.cloudfrontconn = cloudfront.New(sess)
   219  		client.cloudtrailconn = cloudtrail.New(sess)
   220  		client.cloudwatchconn = cloudwatch.New(sess)
   221  		client.cloudwatcheventsconn = cloudwatchevents.New(sess)
   222  		client.cloudwatchlogsconn = cloudwatchlogs.New(sess)
   223  		client.codecommitconn = codecommit.New(usEast1Sess)
   224  		client.codedeployconn = codedeploy.New(sess)
   225  		client.dsconn = directoryservice.New(sess)
   226  		client.dynamodbconn = dynamodb.New(dynamoSess)
   227  		client.ec2conn = ec2.New(awsEc2Sess)
   228  		client.ecrconn = ecr.New(sess)
   229  		client.ecsconn = ecs.New(sess)
   230  		client.efsconn = efs.New(sess)
   231  		client.elasticacheconn = elasticache.New(sess)
   232  		client.elasticbeanstalkconn = elasticbeanstalk.New(sess)
   233  		client.elastictranscoderconn = elastictranscoder.New(sess)
   234  		client.elbconn = elb.New(awsElbSess)
   235  		client.emrconn = emr.New(sess)
   236  		client.esconn = elasticsearch.New(sess)
   237  		client.firehoseconn = firehose.New(sess)
   238  		client.glacierconn = glacier.New(sess)
   239  		client.kinesisconn = kinesis.New(kinesisSess)
   240  		client.kmsconn = kms.New(sess)
   241  		client.lambdaconn = lambda.New(sess)
   242  		client.opsworksconn = opsworks.New(usEast1Sess)
   243  		client.r53conn = route53.New(usEast1Sess)
   244  		client.rdsconn = rds.New(sess)
   245  		client.redshiftconn = redshift.New(sess)
   246  		client.simpledbconn = simpledb.New(sess)
   247  		client.s3conn = s3.New(sess)
   248  		client.sesConn = ses.New(sess)
   249  		client.snsconn = sns.New(sess)
   250  		client.sqsconn = sqs.New(sess)
   251  	}
   252  
   253  	if len(errs) > 0 {
   254  		return nil, &multierror.Error{Errors: errs}
   255  	}
   256  
   257  	return &client, nil
   258  }
   259  
   260  // ValidateRegion returns an error if the configured region is not a
   261  // valid aws region and nil otherwise.
   262  func (c *Config) ValidateRegion() error {
   263  	var regions = [13]string{
   264  		"ap-northeast-1",
   265  		"ap-northeast-2",
   266  		"ap-south-1",
   267  		"ap-southeast-1",
   268  		"ap-southeast-2",
   269  		"cn-north-1",
   270  		"eu-central-1",
   271  		"eu-west-1",
   272  		"sa-east-1",
   273  		"us-east-1",
   274  		"us-gov-west-1",
   275  		"us-west-1",
   276  		"us-west-2",
   277  	}
   278  
   279  	for _, valid := range regions {
   280  		if c.Region == valid {
   281  			return nil
   282  		}
   283  	}
   284  	return fmt.Errorf("Not a valid region: %s", c.Region)
   285  }
   286  
   287  // Validate credentials early and fail before we do any graph walking.
   288  func (c *Config) ValidateCredentials(stsconn *sts.STS) error {
   289  	_, err := stsconn.GetCallerIdentity(&sts.GetCallerIdentityInput{})
   290  	return err
   291  }
   292  
   293  // ValidateAccountId returns a context-specific error if the configured account
   294  // id is explicitly forbidden or not authorised; and nil if it is authorised.
   295  func (c *Config) ValidateAccountId(accountId string) error {
   296  	if c.AllowedAccountIds == nil && c.ForbiddenAccountIds == nil {
   297  		return nil
   298  	}
   299  
   300  	log.Printf("[INFO] Validating account ID")
   301  
   302  	if c.ForbiddenAccountIds != nil {
   303  		for _, id := range c.ForbiddenAccountIds {
   304  			if id == accountId {
   305  				return fmt.Errorf("Forbidden account ID (%s)", id)
   306  			}
   307  		}
   308  	}
   309  
   310  	if c.AllowedAccountIds != nil {
   311  		for _, id := range c.AllowedAccountIds {
   312  			if id == accountId {
   313  				return nil
   314  			}
   315  		}
   316  		return fmt.Errorf("Account ID not allowed (%s)", accountId)
   317  	}
   318  
   319  	return nil
   320  }
   321  
   322  // addTerraformVersionToUserAgent is a named handler that will add Terraform's
   323  // version information to requests made by the AWS SDK.
   324  var addTerraformVersionToUserAgent = request.NamedHandler{
   325  	Name: "terraform.TerraformVersionUserAgentHandler",
   326  	Fn: request.MakeAddToUserAgentHandler(
   327  		"terraform", terraform.VersionString()),
   328  }
   329  
   330  type awsLogger struct{}
   331  
   332  func (l awsLogger) Log(args ...interface{}) {
   333  	tokens := make([]string, 0, len(args))
   334  	for _, arg := range args {
   335  		if token, ok := arg.(string); ok {
   336  			tokens = append(tokens, token)
   337  		}
   338  	}
   339  	log.Printf("[DEBUG] [aws-sdk-go] %s", strings.Join(tokens, " "))
   340  }