github.com/recobe182/terraform@v0.8.5-0.20170117231232-49ab22a935b7/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 }, 125 126 "self_link": &schema.Schema{ 127 Type: schema.TypeString, 128 Computed: true, 129 }, 130 131 "session_affinity": &schema.Schema{ 132 Type: schema.TypeString, 133 Optional: true, 134 Computed: true, 135 }, 136 137 "timeout_sec": &schema.Schema{ 138 Type: schema.TypeInt, 139 Optional: true, 140 Computed: true, 141 }, 142 }, 143 } 144 } 145 146 func resourceComputeBackendServiceCreate(d *schema.ResourceData, meta interface{}) error { 147 config := meta.(*Config) 148 149 hc := d.Get("health_checks").(*schema.Set).List() 150 healthChecks := make([]string, 0, len(hc)) 151 for _, v := range hc { 152 healthChecks = append(healthChecks, v.(string)) 153 } 154 155 service := compute.BackendService{ 156 Name: d.Get("name").(string), 157 HealthChecks: healthChecks, 158 } 159 160 if v, ok := d.GetOk("backend"); ok { 161 service.Backends = expandBackends(v.(*schema.Set).List()) 162 } 163 164 if v, ok := d.GetOk("description"); ok { 165 service.Description = v.(string) 166 } 167 168 if v, ok := d.GetOk("port_name"); ok { 169 service.PortName = v.(string) 170 } 171 172 if v, ok := d.GetOk("protocol"); ok { 173 service.Protocol = v.(string) 174 } 175 176 if v, ok := d.GetOk("session_affinity"); ok { 177 service.SessionAffinity = v.(string) 178 } 179 180 if v, ok := d.GetOk("timeout_sec"); ok { 181 service.TimeoutSec = int64(v.(int)) 182 } 183 184 if v, ok := d.GetOk("enable_cdn"); ok { 185 service.EnableCDN = v.(bool) 186 } 187 188 project, err := getProject(d, config) 189 if err != nil { 190 return err 191 } 192 193 log.Printf("[DEBUG] Creating new Backend Service: %#v", service) 194 op, err := config.clientCompute.BackendServices.Insert( 195 project, &service).Do() 196 if err != nil { 197 return fmt.Errorf("Error creating backend service: %s", err) 198 } 199 200 log.Printf("[DEBUG] Waiting for new backend service, operation: %#v", op) 201 202 d.SetId(service.Name) 203 204 err = computeOperationWaitGlobal(config, op, project, "Creating Backend Service") 205 if err != nil { 206 return err 207 } 208 209 return resourceComputeBackendServiceRead(d, meta) 210 } 211 212 func resourceComputeBackendServiceRead(d *schema.ResourceData, meta interface{}) error { 213 config := meta.(*Config) 214 215 project, err := getProject(d, config) 216 if err != nil { 217 return err 218 } 219 220 service, err := config.clientCompute.BackendServices.Get( 221 project, d.Id()).Do() 222 if err != nil { 223 if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { 224 // The resource doesn't exist anymore 225 log.Printf("[WARN] Removing Backend Service %q because it's gone", d.Get("name").(string)) 226 d.SetId("") 227 228 return nil 229 } 230 231 return fmt.Errorf("Error reading service: %s", err) 232 } 233 234 d.Set("description", service.Description) 235 d.Set("enable_cdn", service.EnableCDN) 236 d.Set("port_name", service.PortName) 237 d.Set("protocol", service.Protocol) 238 d.Set("session_affinity", service.SessionAffinity) 239 d.Set("timeout_sec", service.TimeoutSec) 240 d.Set("fingerprint", service.Fingerprint) 241 d.Set("self_link", service.SelfLink) 242 243 d.Set("backend", flattenBackends(service.Backends)) 244 d.Set("health_checks", service.HealthChecks) 245 246 return nil 247 } 248 249 func resourceComputeBackendServiceUpdate(d *schema.ResourceData, meta interface{}) error { 250 config := meta.(*Config) 251 252 project, err := getProject(d, config) 253 if err != nil { 254 return err 255 } 256 257 hc := d.Get("health_checks").(*schema.Set).List() 258 healthChecks := make([]string, 0, len(hc)) 259 for _, v := range hc { 260 healthChecks = append(healthChecks, v.(string)) 261 } 262 263 service := compute.BackendService{ 264 Name: d.Get("name").(string), 265 Fingerprint: d.Get("fingerprint").(string), 266 HealthChecks: healthChecks, 267 } 268 269 // Optional things 270 if v, ok := d.GetOk("backend"); ok { 271 service.Backends = expandBackends(v.(*schema.Set).List()) 272 } 273 if v, ok := d.GetOk("description"); ok { 274 service.Description = v.(string) 275 } 276 if v, ok := d.GetOk("port_name"); ok { 277 service.PortName = v.(string) 278 } 279 if v, ok := d.GetOk("protocol"); ok { 280 service.Protocol = v.(string) 281 } 282 if v, ok := d.GetOk("timeout_sec"); ok { 283 service.TimeoutSec = int64(v.(int)) 284 } 285 286 if d.HasChange("session_affinity") { 287 service.SessionAffinity = d.Get("session_affinity").(string) 288 } 289 290 if d.HasChange("enable_cdn") { 291 service.EnableCDN = d.Get("enable_cdn").(bool) 292 } 293 294 log.Printf("[DEBUG] Updating existing Backend Service %q: %#v", d.Id(), service) 295 op, err := config.clientCompute.BackendServices.Update( 296 project, d.Id(), &service).Do() 297 if err != nil { 298 return fmt.Errorf("Error updating backend service: %s", err) 299 } 300 301 d.SetId(service.Name) 302 303 err = computeOperationWaitGlobal(config, op, project, "Updating Backend Service") 304 if err != nil { 305 return err 306 } 307 308 return resourceComputeBackendServiceRead(d, meta) 309 } 310 311 func resourceComputeBackendServiceDelete(d *schema.ResourceData, meta interface{}) error { 312 config := meta.(*Config) 313 314 project, err := getProject(d, config) 315 if err != nil { 316 return err 317 } 318 319 log.Printf("[DEBUG] Deleting backend service %s", d.Id()) 320 op, err := config.clientCompute.BackendServices.Delete( 321 project, d.Id()).Do() 322 if err != nil { 323 return fmt.Errorf("Error deleting backend service: %s", err) 324 } 325 326 err = computeOperationWaitGlobal(config, op, project, "Deleting Backend Service") 327 if err != nil { 328 return err 329 } 330 331 d.SetId("") 332 return nil 333 } 334 335 func expandBackends(configured []interface{}) []*compute.Backend { 336 backends := make([]*compute.Backend, 0, len(configured)) 337 338 for _, raw := range configured { 339 data := raw.(map[string]interface{}) 340 341 b := compute.Backend{ 342 Group: data["group"].(string), 343 } 344 345 if v, ok := data["balancing_mode"]; ok { 346 b.BalancingMode = v.(string) 347 } 348 if v, ok := data["capacity_scaler"]; ok { 349 b.CapacityScaler = v.(float64) 350 } 351 if v, ok := data["description"]; ok { 352 b.Description = v.(string) 353 } 354 if v, ok := data["max_rate"]; ok { 355 b.MaxRate = int64(v.(int)) 356 } 357 if v, ok := data["max_rate_per_instance"]; ok { 358 b.MaxRatePerInstance = v.(float64) 359 } 360 if v, ok := data["max_utilization"]; ok { 361 b.MaxUtilization = v.(float64) 362 } 363 364 backends = append(backends, &b) 365 } 366 367 return backends 368 } 369 370 func flattenBackends(backends []*compute.Backend) []map[string]interface{} { 371 result := make([]map[string]interface{}, 0, len(backends)) 372 373 for _, b := range backends { 374 data := make(map[string]interface{}) 375 376 data["balancing_mode"] = b.BalancingMode 377 data["capacity_scaler"] = b.CapacityScaler 378 data["description"] = b.Description 379 data["group"] = b.Group 380 data["max_rate"] = b.MaxRate 381 data["max_rate_per_instance"] = b.MaxRatePerInstance 382 data["max_utilization"] = b.MaxUtilization 383 384 result = append(result, data) 385 } 386 387 return result 388 } 389 390 func resourceGoogleComputeBackendServiceBackendHash(v interface{}) int { 391 if v == nil { 392 return 0 393 } 394 395 var buf bytes.Buffer 396 m := v.(map[string]interface{}) 397 398 buf.WriteString(fmt.Sprintf("%s-", m["group"].(string))) 399 400 if v, ok := m["balancing_mode"]; ok { 401 buf.WriteString(fmt.Sprintf("%s-", v.(string))) 402 } 403 if v, ok := m["capacity_scaler"]; ok { 404 buf.WriteString(fmt.Sprintf("%f-", v.(float64))) 405 } 406 if v, ok := m["description"]; ok { 407 buf.WriteString(fmt.Sprintf("%s-", v.(string))) 408 } 409 if v, ok := m["max_rate"]; ok { 410 buf.WriteString(fmt.Sprintf("%d-", int64(v.(int)))) 411 } 412 if v, ok := m["max_rate_per_instance"]; ok { 413 buf.WriteString(fmt.Sprintf("%f-", v.(float64))) 414 } 415 if v, ok := m["max_rate_per_instance"]; ok { 416 buf.WriteString(fmt.Sprintf("%f-", v.(float64))) 417 } 418 419 return hashcode.String(buf.String()) 420 }