github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/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_http_health_check": resourceComputeHttpHealthCheck(), 73 "google_compute_https_health_check": resourceComputeHttpsHealthCheck(), 74 "google_compute_image": resourceComputeImage(), 75 "google_compute_instance": resourceComputeInstance(), 76 "google_compute_instance_group": resourceComputeInstanceGroup(), 77 "google_compute_instance_group_manager": resourceComputeInstanceGroupManager(), 78 "google_compute_instance_template": resourceComputeInstanceTemplate(), 79 "google_compute_network": resourceComputeNetwork(), 80 "google_compute_project_metadata": resourceComputeProjectMetadata(), 81 "google_compute_route": resourceComputeRoute(), 82 "google_compute_ssl_certificate": resourceComputeSslCertificate(), 83 "google_compute_subnetwork": resourceComputeSubnetwork(), 84 "google_compute_target_http_proxy": resourceComputeTargetHttpProxy(), 85 "google_compute_target_https_proxy": resourceComputeTargetHttpsProxy(), 86 "google_compute_target_pool": resourceComputeTargetPool(), 87 "google_compute_url_map": resourceComputeUrlMap(), 88 "google_compute_vpn_gateway": resourceComputeVpnGateway(), 89 "google_compute_vpn_tunnel": resourceComputeVpnTunnel(), 90 "google_container_cluster": resourceContainerCluster(), 91 "google_dns_managed_zone": resourceDnsManagedZone(), 92 "google_dns_record_set": resourceDnsRecordSet(), 93 "google_sql_database": resourceSqlDatabase(), 94 "google_sql_database_instance": resourceSqlDatabaseInstance(), 95 "google_sql_user": resourceSqlUser(), 96 "google_project": resourceGoogleProject(), 97 "google_pubsub_topic": resourcePubsubTopic(), 98 "google_pubsub_subscription": resourcePubsubSubscription(), 99 "google_storage_bucket": resourceStorageBucket(), 100 "google_storage_bucket_acl": resourceStorageBucketAcl(), 101 "google_storage_bucket_object": resourceStorageBucketObject(), 102 "google_storage_object_acl": resourceStorageObjectAcl(), 103 }, 104 105 ConfigureFunc: providerConfigure, 106 } 107 } 108 109 func providerConfigure(d *schema.ResourceData) (interface{}, error) { 110 credentials := d.Get("credentials").(string) 111 if credentials == "" { 112 credentials = d.Get("account_file").(string) 113 } 114 config := Config{ 115 Credentials: credentials, 116 Project: d.Get("project").(string), 117 Region: d.Get("region").(string), 118 } 119 120 if err := config.loadAndValidate(); err != nil { 121 return nil, err 122 } 123 124 return &config, nil 125 } 126 127 func validateAccountFile(v interface{}, k string) (warnings []string, errors []error) { 128 if v == nil { 129 return 130 } 131 132 value := v.(string) 133 134 if value == "" { 135 return 136 } 137 138 contents, wasPath, err := pathorcontents.Read(value) 139 if err != nil { 140 errors = append(errors, fmt.Errorf("Error loading Account File: %s", err)) 141 } 142 if wasPath { 143 warnings = append(warnings, `account_file was provided as a path instead of 144 as file contents. This support will be removed in the future. Please update 145 your configuration to use ${file("filename.json")} instead.`) 146 } 147 148 var account accountFile 149 if err := json.Unmarshal([]byte(contents), &account); err != nil { 150 errors = append(errors, 151 fmt.Errorf("account_file not valid JSON '%s': %s", contents, err)) 152 } 153 154 return 155 } 156 157 func validateCredentials(v interface{}, k string) (warnings []string, errors []error) { 158 if v == nil || v.(string) == "" { 159 return 160 } 161 creds := v.(string) 162 var account accountFile 163 if err := json.Unmarshal([]byte(creds), &account); err != nil { 164 errors = append(errors, 165 fmt.Errorf("credentials are not valid JSON '%s': %s", creds, err)) 166 } 167 168 return 169 } 170 171 // getRegionFromZone returns the region from a zone for Google cloud. 172 func getRegionFromZone(zone string) string { 173 if zone != "" && len(zone) > 2 { 174 region := zone[:len(zone)-2] 175 return region 176 } 177 return "" 178 } 179 180 // getRegion reads the "region" field from the given resource data and falls 181 // back to the provider's value if not given. If the provider's value is not 182 // given, an error is returned. 183 func getRegion(d *schema.ResourceData, config *Config) (string, error) { 184 res, ok := d.GetOk("region") 185 if !ok { 186 if config.Region != "" { 187 return config.Region, nil 188 } 189 return "", fmt.Errorf("%q: required field is not set", "region") 190 } 191 return res.(string), nil 192 } 193 194 // getProject reads the "project" field from the given resource data and falls 195 // back to the provider's value if not given. If the provider's value is not 196 // given, an error is returned. 197 func getProject(d *schema.ResourceData, config *Config) (string, error) { 198 res, ok := d.GetOk("project") 199 if !ok { 200 if config.Project != "" { 201 return config.Project, nil 202 } 203 return "", fmt.Errorf("%q: required field is not set", "project") 204 } 205 return res.(string), nil 206 } 207 208 func getZonalResourceFromRegion(getResource func(string) (interface{}, error), region string, compute *compute.Service, project string) (interface{}, error) { 209 zoneList, err := compute.Zones.List(project).Do() 210 if err != nil { 211 return nil, err 212 } 213 var resource interface{} 214 for _, zone := range zoneList.Items { 215 if strings.Contains(zone.Name, region) { 216 resource, err = getResource(zone.Name) 217 if err != nil { 218 if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { 219 // Resource was not found in this zone 220 continue 221 } 222 return nil, fmt.Errorf("Error reading Resource: %s", err) 223 } 224 // Resource was found 225 return resource, nil 226 } 227 } 228 // Resource does not exist in this region 229 return nil, nil 230 } 231 232 // getNetworkLink reads the "network" field from the given resource data and if the value: 233 // - is a resource URL, returns the string unchanged 234 // - is the network name only, then looks up the resource URL using the google client 235 func getNetworkLink(d *schema.ResourceData, config *Config, field string) (string, error) { 236 if v, ok := d.GetOk(field); ok { 237 network := v.(string) 238 239 project, err := getProject(d, config) 240 if err != nil { 241 return "", err 242 } 243 244 if !strings.HasPrefix(network, "https://www.googleapis.com/compute/") { 245 // Network value provided is just the name, lookup the network SelfLink 246 networkData, err := config.clientCompute.Networks.Get( 247 project, network).Do() 248 if err != nil { 249 return "", fmt.Errorf("Error reading network: %s", err) 250 } 251 network = networkData.SelfLink 252 } 253 254 return network, nil 255 256 } else { 257 return "", nil 258 } 259 } 260 261 // getNetworkName reads the "network" field from the given resource data and if the value: 262 // - is a resource URL, extracts the network name from the URL and returns it 263 // - is the network name only (i.e not prefixed with http://www.googleapis.com/compute/...), is returned unchanged 264 func getNetworkName(d *schema.ResourceData, field string) (string, error) { 265 if v, ok := d.GetOk(field); ok { 266 network := v.(string) 267 268 if strings.HasPrefix(network, "https://www.googleapis.com/compute/") { 269 // extract the network name from SelfLink URL 270 networkName := network[strings.LastIndex(network, "/")+1:] 271 if networkName == "" { 272 return "", fmt.Errorf("network url not valid") 273 } 274 return networkName, nil 275 } 276 277 return network, nil 278 } 279 return "", nil 280 }