github.com/ricardclau/terraform@v0.6.17-0.20160519222547-283e3ae6b5a9/builtin/providers/aws/provider.go (about)

     1  package aws
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  
     7  	"github.com/hashicorp/terraform/helper/hashcode"
     8  	"github.com/hashicorp/terraform/helper/mutexkv"
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  	"github.com/hashicorp/terraform/terraform"
    11  )
    12  
    13  // Provider returns a terraform.ResourceProvider.
    14  func Provider() terraform.ResourceProvider {
    15  	// TODO: Move the validation to this, requires conditional schemas
    16  	// TODO: Move the configuration to this, requires validation
    17  
    18  	// The actual provider
    19  	return &schema.Provider{
    20  		Schema: map[string]*schema.Schema{
    21  			"access_key": &schema.Schema{
    22  				Type:        schema.TypeString,
    23  				Optional:    true,
    24  				Default:     "",
    25  				Description: descriptions["access_key"],
    26  			},
    27  
    28  			"secret_key": &schema.Schema{
    29  				Type:        schema.TypeString,
    30  				Optional:    true,
    31  				Default:     "",
    32  				Description: descriptions["secret_key"],
    33  			},
    34  
    35  			"profile": &schema.Schema{
    36  				Type:        schema.TypeString,
    37  				Optional:    true,
    38  				Default:     "",
    39  				Description: descriptions["profile"],
    40  			},
    41  
    42  			"shared_credentials_file": &schema.Schema{
    43  				Type:        schema.TypeString,
    44  				Optional:    true,
    45  				Default:     "",
    46  				Description: descriptions["shared_credentials_file"],
    47  			},
    48  
    49  			"token": &schema.Schema{
    50  				Type:        schema.TypeString,
    51  				Optional:    true,
    52  				Default:     "",
    53  				Description: descriptions["token"],
    54  			},
    55  
    56  			"region": &schema.Schema{
    57  				Type:     schema.TypeString,
    58  				Required: true,
    59  				DefaultFunc: schema.MultiEnvDefaultFunc([]string{
    60  					"AWS_REGION",
    61  					"AWS_DEFAULT_REGION",
    62  				}, nil),
    63  				Description:  descriptions["region"],
    64  				InputDefault: "us-east-1",
    65  			},
    66  
    67  			"max_retries": &schema.Schema{
    68  				Type:        schema.TypeInt,
    69  				Optional:    true,
    70  				Default:     11,
    71  				Description: descriptions["max_retries"],
    72  			},
    73  
    74  			"allowed_account_ids": &schema.Schema{
    75  				Type:          schema.TypeSet,
    76  				Elem:          &schema.Schema{Type: schema.TypeString},
    77  				Optional:      true,
    78  				ConflictsWith: []string{"forbidden_account_ids"},
    79  				Set:           schema.HashString,
    80  			},
    81  
    82  			"forbidden_account_ids": &schema.Schema{
    83  				Type:          schema.TypeSet,
    84  				Elem:          &schema.Schema{Type: schema.TypeString},
    85  				Optional:      true,
    86  				ConflictsWith: []string{"allowed_account_ids"},
    87  				Set:           schema.HashString,
    88  			},
    89  
    90  			"dynamodb_endpoint": &schema.Schema{
    91  				Type:        schema.TypeString,
    92  				Optional:    true,
    93  				Default:     "",
    94  				Description: descriptions["dynamodb_endpoint"],
    95  			},
    96  
    97  			"kinesis_endpoint": &schema.Schema{
    98  				Type:        schema.TypeString,
    99  				Optional:    true,
   100  				Default:     "",
   101  				Description: descriptions["kinesis_endpoint"],
   102  			},
   103  			"endpoints": endpointsSchema(),
   104  
   105  			"insecure": &schema.Schema{
   106  				Type:        schema.TypeBool,
   107  				Optional:    true,
   108  				Default:     false,
   109  				Description: descriptions["insecure"],
   110  			},
   111  		},
   112  
   113  		ResourcesMap: map[string]*schema.Resource{
   114  			"aws_ami":                                      resourceAwsAmi(),
   115  			"aws_ami_copy":                                 resourceAwsAmiCopy(),
   116  			"aws_ami_from_instance":                        resourceAwsAmiFromInstance(),
   117  			"aws_api_gateway_account":                      resourceAwsApiGatewayAccount(),
   118  			"aws_api_gateway_api_key":                      resourceAwsApiGatewayApiKey(),
   119  			"aws_api_gateway_authorizer":                   resourceAwsApiGatewayAuthorizer(),
   120  			"aws_api_gateway_deployment":                   resourceAwsApiGatewayDeployment(),
   121  			"aws_api_gateway_integration":                  resourceAwsApiGatewayIntegration(),
   122  			"aws_api_gateway_integration_response":         resourceAwsApiGatewayIntegrationResponse(),
   123  			"aws_api_gateway_method":                       resourceAwsApiGatewayMethod(),
   124  			"aws_api_gateway_method_response":              resourceAwsApiGatewayMethodResponse(),
   125  			"aws_api_gateway_model":                        resourceAwsApiGatewayModel(),
   126  			"aws_api_gateway_resource":                     resourceAwsApiGatewayResource(),
   127  			"aws_api_gateway_rest_api":                     resourceAwsApiGatewayRestApi(),
   128  			"aws_app_cookie_stickiness_policy":             resourceAwsAppCookieStickinessPolicy(),
   129  			"aws_autoscaling_group":                        resourceAwsAutoscalingGroup(),
   130  			"aws_autoscaling_notification":                 resourceAwsAutoscalingNotification(),
   131  			"aws_autoscaling_policy":                       resourceAwsAutoscalingPolicy(),
   132  			"aws_autoscaling_schedule":                     resourceAwsAutoscalingSchedule(),
   133  			"aws_cloudformation_stack":                     resourceAwsCloudFormationStack(),
   134  			"aws_cloudfront_distribution":                  resourceAwsCloudFrontDistribution(),
   135  			"aws_cloudfront_origin_access_identity":        resourceAwsCloudFrontOriginAccessIdentity(),
   136  			"aws_cloudtrail":                               resourceAwsCloudTrail(),
   137  			"aws_cloudwatch_event_rule":                    resourceAwsCloudWatchEventRule(),
   138  			"aws_cloudwatch_event_target":                  resourceAwsCloudWatchEventTarget(),
   139  			"aws_cloudwatch_log_group":                     resourceAwsCloudWatchLogGroup(),
   140  			"aws_cloudwatch_log_metric_filter":             resourceAwsCloudWatchLogMetricFilter(),
   141  			"aws_cloudwatch_log_subscription_filter":       resourceAwsCloudwatchLogSubscriptionFilter(),
   142  			"aws_autoscaling_lifecycle_hook":               resourceAwsAutoscalingLifecycleHook(),
   143  			"aws_cloudwatch_metric_alarm":                  resourceAwsCloudWatchMetricAlarm(),
   144  			"aws_codedeploy_app":                           resourceAwsCodeDeployApp(),
   145  			"aws_codedeploy_deployment_group":              resourceAwsCodeDeployDeploymentGroup(),
   146  			"aws_codecommit_repository":                    resourceAwsCodeCommitRepository(),
   147  			"aws_customer_gateway":                         resourceAwsCustomerGateway(),
   148  			"aws_db_event_subscription":                    resourceAwsDbEventSubscription(),
   149  			"aws_db_instance":                              resourceAwsDbInstance(),
   150  			"aws_db_option_group":                          resourceAwsDbOptionGroup(),
   151  			"aws_db_parameter_group":                       resourceAwsDbParameterGroup(),
   152  			"aws_db_security_group":                        resourceAwsDbSecurityGroup(),
   153  			"aws_db_subnet_group":                          resourceAwsDbSubnetGroup(),
   154  			"aws_directory_service_directory":              resourceAwsDirectoryServiceDirectory(),
   155  			"aws_dynamodb_table":                           resourceAwsDynamoDbTable(),
   156  			"aws_ebs_volume":                               resourceAwsEbsVolume(),
   157  			"aws_ecr_repository":                           resourceAwsEcrRepository(),
   158  			"aws_ecr_repository_policy":                    resourceAwsEcrRepositoryPolicy(),
   159  			"aws_ecs_cluster":                              resourceAwsEcsCluster(),
   160  			"aws_ecs_service":                              resourceAwsEcsService(),
   161  			"aws_ecs_task_definition":                      resourceAwsEcsTaskDefinition(),
   162  			"aws_efs_file_system":                          resourceAwsEfsFileSystem(),
   163  			"aws_efs_mount_target":                         resourceAwsEfsMountTarget(),
   164  			"aws_eip":                                      resourceAwsEip(),
   165  			"aws_eip_association":                          resourceAwsEipAssociation(),
   166  			"aws_elasticache_cluster":                      resourceAwsElasticacheCluster(),
   167  			"aws_elasticache_parameter_group":              resourceAwsElasticacheParameterGroup(),
   168  			"aws_elasticache_security_group":               resourceAwsElasticacheSecurityGroup(),
   169  			"aws_elasticache_subnet_group":                 resourceAwsElasticacheSubnetGroup(),
   170  			"aws_elastic_beanstalk_application":            resourceAwsElasticBeanstalkApplication(),
   171  			"aws_elastic_beanstalk_configuration_template": resourceAwsElasticBeanstalkConfigurationTemplate(),
   172  			"aws_elastic_beanstalk_environment":            resourceAwsElasticBeanstalkEnvironment(),
   173  			"aws_elasticsearch_domain":                     resourceAwsElasticSearchDomain(),
   174  			"aws_elb":                                      resourceAwsElb(),
   175  			"aws_flow_log":                                 resourceAwsFlowLog(),
   176  			"aws_glacier_vault":                            resourceAwsGlacierVault(),
   177  			"aws_iam_access_key":                           resourceAwsIamAccessKey(),
   178  			"aws_iam_account_password_policy":              resourceAwsIamAccountPasswordPolicy(),
   179  			"aws_iam_group_policy":                         resourceAwsIamGroupPolicy(),
   180  			"aws_iam_group":                                resourceAwsIamGroup(),
   181  			"aws_iam_group_membership":                     resourceAwsIamGroupMembership(),
   182  			"aws_iam_instance_profile":                     resourceAwsIamInstanceProfile(),
   183  			"aws_iam_policy":                               resourceAwsIamPolicy(),
   184  			"aws_iam_policy_attachment":                    resourceAwsIamPolicyAttachment(),
   185  			"aws_iam_role_policy":                          resourceAwsIamRolePolicy(),
   186  			"aws_iam_role":                                 resourceAwsIamRole(),
   187  			"aws_iam_saml_provider":                        resourceAwsIamSamlProvider(),
   188  			"aws_iam_server_certificate":                   resourceAwsIAMServerCertificate(),
   189  			"aws_iam_user_policy":                          resourceAwsIamUserPolicy(),
   190  			"aws_iam_user_ssh_key":                         resourceAwsIamUserSshKey(),
   191  			"aws_iam_user":                                 resourceAwsIamUser(),
   192  			"aws_instance":                                 resourceAwsInstance(),
   193  			"aws_internet_gateway":                         resourceAwsInternetGateway(),
   194  			"aws_key_pair":                                 resourceAwsKeyPair(),
   195  			"aws_kinesis_firehose_delivery_stream":         resourceAwsKinesisFirehoseDeliveryStream(),
   196  			"aws_kinesis_stream":                           resourceAwsKinesisStream(),
   197  			"aws_kms_alias":                                resourceAwsKmsAlias(),
   198  			"aws_kms_key":                                  resourceAwsKmsKey(),
   199  			"aws_lambda_function":                          resourceAwsLambdaFunction(),
   200  			"aws_lambda_event_source_mapping":              resourceAwsLambdaEventSourceMapping(),
   201  			"aws_lambda_alias":                             resourceAwsLambdaAlias(),
   202  			"aws_lambda_permission":                        resourceAwsLambdaPermission(),
   203  			"aws_launch_configuration":                     resourceAwsLaunchConfiguration(),
   204  			"aws_lb_cookie_stickiness_policy":              resourceAwsLBCookieStickinessPolicy(),
   205  			"aws_main_route_table_association":             resourceAwsMainRouteTableAssociation(),
   206  			"aws_nat_gateway":                              resourceAwsNatGateway(),
   207  			"aws_network_acl":                              resourceAwsNetworkAcl(),
   208  			"aws_default_network_acl":                      resourceAwsDefaultNetworkAcl(),
   209  			"aws_network_acl_rule":                         resourceAwsNetworkAclRule(),
   210  			"aws_network_interface":                        resourceAwsNetworkInterface(),
   211  			"aws_opsworks_application":                     resourceAwsOpsworksApplication(),
   212  			"aws_opsworks_stack":                           resourceAwsOpsworksStack(),
   213  			"aws_opsworks_java_app_layer":                  resourceAwsOpsworksJavaAppLayer(),
   214  			"aws_opsworks_haproxy_layer":                   resourceAwsOpsworksHaproxyLayer(),
   215  			"aws_opsworks_static_web_layer":                resourceAwsOpsworksStaticWebLayer(),
   216  			"aws_opsworks_php_app_layer":                   resourceAwsOpsworksPhpAppLayer(),
   217  			"aws_opsworks_rails_app_layer":                 resourceAwsOpsworksRailsAppLayer(),
   218  			"aws_opsworks_nodejs_app_layer":                resourceAwsOpsworksNodejsAppLayer(),
   219  			"aws_opsworks_memcached_layer":                 resourceAwsOpsworksMemcachedLayer(),
   220  			"aws_opsworks_mysql_layer":                     resourceAwsOpsworksMysqlLayer(),
   221  			"aws_opsworks_ganglia_layer":                   resourceAwsOpsworksGangliaLayer(),
   222  			"aws_opsworks_custom_layer":                    resourceAwsOpsworksCustomLayer(),
   223  			"aws_opsworks_instance":                        resourceAwsOpsworksInstance(),
   224  			"aws_placement_group":                          resourceAwsPlacementGroup(),
   225  			"aws_proxy_protocol_policy":                    resourceAwsProxyProtocolPolicy(),
   226  			"aws_rds_cluster":                              resourceAwsRDSCluster(),
   227  			"aws_rds_cluster_instance":                     resourceAwsRDSClusterInstance(),
   228  			"aws_rds_cluster_parameter_group":              resourceAwsRDSClusterParameterGroup(),
   229  			"aws_redshift_cluster":                         resourceAwsRedshiftCluster(),
   230  			"aws_redshift_security_group":                  resourceAwsRedshiftSecurityGroup(),
   231  			"aws_redshift_parameter_group":                 resourceAwsRedshiftParameterGroup(),
   232  			"aws_redshift_subnet_group":                    resourceAwsRedshiftSubnetGroup(),
   233  			"aws_route53_delegation_set":                   resourceAwsRoute53DelegationSet(),
   234  			"aws_route53_record":                           resourceAwsRoute53Record(),
   235  			"aws_route53_zone_association":                 resourceAwsRoute53ZoneAssociation(),
   236  			"aws_route53_zone":                             resourceAwsRoute53Zone(),
   237  			"aws_route53_health_check":                     resourceAwsRoute53HealthCheck(),
   238  			"aws_route":                                    resourceAwsRoute(),
   239  			"aws_route_table":                              resourceAwsRouteTable(),
   240  			"aws_route_table_association":                  resourceAwsRouteTableAssociation(),
   241  			"aws_s3_bucket":                                resourceAwsS3Bucket(),
   242  			"aws_s3_bucket_object":                         resourceAwsS3BucketObject(),
   243  			"aws_s3_bucket_notification":                   resourceAwsS3BucketNotification(),
   244  			"aws_security_group":                           resourceAwsSecurityGroup(),
   245  			"aws_security_group_rule":                      resourceAwsSecurityGroupRule(),
   246  			"aws_spot_instance_request":                    resourceAwsSpotInstanceRequest(),
   247  			"aws_sqs_queue":                                resourceAwsSqsQueue(),
   248  			"aws_sns_topic":                                resourceAwsSnsTopic(),
   249  			"aws_sns_topic_subscription":                   resourceAwsSnsTopicSubscription(),
   250  			"aws_subnet":                                   resourceAwsSubnet(),
   251  			"aws_volume_attachment":                        resourceAwsVolumeAttachment(),
   252  			"aws_vpc_dhcp_options_association":             resourceAwsVpcDhcpOptionsAssociation(),
   253  			"aws_vpc_dhcp_options":                         resourceAwsVpcDhcpOptions(),
   254  			"aws_vpc_peering_connection":                   resourceAwsVpcPeeringConnection(),
   255  			"aws_vpc":                                      resourceAwsVpc(),
   256  			"aws_vpc_endpoint":                             resourceAwsVpcEndpoint(),
   257  			"aws_vpn_connection":                           resourceAwsVpnConnection(),
   258  			"aws_vpn_connection_route":                     resourceAwsVpnConnectionRoute(),
   259  			"aws_vpn_gateway":                              resourceAwsVpnGateway(),
   260  		},
   261  		ConfigureFunc: providerConfigure,
   262  	}
   263  }
   264  
   265  var descriptions map[string]string
   266  
   267  func init() {
   268  	descriptions = map[string]string{
   269  		"region": "The region where AWS operations will take place. Examples\n" +
   270  			"are us-east-1, us-west-2, etc.",
   271  
   272  		"access_key": "The access key for API operations. You can retrieve this\n" +
   273  			"from the 'Security & Credentials' section of the AWS console.",
   274  
   275  		"secret_key": "The secret key for API operations. You can retrieve this\n" +
   276  			"from the 'Security & Credentials' section of the AWS console.",
   277  
   278  		"profile": "The profile for API operations. If not set, the default profile\n" +
   279  			"created with `aws configure` will be used.",
   280  
   281  		"shared_credentials_file": "The path to the shared credentials file. If not set\n" +
   282  			"this defaults to ~/.aws/credentials.",
   283  
   284  		"token": "session token. A session token is only required if you are\n" +
   285  			"using temporary security credentials.",
   286  
   287  		"max_retries": "The maximum number of times an AWS API request is\n" +
   288  			"being executed. If the API request still fails, an error is\n" +
   289  			"thrown.",
   290  
   291  		"dynamodb_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n" +
   292  			"It's typically used to connect to dynamodb-local.",
   293  
   294  		"kinesis_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n" +
   295  			"It's typically used to connect to kinesalite.",
   296  
   297  		"iam_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
   298  
   299  		"ec2_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
   300  
   301  		"elb_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
   302  
   303  		"insecure": "Explicitly allow the provider to perform \"insecure\" SSL requests. If omitted," +
   304  			"default value is `false`",
   305  	}
   306  }
   307  
   308  func providerConfigure(d *schema.ResourceData) (interface{}, error) {
   309  	config := Config{
   310  		AccessKey:        d.Get("access_key").(string),
   311  		SecretKey:        d.Get("secret_key").(string),
   312  		Profile:          d.Get("profile").(string),
   313  		CredsFilename:    d.Get("shared_credentials_file").(string),
   314  		Token:            d.Get("token").(string),
   315  		Region:           d.Get("region").(string),
   316  		MaxRetries:       d.Get("max_retries").(int),
   317  		DynamoDBEndpoint: d.Get("dynamodb_endpoint").(string),
   318  		KinesisEndpoint:  d.Get("kinesis_endpoint").(string),
   319  		Insecure:         d.Get("insecure").(bool),
   320  	}
   321  
   322  	endpointsSet := d.Get("endpoints").(*schema.Set)
   323  
   324  	for _, endpointsSetI := range endpointsSet.List() {
   325  		endpoints := endpointsSetI.(map[string]interface{})
   326  		config.IamEndpoint = endpoints["iam"].(string)
   327  		config.Ec2Endpoint = endpoints["ec2"].(string)
   328  		config.ElbEndpoint = endpoints["elb"].(string)
   329  	}
   330  
   331  	if v, ok := d.GetOk("allowed_account_ids"); ok {
   332  		config.AllowedAccountIds = v.(*schema.Set).List()
   333  	}
   334  
   335  	if v, ok := d.GetOk("forbidden_account_ids"); ok {
   336  		config.ForbiddenAccountIds = v.(*schema.Set).List()
   337  	}
   338  
   339  	return config.Client()
   340  }
   341  
   342  // This is a global MutexKV for use within this plugin.
   343  var awsMutexKV = mutexkv.NewMutexKV()
   344  
   345  func endpointsSchema() *schema.Schema {
   346  	return &schema.Schema{
   347  		Type:     schema.TypeSet,
   348  		Optional: true,
   349  		Elem: &schema.Resource{
   350  			Schema: map[string]*schema.Schema{
   351  				"iam": &schema.Schema{
   352  					Type:        schema.TypeString,
   353  					Optional:    true,
   354  					Default:     "",
   355  					Description: descriptions["iam_endpoint"],
   356  				},
   357  
   358  				"ec2": &schema.Schema{
   359  					Type:        schema.TypeString,
   360  					Optional:    true,
   361  					Default:     "",
   362  					Description: descriptions["ec2_endpoint"],
   363  				},
   364  
   365  				"elb": &schema.Schema{
   366  					Type:        schema.TypeString,
   367  					Optional:    true,
   368  					Default:     "",
   369  					Description: descriptions["elb_endpoint"],
   370  				},
   371  			},
   372  		},
   373  		Set: endpointsToHash,
   374  	}
   375  }
   376  
   377  func endpointsToHash(v interface{}) int {
   378  	var buf bytes.Buffer
   379  	m := v.(map[string]interface{})
   380  	buf.WriteString(fmt.Sprintf("%s-", m["iam"].(string)))
   381  	buf.WriteString(fmt.Sprintf("%s-", m["ec2"].(string)))
   382  	buf.WriteString(fmt.Sprintf("%s-", m["elb"].(string)))
   383  
   384  	return hashcode.String(buf.String())
   385  }