github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/google/resource_compute_backend_service.go (about) 1 package google 2 3 import ( 4 "bytes" 5 "fmt" 6 "log" 7 "regexp" 8 9 "github.com/hashicorp/terraform/helper/hashcode" 10 "github.com/hashicorp/terraform/helper/schema" 11 "google.golang.org/api/compute/v1" 12 "google.golang.org/api/googleapi" 13 ) 14 15 func resourceComputeBackendService() *schema.Resource { 16 return &schema.Resource{ 17 Create: resourceComputeBackendServiceCreate, 18 Read: resourceComputeBackendServiceRead, 19 Update: resourceComputeBackendServiceUpdate, 20 Delete: resourceComputeBackendServiceDelete, 21 22 Schema: map[string]*schema.Schema{ 23 "name": &schema.Schema{ 24 Type: schema.TypeString, 25 Required: true, 26 ForceNew: true, 27 ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { 28 value := v.(string) 29 re := `^(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)$` 30 if !regexp.MustCompile(re).MatchString(value) { 31 errors = append(errors, fmt.Errorf( 32 "%q (%q) doesn't match regexp %q", k, value, re)) 33 } 34 return 35 }, 36 }, 37 38 "health_checks": &schema.Schema{ 39 Type: schema.TypeSet, 40 Elem: &schema.Schema{Type: schema.TypeString}, 41 Required: true, 42 Set: schema.HashString, 43 }, 44 45 "backend": &schema.Schema{ 46 Type: schema.TypeSet, 47 Elem: &schema.Resource{ 48 Schema: map[string]*schema.Schema{ 49 "group": &schema.Schema{ 50 Type: schema.TypeString, 51 Optional: true, 52 }, 53 "balancing_mode": &schema.Schema{ 54 Type: schema.TypeString, 55 Optional: true, 56 Default: "UTILIZATION", 57 }, 58 "capacity_scaler": &schema.Schema{ 59 Type: schema.TypeFloat, 60 Optional: true, 61 Default: 1, 62 }, 63 "description": &schema.Schema{ 64 Type: schema.TypeString, 65 Optional: true, 66 }, 67 "max_rate": &schema.Schema{ 68 Type: schema.TypeInt, 69 Optional: true, 70 }, 71 "max_rate_per_instance": &schema.Schema{ 72 Type: schema.TypeFloat, 73 Optional: true, 74 }, 75 "max_utilization": &schema.Schema{ 76 Type: schema.TypeFloat, 77 Optional: true, 78 Default: 0.8, 79 }, 80 }, 81 }, 82 Optional: true, 83 Set: resourceGoogleComputeBackendServiceBackendHash, 84 }, 85 86 "description": &schema.Schema{ 87 Type: schema.TypeString, 88 Optional: true, 89 }, 90 91 "enable_cdn": &schema.Schema{ 92 Type: schema.TypeBool, 93 Optional: true, 94 Default: false, 95 }, 96 97 "fingerprint": &schema.Schema{ 98 Type: schema.TypeString, 99 Computed: true, 100 }, 101 102 "port_name": &schema.Schema{ 103 Type: schema.TypeString, 104 Optional: true, 105 Computed: true, 106 }, 107 108 "project": &schema.Schema{ 109 Type: schema.TypeString, 110 Optional: true, 111 ForceNew: true, 112 }, 113 114 "protocol": &schema.Schema{ 115 Type: schema.TypeString, 116 Optional: true, 117 Computed: true, 118 }, 119 120 "region": &schema.Schema{ 121 Type: schema.TypeString, 122 Optional: true, 123 ForceNew: true, 124 Deprecated: "This parameter has been removed as it was never used", 125 }, 126 127 "self_link": &schema.Schema{ 128 Type: schema.TypeString, 129 Computed: true, 130 }, 131 132 "session_affinity": &schema.Schema{ 133 Type: schema.TypeString, 134 Optional: true, 135 Computed: true, 136 }, 137 138 "timeout_sec": &schema.Schema{ 139 Type: schema.TypeInt, 140 Optional: true, 141 Computed: true, 142 }, 143 }, 144 } 145 } 146 147 func resourceComputeBackendServiceCreate(d *schema.ResourceData, meta interface{}) error { 148 config := meta.(*Config) 149 150 hc := d.Get("health_checks").(*schema.Set).List() 151 healthChecks := make([]string, 0, len(hc)) 152 for _, v := range hc { 153 healthChecks = append(healthChecks, v.(string)) 154 } 155 156 service := compute.BackendService{ 157 Name: d.Get("name").(string), 158 HealthChecks: healthChecks, 159 } 160 161 if v, ok := d.GetOk("backend"); ok { 162 service.Backends = expandBackends(v.(*schema.Set).List()) 163 } 164 165 if v, ok := d.GetOk("description"); ok { 166 service.Description = v.(string) 167 } 168 169 if v, ok := d.GetOk("port_name"); ok { 170 service.PortName = v.(string) 171 } 172 173 if v, ok := d.GetOk("protocol"); ok { 174 service.Protocol = v.(string) 175 } 176 177 if v, ok := d.GetOk("session_affinity"); ok { 178 service.SessionAffinity = v.(string) 179 } 180 181 if v, ok := d.GetOk("timeout_sec"); ok { 182 service.TimeoutSec = int64(v.(int)) 183 } 184 185 if v, ok := d.GetOk("enable_cdn"); ok { 186 service.EnableCDN = v.(bool) 187 } 188 189 project, err := getProject(d, config) 190 if err != nil { 191 return err 192 } 193 194 log.Printf("[DEBUG] Creating new Backend Service: %#v", service) 195 op, err := config.clientCompute.BackendServices.Insert( 196 project, &service).Do() 197 if err != nil { 198 return fmt.Errorf("Error creating backend service: %s", err) 199 } 200 201 log.Printf("[DEBUG] Waiting for new backend service, operation: %#v", op) 202 203 d.SetId(service.Name) 204 205 err = computeOperationWaitGlobal(config, op, project, "Creating Backend Service") 206 if err != nil { 207 return err 208 } 209 210 return resourceComputeBackendServiceRead(d, meta) 211 } 212 213 func resourceComputeBackendServiceRead(d *schema.ResourceData, meta interface{}) error { 214 config := meta.(*Config) 215 216 project, err := getProject(d, config) 217 if err != nil { 218 return err 219 } 220 221 service, err := config.clientCompute.BackendServices.Get( 222 project, d.Id()).Do() 223 if err != nil { 224 if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { 225 // The resource doesn't exist anymore 226 log.Printf("[WARN] Removing Backend Service %q because it's gone", d.Get("name").(string)) 227 d.SetId("") 228 229 return nil 230 } 231 232 return fmt.Errorf("Error reading service: %s", err) 233 } 234 235 d.Set("description", service.Description) 236 d.Set("enable_cdn", service.EnableCDN) 237 d.Set("port_name", service.PortName) 238 d.Set("protocol", service.Protocol) 239 d.Set("session_affinity", service.SessionAffinity) 240 d.Set("timeout_sec", service.TimeoutSec) 241 d.Set("fingerprint", service.Fingerprint) 242 d.Set("self_link", service.SelfLink) 243 244 d.Set("backend", flattenBackends(service.Backends)) 245 d.Set("health_checks", service.HealthChecks) 246 247 return nil 248 } 249 250 func resourceComputeBackendServiceUpdate(d *schema.ResourceData, meta interface{}) error { 251 config := meta.(*Config) 252 253 project, err := getProject(d, config) 254 if err != nil { 255 return err 256 } 257 258 hc := d.Get("health_checks").(*schema.Set).List() 259 healthChecks := make([]string, 0, len(hc)) 260 for _, v := range hc { 261 healthChecks = append(healthChecks, v.(string)) 262 } 263 264 service := compute.BackendService{ 265 Name: d.Get("name").(string), 266 Fingerprint: d.Get("fingerprint").(string), 267 HealthChecks: healthChecks, 268 } 269 270 // Optional things 271 if v, ok := d.GetOk("backend"); ok { 272 service.Backends = expandBackends(v.(*schema.Set).List()) 273 } 274 if v, ok := d.GetOk("description"); ok { 275 service.Description = v.(string) 276 } 277 if v, ok := d.GetOk("port_name"); ok { 278 service.PortName = v.(string) 279 } 280 if v, ok := d.GetOk("protocol"); ok { 281 service.Protocol = v.(string) 282 } 283 if v, ok := d.GetOk("timeout_sec"); ok { 284 service.TimeoutSec = int64(v.(int)) 285 } 286 287 if d.HasChange("session_affinity") { 288 service.SessionAffinity = d.Get("session_affinity").(string) 289 } 290 291 if d.HasChange("enable_cdn") { 292 service.EnableCDN = d.Get("enable_cdn").(bool) 293 } 294 295 log.Printf("[DEBUG] Updating existing Backend Service %q: %#v", d.Id(), service) 296 op, err := config.clientCompute.BackendServices.Update( 297 project, d.Id(), &service).Do() 298 if err != nil { 299 return fmt.Errorf("Error updating backend service: %s", err) 300 } 301 302 d.SetId(service.Name) 303 304 err = computeOperationWaitGlobal(config, op, project, "Updating Backend Service") 305 if err != nil { 306 return err 307 } 308 309 return resourceComputeBackendServiceRead(d, meta) 310 } 311 312 func resourceComputeBackendServiceDelete(d *schema.ResourceData, meta interface{}) error { 313 config := meta.(*Config) 314 315 project, err := getProject(d, config) 316 if err != nil { 317 return err 318 } 319 320 log.Printf("[DEBUG] Deleting backend service %s", d.Id()) 321 op, err := config.clientCompute.BackendServices.Delete( 322 project, d.Id()).Do() 323 if err != nil { 324 return fmt.Errorf("Error deleting backend service: %s", err) 325 } 326 327 err = computeOperationWaitGlobal(config, op, project, "Deleting Backend Service") 328 if err != nil { 329 return err 330 } 331 332 d.SetId("") 333 return nil 334 } 335 336 func expandBackends(configured []interface{}) []*compute.Backend { 337 backends := make([]*compute.Backend, 0, len(configured)) 338 339 for _, raw := range configured { 340 data := raw.(map[string]interface{}) 341 342 b := compute.Backend{ 343 Group: data["group"].(string), 344 } 345 346 if v, ok := data["balancing_mode"]; ok { 347 b.BalancingMode = v.(string) 348 } 349 if v, ok := data["capacity_scaler"]; ok { 350 b.CapacityScaler = v.(float64) 351 } 352 if v, ok := data["description"]; ok { 353 b.Description = v.(string) 354 } 355 if v, ok := data["max_rate"]; ok { 356 b.MaxRate = int64(v.(int)) 357 } 358 if v, ok := data["max_rate_per_instance"]; ok { 359 b.MaxRatePerInstance = v.(float64) 360 } 361 if v, ok := data["max_utilization"]; ok { 362 b.MaxUtilization = v.(float64) 363 } 364 365 backends = append(backends, &b) 366 } 367 368 return backends 369 } 370 371 func flattenBackends(backends []*compute.Backend) []map[string]interface{} { 372 result := make([]map[string]interface{}, 0, len(backends)) 373 374 for _, b := range backends { 375 data := make(map[string]interface{}) 376 377 data["balancing_mode"] = b.BalancingMode 378 data["capacity_scaler"] = b.CapacityScaler 379 data["description"] = b.Description 380 data["group"] = b.Group 381 data["max_rate"] = b.MaxRate 382 data["max_rate_per_instance"] = b.MaxRatePerInstance 383 data["max_utilization"] = b.MaxUtilization 384 385 result = append(result, data) 386 } 387 388 return result 389 } 390 391 func resourceGoogleComputeBackendServiceBackendHash(v interface{}) int { 392 if v == nil { 393 return 0 394 } 395 396 var buf bytes.Buffer 397 m := v.(map[string]interface{}) 398 399 buf.WriteString(fmt.Sprintf("%s-", m["group"].(string))) 400 401 if v, ok := m["balancing_mode"]; ok { 402 buf.WriteString(fmt.Sprintf("%s-", v.(string))) 403 } 404 if v, ok := m["capacity_scaler"]; ok { 405 buf.WriteString(fmt.Sprintf("%f-", v.(float64))) 406 } 407 if v, ok := m["description"]; ok { 408 buf.WriteString(fmt.Sprintf("%s-", v.(string))) 409 } 410 if v, ok := m["max_rate"]; ok { 411 buf.WriteString(fmt.Sprintf("%d-", int64(v.(int)))) 412 } 413 if v, ok := m["max_rate_per_instance"]; ok { 414 buf.WriteString(fmt.Sprintf("%f-", v.(float64))) 415 } 416 if v, ok := m["max_rate_per_instance"]; ok { 417 buf.WriteString(fmt.Sprintf("%f-", v.(float64))) 418 } 419 420 return hashcode.String(buf.String()) 421 }