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