github.com/aznashwan/terraform@v0.4.3-0.20151118032030-21f93ca4558d/builtin/providers/aws/provider.go (about)

     1  package aws
     2  
     3  import (
     4  	"net"
     5  	"sync"
     6  	"time"
     7  
     8  	"github.com/hashicorp/terraform/helper/hashcode"
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  	"github.com/hashicorp/terraform/terraform"
    11  
    12  	"github.com/aws/aws-sdk-go/aws/credentials"
    13  	"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
    14  )
    15  
    16  // Provider returns a terraform.ResourceProvider.
    17  func Provider() terraform.ResourceProvider {
    18  	// TODO: Move the validation to this, requires conditional schemas
    19  	// TODO: Move the configuration to this, requires validation
    20  
    21  	// These variables are closed within the `getCreds` function below.
    22  	// This function is responsible for reading credentials from the
    23  	// environment in the case that they're not explicitly specified
    24  	// in the Terraform configuration.
    25  	//
    26  	// By using the getCreds function here instead of making the default
    27  	// empty, we avoid asking for input on credentials if they're available
    28  	// in the environment.
    29  	var credVal credentials.Value
    30  	var credErr error
    31  	var once sync.Once
    32  	getCreds := func() {
    33  		// Build the list of providers to look for creds in
    34  		providers := []credentials.Provider{
    35  			&credentials.EnvProvider{},
    36  			&credentials.SharedCredentialsProvider{},
    37  		}
    38  
    39  		// We only look in the EC2 metadata API if we can connect
    40  		// to the metadata service within a reasonable amount of time
    41  		conn, err := net.DialTimeout("tcp", "169.254.169.254:80", 100*time.Millisecond)
    42  		if err == nil {
    43  			conn.Close()
    44  			providers = append(providers, &ec2rolecreds.EC2RoleProvider{})
    45  		}
    46  
    47  		credVal, credErr = credentials.NewChainCredentials(providers).Get()
    48  
    49  		// If we didn't successfully find any credentials, just
    50  		// set the error to nil.
    51  		if credErr == credentials.ErrNoValidProvidersFoundInChain {
    52  			credErr = nil
    53  		}
    54  	}
    55  
    56  	// getCredDefault is a function used by DefaultFunc below to
    57  	// get the default value for various parts of the credentials.
    58  	// This function properly handles loading the credentials, checking
    59  	// for errors, etc.
    60  	getCredDefault := func(def interface{}, f func() string) (interface{}, error) {
    61  		once.Do(getCreds)
    62  
    63  		// If there was an error, that is always first
    64  		if credErr != nil {
    65  			return nil, credErr
    66  		}
    67  
    68  		// If the value is empty string, return nil (not set)
    69  		val := f()
    70  		if val == "" {
    71  			return def, nil
    72  		}
    73  
    74  		return val, nil
    75  	}
    76  
    77  	// The actual provider
    78  	return &schema.Provider{
    79  		Schema: map[string]*schema.Schema{
    80  			"access_key": &schema.Schema{
    81  				Type:     schema.TypeString,
    82  				Required: true,
    83  				DefaultFunc: func() (interface{}, error) {
    84  					return getCredDefault(nil, func() string {
    85  						return credVal.AccessKeyID
    86  					})
    87  				},
    88  				Description: descriptions["access_key"],
    89  			},
    90  
    91  			"secret_key": &schema.Schema{
    92  				Type:     schema.TypeString,
    93  				Required: true,
    94  				DefaultFunc: func() (interface{}, error) {
    95  					return getCredDefault(nil, func() string {
    96  						return credVal.SecretAccessKey
    97  					})
    98  				},
    99  				Description: descriptions["secret_key"],
   100  			},
   101  
   102  			"token": &schema.Schema{
   103  				Type:     schema.TypeString,
   104  				Optional: true,
   105  				DefaultFunc: func() (interface{}, error) {
   106  					return getCredDefault("", func() string {
   107  						return credVal.SessionToken
   108  					})
   109  				},
   110  				Description: descriptions["token"],
   111  			},
   112  
   113  			"region": &schema.Schema{
   114  				Type:     schema.TypeString,
   115  				Required: true,
   116  				DefaultFunc: schema.MultiEnvDefaultFunc([]string{
   117  					"AWS_REGION",
   118  					"AWS_DEFAULT_REGION",
   119  				}, nil),
   120  				Description:  descriptions["region"],
   121  				InputDefault: "us-east-1",
   122  			},
   123  
   124  			"max_retries": &schema.Schema{
   125  				Type:        schema.TypeInt,
   126  				Optional:    true,
   127  				Default:     11,
   128  				Description: descriptions["max_retries"],
   129  			},
   130  
   131  			"allowed_account_ids": &schema.Schema{
   132  				Type:          schema.TypeSet,
   133  				Elem:          &schema.Schema{Type: schema.TypeString},
   134  				Optional:      true,
   135  				ConflictsWith: []string{"forbidden_account_ids"},
   136  				Set: func(v interface{}) int {
   137  					return hashcode.String(v.(string))
   138  				},
   139  			},
   140  
   141  			"forbidden_account_ids": &schema.Schema{
   142  				Type:          schema.TypeSet,
   143  				Elem:          &schema.Schema{Type: schema.TypeString},
   144  				Optional:      true,
   145  				ConflictsWith: []string{"allowed_account_ids"},
   146  				Set: func(v interface{}) int {
   147  					return hashcode.String(v.(string))
   148  				},
   149  			},
   150  
   151  			"dynamodb_endpoint": &schema.Schema{
   152  				Type:        schema.TypeString,
   153  				Optional:    true,
   154  				Default:     "",
   155  				Description: descriptions["dynamodb_endpoint"],
   156  			},
   157  
   158  			"kinesis_endpoint": &schema.Schema{
   159  				Type:        schema.TypeString,
   160  				Optional:    true,
   161  				Default:     "",
   162  				Description: descriptions["kinesis_endpoint"],
   163  			},
   164  		},
   165  
   166  		ResourcesMap: map[string]*schema.Resource{
   167  			"aws_ami":                              resourceAwsAmi(),
   168  			"aws_ami_copy":                         resourceAwsAmiCopy(),
   169  			"aws_ami_from_instance":                resourceAwsAmiFromInstance(),
   170  			"aws_app_cookie_stickiness_policy":     resourceAwsAppCookieStickinessPolicy(),
   171  			"aws_autoscaling_group":                resourceAwsAutoscalingGroup(),
   172  			"aws_autoscaling_notification":         resourceAwsAutoscalingNotification(),
   173  			"aws_autoscaling_policy":               resourceAwsAutoscalingPolicy(),
   174  			"aws_cloudformation_stack":             resourceAwsCloudFormationStack(),
   175  			"aws_cloudtrail":                       resourceAwsCloudTrail(),
   176  			"aws_cloudwatch_log_group":             resourceAwsCloudWatchLogGroup(),
   177  			"aws_autoscaling_lifecycle_hook":       resourceAwsAutoscalingLifecycleHook(),
   178  			"aws_cloudwatch_metric_alarm":          resourceAwsCloudWatchMetricAlarm(),
   179  			"aws_codedeploy_app":                   resourceAwsCodeDeployApp(),
   180  			"aws_codedeploy_deployment_group":      resourceAwsCodeDeployDeploymentGroup(),
   181  			"aws_codecommit_repository":            resourceAwsCodeCommitRepository(),
   182  			"aws_customer_gateway":                 resourceAwsCustomerGateway(),
   183  			"aws_db_instance":                      resourceAwsDbInstance(),
   184  			"aws_db_parameter_group":               resourceAwsDbParameterGroup(),
   185  			"aws_db_security_group":                resourceAwsDbSecurityGroup(),
   186  			"aws_db_subnet_group":                  resourceAwsDbSubnetGroup(),
   187  			"aws_directory_service_directory":      resourceAwsDirectoryServiceDirectory(),
   188  			"aws_dynamodb_table":                   resourceAwsDynamoDbTable(),
   189  			"aws_ebs_volume":                       resourceAwsEbsVolume(),
   190  			"aws_ecs_cluster":                      resourceAwsEcsCluster(),
   191  			"aws_ecs_service":                      resourceAwsEcsService(),
   192  			"aws_ecs_task_definition":              resourceAwsEcsTaskDefinition(),
   193  			"aws_efs_file_system":                  resourceAwsEfsFileSystem(),
   194  			"aws_efs_mount_target":                 resourceAwsEfsMountTarget(),
   195  			"aws_eip":                              resourceAwsEip(),
   196  			"aws_elasticache_cluster":              resourceAwsElasticacheCluster(),
   197  			"aws_elasticache_parameter_group":      resourceAwsElasticacheParameterGroup(),
   198  			"aws_elasticache_security_group":       resourceAwsElasticacheSecurityGroup(),
   199  			"aws_elasticache_subnet_group":         resourceAwsElasticacheSubnetGroup(),
   200  			"aws_elasticsearch_domain":             resourceAwsElasticSearchDomain(),
   201  			"aws_elb":                              resourceAwsElb(),
   202  			"aws_flow_log":                         resourceAwsFlowLog(),
   203  			"aws_glacier_vault":                    resourceAwsGlacierVault(),
   204  			"aws_iam_access_key":                   resourceAwsIamAccessKey(),
   205  			"aws_iam_group_policy":                 resourceAwsIamGroupPolicy(),
   206  			"aws_iam_group":                        resourceAwsIamGroup(),
   207  			"aws_iam_group_membership":             resourceAwsIamGroupMembership(),
   208  			"aws_iam_instance_profile":             resourceAwsIamInstanceProfile(),
   209  			"aws_iam_policy":                       resourceAwsIamPolicy(),
   210  			"aws_iam_policy_attachment":            resourceAwsIamPolicyAttachment(),
   211  			"aws_iam_role_policy":                  resourceAwsIamRolePolicy(),
   212  			"aws_iam_role":                         resourceAwsIamRole(),
   213  			"aws_iam_saml_provider":                resourceAwsIamSamlProvider(),
   214  			"aws_iam_server_certificate":           resourceAwsIAMServerCertificate(),
   215  			"aws_iam_user_policy":                  resourceAwsIamUserPolicy(),
   216  			"aws_iam_user":                         resourceAwsIamUser(),
   217  			"aws_instance":                         resourceAwsInstance(),
   218  			"aws_internet_gateway":                 resourceAwsInternetGateway(),
   219  			"aws_key_pair":                         resourceAwsKeyPair(),
   220  			"aws_kinesis_firehose_delivery_stream": resourceAwsKinesisFirehoseDeliveryStream(),
   221  			"aws_kinesis_stream":                   resourceAwsKinesisStream(),
   222  			"aws_lambda_function":                  resourceAwsLambdaFunction(),
   223  			"aws_launch_configuration":             resourceAwsLaunchConfiguration(),
   224  			"aws_lb_cookie_stickiness_policy":      resourceAwsLBCookieStickinessPolicy(),
   225  			"aws_main_route_table_association":     resourceAwsMainRouteTableAssociation(),
   226  			"aws_network_acl":                      resourceAwsNetworkAcl(),
   227  			"aws_network_interface":                resourceAwsNetworkInterface(),
   228  			"aws_opsworks_stack":                   resourceAwsOpsworksStack(),
   229  			"aws_opsworks_java_app_layer":          resourceAwsOpsworksJavaAppLayer(),
   230  			"aws_opsworks_haproxy_layer":           resourceAwsOpsworksHaproxyLayer(),
   231  			"aws_opsworks_static_web_layer":        resourceAwsOpsworksStaticWebLayer(),
   232  			"aws_opsworks_php_app_layer":           resourceAwsOpsworksPhpAppLayer(),
   233  			"aws_opsworks_rails_app_layer":         resourceAwsOpsworksRailsAppLayer(),
   234  			"aws_opsworks_nodejs_app_layer":        resourceAwsOpsworksNodejsAppLayer(),
   235  			"aws_opsworks_memcached_layer":         resourceAwsOpsworksMemcachedLayer(),
   236  			"aws_opsworks_mysql_layer":             resourceAwsOpsworksMysqlLayer(),
   237  			"aws_opsworks_ganglia_layer":           resourceAwsOpsworksGangliaLayer(),
   238  			"aws_opsworks_custom_layer":            resourceAwsOpsworksCustomLayer(),
   239  			"aws_placement_group":                  resourceAwsPlacementGroup(),
   240  			"aws_proxy_protocol_policy":            resourceAwsProxyProtocolPolicy(),
   241  			"aws_rds_cluster":                      resourceAwsRDSCluster(),
   242  			"aws_rds_cluster_instance":             resourceAwsRDSClusterInstance(),
   243  			"aws_route53_delegation_set":           resourceAwsRoute53DelegationSet(),
   244  			"aws_route53_record":                   resourceAwsRoute53Record(),
   245  			"aws_route53_zone_association":         resourceAwsRoute53ZoneAssociation(),
   246  			"aws_route53_zone":                     resourceAwsRoute53Zone(),
   247  			"aws_route53_health_check":             resourceAwsRoute53HealthCheck(),
   248  			"aws_route":                            resourceAwsRoute(),
   249  			"aws_route_table":                      resourceAwsRouteTable(),
   250  			"aws_route_table_association":          resourceAwsRouteTableAssociation(),
   251  			"aws_s3_bucket":                        resourceAwsS3Bucket(),
   252  			"aws_s3_bucket_object":                 resourceAwsS3BucketObject(),
   253  			"aws_security_group":                   resourceAwsSecurityGroup(),
   254  			"aws_security_group_rule":              resourceAwsSecurityGroupRule(),
   255  			"aws_spot_instance_request":            resourceAwsSpotInstanceRequest(),
   256  			"aws_sqs_queue":                        resourceAwsSqsQueue(),
   257  			"aws_sns_topic":                        resourceAwsSnsTopic(),
   258  			"aws_sns_topic_subscription":           resourceAwsSnsTopicSubscription(),
   259  			"aws_subnet":                           resourceAwsSubnet(),
   260  			"aws_volume_attachment":                resourceAwsVolumeAttachment(),
   261  			"aws_vpc_dhcp_options_association":     resourceAwsVpcDhcpOptionsAssociation(),
   262  			"aws_vpc_dhcp_options":                 resourceAwsVpcDhcpOptions(),
   263  			"aws_vpc_peering_connection":           resourceAwsVpcPeeringConnection(),
   264  			"aws_vpc":                              resourceAwsVpc(),
   265  			"aws_vpc_endpoint":                     resourceAwsVpcEndpoint(),
   266  			"aws_vpn_connection":                   resourceAwsVpnConnection(),
   267  			"aws_vpn_connection_route":             resourceAwsVpnConnectionRoute(),
   268  			"aws_vpn_gateway":                      resourceAwsVpnGateway(),
   269  		},
   270  
   271  		ConfigureFunc: providerConfigure,
   272  	}
   273  }
   274  
   275  var descriptions map[string]string
   276  
   277  func init() {
   278  	descriptions = map[string]string{
   279  		"region": "The region where AWS operations will take place. Examples\n" +
   280  			"are us-east-1, us-west-2, etc.",
   281  
   282  		"access_key": "The access key for API operations. You can retrieve this\n" +
   283  			"from the 'Security & Credentials' section of the AWS console.",
   284  
   285  		"secret_key": "The secret key for API operations. You can retrieve this\n" +
   286  			"from the 'Security & Credentials' section of the AWS console.",
   287  
   288  		"token": "session token. A session token is only required if you are\n" +
   289  			"using temporary security credentials.",
   290  
   291  		"max_retries": "The maximum number of times an AWS API request is\n" +
   292  			"being executed. If the API request still fails, an error is\n" +
   293  			"thrown.",
   294  
   295  		"dynamodb_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n" +
   296  			"It's typically used to connect to dynamodb-local.",
   297  
   298  		"kinesis_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n" +
   299  			"It's typically used to connect to kinesalite.",
   300  	}
   301  }
   302  
   303  func providerConfigure(d *schema.ResourceData) (interface{}, error) {
   304  	config := Config{
   305  		AccessKey:        d.Get("access_key").(string),
   306  		SecretKey:        d.Get("secret_key").(string),
   307  		Token:            d.Get("token").(string),
   308  		Region:           d.Get("region").(string),
   309  		MaxRetries:       d.Get("max_retries").(int),
   310  		DynamoDBEndpoint: d.Get("dynamodb_endpoint").(string),
   311  		KinesisEndpoint:  d.Get("kinesis_endpoint").(string),
   312  	}
   313  
   314  	if v, ok := d.GetOk("allowed_account_ids"); ok {
   315  		config.AllowedAccountIds = v.(*schema.Set).List()
   316  	}
   317  
   318  	if v, ok := d.GetOk("forbidden_account_ids"); ok {
   319  		config.ForbiddenAccountIds = v.(*schema.Set).List()
   320  	}
   321  
   322  	return config.Client()
   323  }