github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/google/provider.go (about)

     1  package google
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/hashicorp/terraform/helper/schema"
     9  	"github.com/hashicorp/terraform/terraform"
    10  	"google.golang.org/api/compute/v1"
    11  	"google.golang.org/api/googleapi"
    12  )
    13  
    14  // Provider returns a terraform.ResourceProvider.
    15  func Provider() terraform.ResourceProvider {
    16  	return &schema.Provider{
    17  		Schema: map[string]*schema.Schema{
    18  			"credentials": &schema.Schema{
    19  				Type:     schema.TypeString,
    20  				Optional: true,
    21  				DefaultFunc: schema.MultiEnvDefaultFunc([]string{
    22  					"GOOGLE_CREDENTIALS",
    23  					"GOOGLE_CLOUD_KEYFILE_JSON",
    24  					"GCLOUD_KEYFILE_JSON",
    25  				}, nil),
    26  				ValidateFunc: validateCredentials,
    27  			},
    28  
    29  			"project": &schema.Schema{
    30  				Type:     schema.TypeString,
    31  				Optional: true,
    32  				DefaultFunc: schema.MultiEnvDefaultFunc([]string{
    33  					"GOOGLE_PROJECT",
    34  					"GCLOUD_PROJECT",
    35  					"CLOUDSDK_CORE_PROJECT",
    36  				}, nil),
    37  			},
    38  
    39  			"region": &schema.Schema{
    40  				Type:     schema.TypeString,
    41  				Required: true,
    42  				DefaultFunc: schema.MultiEnvDefaultFunc([]string{
    43  					"GOOGLE_REGION",
    44  					"GCLOUD_REGION",
    45  					"CLOUDSDK_COMPUTE_REGION",
    46  				}, nil),
    47  			},
    48  		},
    49  
    50  		DataSourcesMap: map[string]*schema.Resource{
    51  			"google_compute_network":    dataSourceGoogleComputeNetwork(),
    52  			"google_compute_subnetwork": dataSourceGoogleComputeSubnetwork(),
    53  			"google_compute_zones":      dataSourceGoogleComputeZones(),
    54  			"google_iam_policy":         dataSourceGoogleIamPolicy(),
    55  		},
    56  
    57  		ResourcesMap: map[string]*schema.Resource{
    58  			"google_bigquery_dataset":               resourceBigQueryDataset(),
    59  			"google_compute_autoscaler":             resourceComputeAutoscaler(),
    60  			"google_compute_address":                resourceComputeAddress(),
    61  			"google_compute_backend_service":        resourceComputeBackendService(),
    62  			"google_compute_disk":                   resourceComputeDisk(),
    63  			"google_compute_firewall":               resourceComputeFirewall(),
    64  			"google_compute_forwarding_rule":        resourceComputeForwardingRule(),
    65  			"google_compute_global_address":         resourceComputeGlobalAddress(),
    66  			"google_compute_global_forwarding_rule": resourceComputeGlobalForwardingRule(),
    67  			"google_compute_health_check":           resourceComputeHealthCheck(),
    68  			"google_compute_http_health_check":      resourceComputeHttpHealthCheck(),
    69  			"google_compute_https_health_check":     resourceComputeHttpsHealthCheck(),
    70  			"google_compute_image":                  resourceComputeImage(),
    71  			"google_compute_instance":               resourceComputeInstance(),
    72  			"google_compute_instance_group":         resourceComputeInstanceGroup(),
    73  			"google_compute_instance_group_manager": resourceComputeInstanceGroupManager(),
    74  			"google_compute_instance_template":      resourceComputeInstanceTemplate(),
    75  			"google_compute_network":                resourceComputeNetwork(),
    76  			"google_compute_project_metadata":       resourceComputeProjectMetadata(),
    77  			"google_compute_region_backend_service": resourceComputeRegionBackendService(),
    78  			"google_compute_route":                  resourceComputeRoute(),
    79  			"google_compute_ssl_certificate":        resourceComputeSslCertificate(),
    80  			"google_compute_subnetwork":             resourceComputeSubnetwork(),
    81  			"google_compute_target_http_proxy":      resourceComputeTargetHttpProxy(),
    82  			"google_compute_target_https_proxy":     resourceComputeTargetHttpsProxy(),
    83  			"google_compute_target_pool":            resourceComputeTargetPool(),
    84  			"google_compute_url_map":                resourceComputeUrlMap(),
    85  			"google_compute_vpn_gateway":            resourceComputeVpnGateway(),
    86  			"google_compute_vpn_tunnel":             resourceComputeVpnTunnel(),
    87  			"google_container_cluster":              resourceContainerCluster(),
    88  			"google_container_node_pool":            resourceContainerNodePool(),
    89  			"google_dns_managed_zone":               resourceDnsManagedZone(),
    90  			"google_dns_record_set":                 resourceDnsRecordSet(),
    91  			"google_sql_database":                   resourceSqlDatabase(),
    92  			"google_sql_database_instance":          resourceSqlDatabaseInstance(),
    93  			"google_sql_user":                       resourceSqlUser(),
    94  			"google_project":                        resourceGoogleProject(),
    95  			"google_project_iam_policy":             resourceGoogleProjectIamPolicy(),
    96  			"google_project_services":               resourceGoogleProjectServices(),
    97  			"google_pubsub_topic":                   resourcePubsubTopic(),
    98  			"google_pubsub_subscription":            resourcePubsubSubscription(),
    99  			"google_service_account":                resourceGoogleServiceAccount(),
   100  			"google_storage_bucket":                 resourceStorageBucket(),
   101  			"google_storage_bucket_acl":             resourceStorageBucketAcl(),
   102  			"google_storage_bucket_object":          resourceStorageBucketObject(),
   103  			"google_storage_object_acl":             resourceStorageObjectAcl(),
   104  		},
   105  
   106  		ConfigureFunc: providerConfigure,
   107  	}
   108  }
   109  
   110  func providerConfigure(d *schema.ResourceData) (interface{}, error) {
   111  	credentials := d.Get("credentials").(string)
   112  	config := Config{
   113  		Credentials: credentials,
   114  		Project:     d.Get("project").(string),
   115  		Region:      d.Get("region").(string),
   116  	}
   117  
   118  	if err := config.loadAndValidate(); err != nil {
   119  		return nil, err
   120  	}
   121  
   122  	return &config, nil
   123  }
   124  
   125  func validateCredentials(v interface{}, k string) (warnings []string, errors []error) {
   126  	if v == nil || v.(string) == "" {
   127  		return
   128  	}
   129  	creds := v.(string)
   130  	var account accountFile
   131  	if err := json.Unmarshal([]byte(creds), &account); err != nil {
   132  		errors = append(errors,
   133  			fmt.Errorf("credentials are not valid JSON '%s': %s", creds, err))
   134  	}
   135  
   136  	return
   137  }
   138  
   139  // getRegionFromZone returns the region from a zone for Google cloud.
   140  func getRegionFromZone(zone string) string {
   141  	if zone != "" && len(zone) > 2 {
   142  		region := zone[:len(zone)-2]
   143  		return region
   144  	}
   145  	return ""
   146  }
   147  
   148  // getRegion reads the "region" field from the given resource data and falls
   149  // back to the provider's value if not given. If the provider's value is not
   150  // given, an error is returned.
   151  func getRegion(d *schema.ResourceData, config *Config) (string, error) {
   152  	res, ok := d.GetOk("region")
   153  	if !ok {
   154  		if config.Region != "" {
   155  			return config.Region, nil
   156  		}
   157  		return "", fmt.Errorf("%q: required field is not set", "region")
   158  	}
   159  	return res.(string), nil
   160  }
   161  
   162  // getProject reads the "project" field from the given resource data and falls
   163  // back to the provider's value if not given. If the provider's value is not
   164  // given, an error is returned.
   165  func getProject(d *schema.ResourceData, config *Config) (string, error) {
   166  	res, ok := d.GetOk("project")
   167  	if !ok {
   168  		if config.Project != "" {
   169  			return config.Project, nil
   170  		}
   171  		return "", fmt.Errorf("%q: required field is not set", "project")
   172  	}
   173  	return res.(string), nil
   174  }
   175  
   176  func getZonalResourceFromRegion(getResource func(string) (interface{}, error), region string, compute *compute.Service, project string) (interface{}, error) {
   177  	zoneList, err := compute.Zones.List(project).Do()
   178  	if err != nil {
   179  		return nil, err
   180  	}
   181  	var resource interface{}
   182  	for _, zone := range zoneList.Items {
   183  		if strings.Contains(zone.Name, region) {
   184  			resource, err = getResource(zone.Name)
   185  			if err != nil {
   186  				if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 {
   187  					// Resource was not found in this zone
   188  					continue
   189  				}
   190  				return nil, fmt.Errorf("Error reading Resource: %s", err)
   191  			}
   192  			// Resource was found
   193  			return resource, nil
   194  		}
   195  	}
   196  	// Resource does not exist in this region
   197  	return nil, nil
   198  }
   199  
   200  // getNetworkLink reads the "network" field from the given resource data and if the value:
   201  // - is a resource URL, returns the string unchanged
   202  // - is the network name only, then looks up the resource URL using the google client
   203  func getNetworkLink(d *schema.ResourceData, config *Config, field string) (string, error) {
   204  	if v, ok := d.GetOk(field); ok {
   205  		network := v.(string)
   206  
   207  		project, err := getProject(d, config)
   208  		if err != nil {
   209  			return "", err
   210  		}
   211  
   212  		if !strings.HasPrefix(network, "https://www.googleapis.com/compute/") {
   213  			// Network value provided is just the name, lookup the network SelfLink
   214  			networkData, err := config.clientCompute.Networks.Get(
   215  				project, network).Do()
   216  			if err != nil {
   217  				return "", fmt.Errorf("Error reading network: %s", err)
   218  			}
   219  			network = networkData.SelfLink
   220  		}
   221  
   222  		return network, nil
   223  
   224  	} else {
   225  		return "", nil
   226  	}
   227  }
   228  
   229  // getNetworkName reads the "network" field from the given resource data and if the value:
   230  // - is a resource URL, extracts the network name from the URL and returns it
   231  // - is the network name only (i.e not prefixed with http://www.googleapis.com/compute/...), is returned unchanged
   232  func getNetworkName(d *schema.ResourceData, field string) (string, error) {
   233  	if v, ok := d.GetOk(field); ok {
   234  		network := v.(string)
   235  		return getNetworkNameFromSelfLink(network)
   236  	}
   237  	return "", nil
   238  }
   239  
   240  func getNetworkNameFromSelfLink(network string) (string, error) {
   241  	if strings.HasPrefix(network, "https://www.googleapis.com/compute/") {
   242  		// extract the network name from SelfLink URL
   243  		networkName := network[strings.LastIndex(network, "/")+1:]
   244  		if networkName == "" {
   245  			return "", fmt.Errorf("network url not valid")
   246  		}
   247  		return networkName, nil
   248  	}
   249  
   250  	return network, nil
   251  }