github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/openstack/resource_openstack_compute_instance_v2.go (about) 1 package openstack 2 3 import ( 4 "bytes" 5 "crypto/sha1" 6 "encoding/hex" 7 "fmt" 8 "log" 9 "os" 10 "time" 11 12 "github.com/gophercloud/gophercloud" 13 "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/bootfromvolume" 14 "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/floatingips" 15 "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/keypairs" 16 "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/schedulerhints" 17 "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/secgroups" 18 "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/startstop" 19 "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/tenantnetworks" 20 "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/volumeattach" 21 "github.com/gophercloud/gophercloud/openstack/compute/v2/flavors" 22 "github.com/gophercloud/gophercloud/openstack/compute/v2/images" 23 "github.com/gophercloud/gophercloud/openstack/compute/v2/servers" 24 "github.com/hashicorp/terraform/helper/hashcode" 25 "github.com/hashicorp/terraform/helper/resource" 26 "github.com/hashicorp/terraform/helper/schema" 27 ) 28 29 func resourceComputeInstanceV2() *schema.Resource { 30 return &schema.Resource{ 31 Create: resourceComputeInstanceV2Create, 32 Read: resourceComputeInstanceV2Read, 33 Update: resourceComputeInstanceV2Update, 34 Delete: resourceComputeInstanceV2Delete, 35 36 Schema: map[string]*schema.Schema{ 37 "region": &schema.Schema{ 38 Type: schema.TypeString, 39 Required: true, 40 ForceNew: true, 41 DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""), 42 }, 43 "name": &schema.Schema{ 44 Type: schema.TypeString, 45 Required: true, 46 ForceNew: false, 47 }, 48 "image_id": &schema.Schema{ 49 Type: schema.TypeString, 50 Optional: true, 51 ForceNew: true, 52 Computed: true, 53 }, 54 "image_name": &schema.Schema{ 55 Type: schema.TypeString, 56 Optional: true, 57 ForceNew: true, 58 Computed: true, 59 }, 60 "flavor_id": &schema.Schema{ 61 Type: schema.TypeString, 62 Optional: true, 63 ForceNew: false, 64 Computed: true, 65 DefaultFunc: schema.EnvDefaultFunc("OS_FLAVOR_ID", nil), 66 }, 67 "flavor_name": &schema.Schema{ 68 Type: schema.TypeString, 69 Optional: true, 70 ForceNew: false, 71 Computed: true, 72 DefaultFunc: schema.EnvDefaultFunc("OS_FLAVOR_NAME", nil), 73 }, 74 "floating_ip": &schema.Schema{ 75 Type: schema.TypeString, 76 Optional: true, 77 ForceNew: false, 78 }, 79 "user_data": &schema.Schema{ 80 Type: schema.TypeString, 81 Optional: true, 82 ForceNew: true, 83 // just stash the hash for state & diff comparisons 84 StateFunc: func(v interface{}) string { 85 switch v.(type) { 86 case string: 87 hash := sha1.Sum([]byte(v.(string))) 88 return hex.EncodeToString(hash[:]) 89 default: 90 return "" 91 } 92 }, 93 }, 94 "security_groups": &schema.Schema{ 95 Type: schema.TypeSet, 96 Optional: true, 97 ForceNew: false, 98 Computed: true, 99 Elem: &schema.Schema{Type: schema.TypeString}, 100 Set: schema.HashString, 101 }, 102 "availability_zone": &schema.Schema{ 103 Type: schema.TypeString, 104 Optional: true, 105 ForceNew: true, 106 }, 107 "network": &schema.Schema{ 108 Type: schema.TypeList, 109 Optional: true, 110 ForceNew: true, 111 Computed: true, 112 Elem: &schema.Resource{ 113 Schema: map[string]*schema.Schema{ 114 "uuid": &schema.Schema{ 115 Type: schema.TypeString, 116 Optional: true, 117 ForceNew: true, 118 Computed: true, 119 }, 120 "name": &schema.Schema{ 121 Type: schema.TypeString, 122 Optional: true, 123 ForceNew: true, 124 Computed: true, 125 }, 126 "port": &schema.Schema{ 127 Type: schema.TypeString, 128 Optional: true, 129 ForceNew: true, 130 Computed: true, 131 }, 132 "fixed_ip_v4": &schema.Schema{ 133 Type: schema.TypeString, 134 Optional: true, 135 ForceNew: true, 136 Computed: true, 137 }, 138 "fixed_ip_v6": &schema.Schema{ 139 Type: schema.TypeString, 140 Optional: true, 141 ForceNew: true, 142 Computed: true, 143 }, 144 "floating_ip": &schema.Schema{ 145 Type: schema.TypeString, 146 Optional: true, 147 Computed: true, 148 }, 149 "mac": &schema.Schema{ 150 Type: schema.TypeString, 151 Computed: true, 152 }, 153 "access_network": &schema.Schema{ 154 Type: schema.TypeBool, 155 Optional: true, 156 Default: false, 157 }, 158 }, 159 }, 160 }, 161 "metadata": &schema.Schema{ 162 Type: schema.TypeMap, 163 Optional: true, 164 ForceNew: false, 165 }, 166 "config_drive": &schema.Schema{ 167 Type: schema.TypeBool, 168 Optional: true, 169 ForceNew: true, 170 }, 171 "admin_pass": &schema.Schema{ 172 Type: schema.TypeString, 173 Optional: true, 174 ForceNew: false, 175 }, 176 "access_ip_v4": &schema.Schema{ 177 Type: schema.TypeString, 178 Computed: true, 179 Optional: true, 180 ForceNew: false, 181 }, 182 "access_ip_v6": &schema.Schema{ 183 Type: schema.TypeString, 184 Computed: true, 185 Optional: true, 186 ForceNew: false, 187 }, 188 "key_pair": &schema.Schema{ 189 Type: schema.TypeString, 190 Optional: true, 191 ForceNew: true, 192 }, 193 "block_device": &schema.Schema{ 194 Type: schema.TypeList, 195 Optional: true, 196 Elem: &schema.Resource{ 197 Schema: map[string]*schema.Schema{ 198 "source_type": &schema.Schema{ 199 Type: schema.TypeString, 200 Required: true, 201 ForceNew: true, 202 }, 203 "uuid": &schema.Schema{ 204 Type: schema.TypeString, 205 Optional: true, 206 ForceNew: true, 207 }, 208 "volume_size": &schema.Schema{ 209 Type: schema.TypeInt, 210 Optional: true, 211 ForceNew: true, 212 }, 213 "destination_type": &schema.Schema{ 214 Type: schema.TypeString, 215 Optional: true, 216 ForceNew: true, 217 }, 218 "boot_index": &schema.Schema{ 219 Type: schema.TypeInt, 220 Optional: true, 221 ForceNew: true, 222 }, 223 "delete_on_termination": &schema.Schema{ 224 Type: schema.TypeBool, 225 Optional: true, 226 Default: false, 227 ForceNew: true, 228 }, 229 "guest_format": &schema.Schema{ 230 Type: schema.TypeString, 231 Optional: true, 232 ForceNew: true, 233 }, 234 }, 235 }, 236 }, 237 "volume": &schema.Schema{ 238 Type: schema.TypeSet, 239 Optional: true, 240 Elem: &schema.Resource{ 241 Schema: map[string]*schema.Schema{ 242 "id": &schema.Schema{ 243 Type: schema.TypeString, 244 Optional: true, 245 Computed: true, 246 }, 247 "volume_id": &schema.Schema{ 248 Type: schema.TypeString, 249 Required: true, 250 }, 251 "device": &schema.Schema{ 252 Type: schema.TypeString, 253 Optional: true, 254 Computed: true, 255 }, 256 }, 257 }, 258 Set: resourceComputeVolumeAttachmentHash, 259 }, 260 "scheduler_hints": &schema.Schema{ 261 Type: schema.TypeSet, 262 Optional: true, 263 Elem: &schema.Resource{ 264 Schema: map[string]*schema.Schema{ 265 "group": &schema.Schema{ 266 Type: schema.TypeString, 267 Optional: true, 268 ForceNew: true, 269 }, 270 "different_host": &schema.Schema{ 271 Type: schema.TypeList, 272 Optional: true, 273 ForceNew: true, 274 Elem: &schema.Schema{Type: schema.TypeString}, 275 }, 276 "same_host": &schema.Schema{ 277 Type: schema.TypeList, 278 Optional: true, 279 ForceNew: true, 280 Elem: &schema.Schema{Type: schema.TypeString}, 281 }, 282 "query": &schema.Schema{ 283 Type: schema.TypeList, 284 Optional: true, 285 ForceNew: true, 286 Elem: &schema.Schema{Type: schema.TypeString}, 287 }, 288 "target_cell": &schema.Schema{ 289 Type: schema.TypeString, 290 Optional: true, 291 ForceNew: true, 292 }, 293 "build_near_host_ip": &schema.Schema{ 294 Type: schema.TypeString, 295 Optional: true, 296 ForceNew: true, 297 }, 298 }, 299 }, 300 Set: resourceComputeSchedulerHintsHash, 301 }, 302 "personality": &schema.Schema{ 303 Type: schema.TypeSet, 304 Optional: true, 305 ForceNew: true, 306 Elem: &schema.Resource{ 307 Schema: map[string]*schema.Schema{ 308 "file": &schema.Schema{ 309 Type: schema.TypeString, 310 Required: true, 311 }, 312 "content": &schema.Schema{ 313 Type: schema.TypeString, 314 Required: true, 315 }, 316 }, 317 }, 318 Set: resourceComputeInstancePersonalityHash, 319 }, 320 "stop_before_destroy": &schema.Schema{ 321 Type: schema.TypeBool, 322 Optional: true, 323 Default: false, 324 }, 325 }, 326 } 327 } 328 329 func resourceComputeInstanceV2Create(d *schema.ResourceData, meta interface{}) error { 330 config := meta.(*Config) 331 computeClient, err := config.computeV2Client(d.Get("region").(string)) 332 if err != nil { 333 return fmt.Errorf("Error creating OpenStack compute client: %s", err) 334 } 335 336 var createOpts servers.CreateOptsBuilder 337 338 // Determines the Image ID using the following rules: 339 // If a bootable block_device was specified, ignore the image altogether. 340 // If an image_id was specified, use it. 341 // If an image_name was specified, look up the image ID, report if error. 342 imageId, err := getImageIDFromConfig(computeClient, d) 343 if err != nil { 344 return err 345 } 346 347 flavorId, err := getFlavorID(computeClient, d) 348 if err != nil { 349 return err 350 } 351 352 // determine if block_device configuration is correct 353 // this includes valid combinations and required attributes 354 if err := checkBlockDeviceConfig(d); err != nil { 355 return err 356 } 357 358 // check if floating IP configuration is correct 359 if err := checkInstanceFloatingIPs(d); err != nil { 360 return err 361 } 362 363 // Build a list of networks with the information given upon creation. 364 // Error out if an invalid network configuration was used. 365 networkDetails, err := getInstanceNetworks(computeClient, d) 366 if err != nil { 367 return err 368 } 369 370 networks := make([]servers.Network, len(networkDetails)) 371 for i, net := range networkDetails { 372 networks[i] = servers.Network{ 373 UUID: net["uuid"].(string), 374 Port: net["port"].(string), 375 FixedIP: net["fixed_ip_v4"].(string), 376 } 377 } 378 379 configDrive := d.Get("config_drive").(bool) 380 381 createOpts = &servers.CreateOpts{ 382 Name: d.Get("name").(string), 383 ImageRef: imageId, 384 FlavorRef: flavorId, 385 SecurityGroups: resourceInstanceSecGroupsV2(d), 386 AvailabilityZone: d.Get("availability_zone").(string), 387 Networks: networks, 388 Metadata: resourceInstanceMetadataV2(d), 389 ConfigDrive: &configDrive, 390 AdminPass: d.Get("admin_pass").(string), 391 UserData: []byte(d.Get("user_data").(string)), 392 Personality: resourceInstancePersonalityV2(d), 393 } 394 395 if keyName, ok := d.Get("key_pair").(string); ok && keyName != "" { 396 createOpts = &keypairs.CreateOptsExt{ 397 CreateOptsBuilder: createOpts, 398 KeyName: keyName, 399 } 400 } 401 402 if vL, ok := d.GetOk("block_device"); ok { 403 blockDevices, err := resourceInstanceBlockDevicesV2(d, vL.([]interface{})) 404 if err != nil { 405 return err 406 } 407 408 createOpts = &bootfromvolume.CreateOptsExt{ 409 CreateOptsBuilder: createOpts, 410 BlockDevice: blockDevices, 411 } 412 } 413 414 schedulerHintsRaw := d.Get("scheduler_hints").(*schema.Set).List() 415 if len(schedulerHintsRaw) > 0 { 416 log.Printf("[DEBUG] schedulerhints: %+v", schedulerHintsRaw) 417 schedulerHints := resourceInstanceSchedulerHintsV2(d, schedulerHintsRaw[0].(map[string]interface{})) 418 createOpts = &schedulerhints.CreateOptsExt{ 419 CreateOptsBuilder: createOpts, 420 SchedulerHints: schedulerHints, 421 } 422 } 423 424 log.Printf("[DEBUG] Create Options: %#v", createOpts) 425 426 // If a block_device is used, use the bootfromvolume.Create function as it allows an empty ImageRef. 427 // Otherwise, use the normal servers.Create function. 428 var server *servers.Server 429 if _, ok := d.GetOk("block_device"); ok { 430 server, err = bootfromvolume.Create(computeClient, createOpts).Extract() 431 } else { 432 server, err = servers.Create(computeClient, createOpts).Extract() 433 } 434 435 if err != nil { 436 return fmt.Errorf("Error creating OpenStack server: %s", err) 437 } 438 log.Printf("[INFO] Instance ID: %s", server.ID) 439 440 // Store the ID now 441 d.SetId(server.ID) 442 443 // Wait for the instance to become running so we can get some attributes 444 // that aren't available until later. 445 log.Printf( 446 "[DEBUG] Waiting for instance (%s) to become running", 447 server.ID) 448 449 stateConf := &resource.StateChangeConf{ 450 Pending: []string{"BUILD"}, 451 Target: []string{"ACTIVE"}, 452 Refresh: ServerV2StateRefreshFunc(computeClient, server.ID), 453 Timeout: 30 * time.Minute, 454 Delay: 10 * time.Second, 455 MinTimeout: 3 * time.Second, 456 } 457 458 _, err = stateConf.WaitForState() 459 if err != nil { 460 return fmt.Errorf( 461 "Error waiting for instance (%s) to become ready: %s", 462 server.ID, err) 463 } 464 465 // Now that the instance has been created, we need to do an early read on the 466 // networks in order to associate floating IPs 467 _, err = getInstanceNetworksAndAddresses(computeClient, d) 468 469 // If floating IPs were specified, associate them after the instance has launched. 470 err = associateFloatingIPsToInstance(computeClient, d) 471 if err != nil { 472 return err 473 } 474 475 // if volumes were specified, attach them after the instance has launched. 476 if v, ok := d.GetOk("volume"); ok { 477 vols := v.(*schema.Set).List() 478 if blockClient, err := config.blockStorageV1Client(d.Get("region").(string)); err != nil { 479 return fmt.Errorf("Error creating OpenStack block storage client: %s", err) 480 } else { 481 if err := attachVolumesToInstance(computeClient, blockClient, d.Id(), vols); err != nil { 482 return err 483 } 484 } 485 } 486 487 return resourceComputeInstanceV2Read(d, meta) 488 } 489 490 func resourceComputeInstanceV2Read(d *schema.ResourceData, meta interface{}) error { 491 config := meta.(*Config) 492 computeClient, err := config.computeV2Client(d.Get("region").(string)) 493 if err != nil { 494 return fmt.Errorf("Error creating OpenStack compute client: %s", err) 495 } 496 497 server, err := servers.Get(computeClient, d.Id()).Extract() 498 if err != nil { 499 return CheckDeleted(d, err, "server") 500 } 501 502 log.Printf("[DEBUG] Retrieved Server %s: %+v", d.Id(), server) 503 504 d.Set("name", server.Name) 505 506 // Get the instance network and address information 507 networks, err := getInstanceNetworksAndAddresses(computeClient, d) 508 if err != nil { 509 return err 510 } 511 512 // Determine the best IPv4 and IPv6 addresses to access the instance with 513 hostv4, hostv6 := getInstanceAccessAddresses(d, networks) 514 515 if server.AccessIPv4 != "" && hostv4 == "" { 516 hostv4 = server.AccessIPv4 517 } 518 519 if server.AccessIPv6 != "" && hostv6 == "" { 520 hostv6 = server.AccessIPv6 521 } 522 523 d.Set("network", networks) 524 d.Set("access_ip_v4", hostv4) 525 d.Set("access_ip_v6", hostv6) 526 527 // Determine the best IP address to use for SSH connectivity. 528 // Prefer IPv4 over IPv6. 529 preferredSSHAddress := "" 530 if hostv4 != "" { 531 preferredSSHAddress = hostv4 532 } else if hostv6 != "" { 533 preferredSSHAddress = hostv6 534 } 535 536 if preferredSSHAddress != "" { 537 // Initialize the connection info 538 d.SetConnInfo(map[string]string{ 539 "type": "ssh", 540 "host": preferredSSHAddress, 541 }) 542 } 543 544 d.Set("metadata", server.Metadata) 545 546 secGrpNames := []string{} 547 for _, sg := range server.SecurityGroups { 548 secGrpNames = append(secGrpNames, sg["name"].(string)) 549 } 550 d.Set("security_groups", secGrpNames) 551 552 flavorId, ok := server.Flavor["id"].(string) 553 if !ok { 554 return fmt.Errorf("Error setting OpenStack server's flavor: %v", server.Flavor) 555 } 556 d.Set("flavor_id", flavorId) 557 558 flavor, err := flavors.Get(computeClient, flavorId).Extract() 559 if err != nil { 560 return err 561 } 562 d.Set("flavor_name", flavor.Name) 563 564 // Set the instance's image information appropriately 565 if err := setImageInformation(computeClient, server, d); err != nil { 566 return err 567 } 568 569 // volume attachments 570 if err := getVolumeAttachments(computeClient, d); err != nil { 571 return err 572 } 573 574 return nil 575 } 576 577 func resourceComputeInstanceV2Update(d *schema.ResourceData, meta interface{}) error { 578 config := meta.(*Config) 579 computeClient, err := config.computeV2Client(d.Get("region").(string)) 580 if err != nil { 581 return fmt.Errorf("Error creating OpenStack compute client: %s", err) 582 } 583 584 var updateOpts servers.UpdateOpts 585 if d.HasChange("name") { 586 updateOpts.Name = d.Get("name").(string) 587 } 588 589 if updateOpts != (servers.UpdateOpts{}) { 590 _, err := servers.Update(computeClient, d.Id(), updateOpts).Extract() 591 if err != nil { 592 return fmt.Errorf("Error updating OpenStack server: %s", err) 593 } 594 } 595 596 if d.HasChange("metadata") { 597 var metadataOpts servers.MetadataOpts 598 metadataOpts = make(servers.MetadataOpts) 599 newMetadata := d.Get("metadata").(map[string]interface{}) 600 for k, v := range newMetadata { 601 metadataOpts[k] = v.(string) 602 } 603 604 _, err := servers.UpdateMetadata(computeClient, d.Id(), metadataOpts).Extract() 605 if err != nil { 606 return fmt.Errorf("Error updating OpenStack server (%s) metadata: %s", d.Id(), err) 607 } 608 } 609 610 if d.HasChange("security_groups") { 611 oldSGRaw, newSGRaw := d.GetChange("security_groups") 612 oldSGSet := oldSGRaw.(*schema.Set) 613 newSGSet := newSGRaw.(*schema.Set) 614 secgroupsToAdd := newSGSet.Difference(oldSGSet) 615 secgroupsToRemove := oldSGSet.Difference(newSGSet) 616 617 log.Printf("[DEBUG] Security groups to add: %v", secgroupsToAdd) 618 619 log.Printf("[DEBUG] Security groups to remove: %v", secgroupsToRemove) 620 621 for _, g := range secgroupsToRemove.List() { 622 err := secgroups.RemoveServer(computeClient, d.Id(), g.(string)).ExtractErr() 623 if err != nil && err.Error() != "EOF" { 624 if _, ok := err.(gophercloud.ErrDefault404); ok { 625 continue 626 } 627 628 return fmt.Errorf("Error removing security group (%s) from OpenStack server (%s): %s", g, d.Id(), err) 629 } else { 630 log.Printf("[DEBUG] Removed security group (%s) from instance (%s)", g, d.Id()) 631 } 632 } 633 634 for _, g := range secgroupsToAdd.List() { 635 err := secgroups.AddServer(computeClient, d.Id(), g.(string)).ExtractErr() 636 if err != nil && err.Error() != "EOF" { 637 return fmt.Errorf("Error adding security group (%s) to OpenStack server (%s): %s", g, d.Id(), err) 638 } 639 log.Printf("[DEBUG] Added security group (%s) to instance (%s)", g, d.Id()) 640 } 641 } 642 643 if d.HasChange("admin_pass") { 644 if newPwd, ok := d.Get("admin_pass").(string); ok { 645 err := servers.ChangeAdminPassword(computeClient, d.Id(), newPwd).ExtractErr() 646 if err != nil { 647 return fmt.Errorf("Error changing admin password of OpenStack server (%s): %s", d.Id(), err) 648 } 649 } 650 } 651 652 if d.HasChange("floating_ip") { 653 oldFIP, newFIP := d.GetChange("floating_ip") 654 log.Printf("[DEBUG] Old Floating IP: %v", oldFIP) 655 log.Printf("[DEBUG] New Floating IP: %v", newFIP) 656 if oldFIP.(string) != "" { 657 log.Printf("[DEBUG] Attempting to disassociate %s from %s", oldFIP, d.Id()) 658 if err := disassociateFloatingIPFromInstance(computeClient, oldFIP.(string), d.Id(), ""); err != nil { 659 return fmt.Errorf("Error disassociating Floating IP during update: %s", err) 660 } 661 } 662 663 if newFIP.(string) != "" { 664 log.Printf("[DEBUG] Attempting to associate %s to %s", newFIP, d.Id()) 665 if err := associateFloatingIPToInstance(computeClient, newFIP.(string), d.Id(), ""); err != nil { 666 return fmt.Errorf("Error associating Floating IP during update: %s", err) 667 } 668 } 669 } 670 671 if d.HasChange("network") { 672 oldNetworks, newNetworks := d.GetChange("network") 673 oldNetworkList := oldNetworks.([]interface{}) 674 newNetworkList := newNetworks.([]interface{}) 675 for i, oldNet := range oldNetworkList { 676 var oldFIP, newFIP string 677 var oldFixedIP, newFixedIP string 678 679 if oldNetRaw, ok := oldNet.(map[string]interface{}); ok { 680 oldFIP = oldNetRaw["floating_ip"].(string) 681 oldFixedIP = oldNetRaw["fixed_ip_v4"].(string) 682 } 683 684 if len(newNetworkList) > i { 685 if newNetRaw, ok := newNetworkList[i].(map[string]interface{}); ok { 686 newFIP = newNetRaw["floating_ip"].(string) 687 newFixedIP = newNetRaw["fixed_ip_v4"].(string) 688 } 689 } 690 691 // Only changes to the floating IP are supported 692 if oldFIP != "" && oldFIP != newFIP { 693 log.Printf("[DEBUG] Attempting to disassociate %s from %s", oldFIP, d.Id()) 694 if err := disassociateFloatingIPFromInstance(computeClient, oldFIP, d.Id(), oldFixedIP); err != nil { 695 return fmt.Errorf("Error disassociating Floating IP during update: %s", err) 696 } 697 } 698 699 if newFIP != "" && oldFIP != newFIP { 700 log.Printf("[DEBUG] Attempting to associate %s to %s", newFIP, d.Id()) 701 if err := associateFloatingIPToInstance(computeClient, newFIP, d.Id(), newFixedIP); err != nil { 702 return fmt.Errorf("Error associating Floating IP during update: %s", err) 703 } 704 } 705 } 706 } 707 708 if d.HasChange("volume") { 709 // old attachments and new attachments 710 oldAttachments, newAttachments := d.GetChange("volume") 711 // for each old attachment, detach the volume 712 oldAttachmentSet := oldAttachments.(*schema.Set).List() 713 714 log.Printf("[DEBUG] Attempting to detach the following volumes: %#v", oldAttachmentSet) 715 if blockClient, err := config.blockStorageV1Client(d.Get("region").(string)); err != nil { 716 return err 717 } else { 718 if err := detachVolumesFromInstance(computeClient, blockClient, d.Id(), oldAttachmentSet); err != nil { 719 return err 720 } 721 } 722 723 // for each new attachment, attach the volume 724 newAttachmentSet := newAttachments.(*schema.Set).List() 725 if blockClient, err := config.blockStorageV1Client(d.Get("region").(string)); err != nil { 726 return err 727 } else { 728 if err := attachVolumesToInstance(computeClient, blockClient, d.Id(), newAttachmentSet); err != nil { 729 return err 730 } 731 } 732 733 d.SetPartial("volume") 734 } 735 736 if d.HasChange("flavor_id") || d.HasChange("flavor_name") { 737 var newFlavorId string 738 var err error 739 if d.HasChange("flavor_id") { 740 newFlavorId = d.Get("flavor_id").(string) 741 } else { 742 newFlavorName := d.Get("flavor_name").(string) 743 newFlavorId, err = flavors.IDFromName(computeClient, newFlavorName) 744 if err != nil { 745 return err 746 } 747 } 748 749 resizeOpts := &servers.ResizeOpts{ 750 FlavorRef: newFlavorId, 751 } 752 log.Printf("[DEBUG] Resize configuration: %#v", resizeOpts) 753 err = servers.Resize(computeClient, d.Id(), resizeOpts).ExtractErr() 754 if err != nil { 755 return fmt.Errorf("Error resizing OpenStack server: %s", err) 756 } 757 758 // Wait for the instance to finish resizing. 759 log.Printf("[DEBUG] Waiting for instance (%s) to finish resizing", d.Id()) 760 761 stateConf := &resource.StateChangeConf{ 762 Pending: []string{"RESIZE"}, 763 Target: []string{"VERIFY_RESIZE"}, 764 Refresh: ServerV2StateRefreshFunc(computeClient, d.Id()), 765 Timeout: 30 * time.Minute, 766 Delay: 10 * time.Second, 767 MinTimeout: 3 * time.Second, 768 } 769 770 _, err = stateConf.WaitForState() 771 if err != nil { 772 return fmt.Errorf("Error waiting for instance (%s) to resize: %s", d.Id(), err) 773 } 774 775 // Confirm resize. 776 log.Printf("[DEBUG] Confirming resize") 777 err = servers.ConfirmResize(computeClient, d.Id()).ExtractErr() 778 if err != nil { 779 return fmt.Errorf("Error confirming resize of OpenStack server: %s", err) 780 } 781 782 stateConf = &resource.StateChangeConf{ 783 Pending: []string{"VERIFY_RESIZE"}, 784 Target: []string{"ACTIVE"}, 785 Refresh: ServerV2StateRefreshFunc(computeClient, d.Id()), 786 Timeout: 30 * time.Minute, 787 Delay: 10 * time.Second, 788 MinTimeout: 3 * time.Second, 789 } 790 791 _, err = stateConf.WaitForState() 792 if err != nil { 793 return fmt.Errorf("Error waiting for instance (%s) to confirm resize: %s", d.Id(), err) 794 } 795 } 796 797 return resourceComputeInstanceV2Read(d, meta) 798 } 799 800 func resourceComputeInstanceV2Delete(d *schema.ResourceData, meta interface{}) error { 801 config := meta.(*Config) 802 computeClient, err := config.computeV2Client(d.Get("region").(string)) 803 if err != nil { 804 return fmt.Errorf("Error creating OpenStack compute client: %s", err) 805 } 806 807 // Make sure all volumes are detached before deleting 808 volumes := d.Get("volume") 809 if volumeSet, ok := volumes.(*schema.Set); ok { 810 volumeList := volumeSet.List() 811 if len(volumeList) > 0 { 812 log.Printf("[DEBUG] Attempting to detach the following volumes: %#v", volumeList) 813 if blockClient, err := config.blockStorageV1Client(d.Get("region").(string)); err != nil { 814 return err 815 } else { 816 if err := detachVolumesFromInstance(computeClient, blockClient, d.Id(), volumeList); err != nil { 817 return err 818 } 819 } 820 } 821 } 822 823 if d.Get("stop_before_destroy").(bool) { 824 err = startstop.Stop(computeClient, d.Id()).ExtractErr() 825 if err != nil { 826 log.Printf("[WARN] Error stopping OpenStack instance: %s", err) 827 } else { 828 stopStateConf := &resource.StateChangeConf{ 829 Pending: []string{"ACTIVE"}, 830 Target: []string{"SHUTOFF"}, 831 Refresh: ServerV2StateRefreshFunc(computeClient, d.Id()), 832 Timeout: 3 * time.Minute, 833 Delay: 10 * time.Second, 834 MinTimeout: 3 * time.Second, 835 } 836 log.Printf("[DEBUG] Waiting for instance (%s) to stop", d.Id()) 837 _, err = stopStateConf.WaitForState() 838 if err != nil { 839 log.Printf("[WARN] Error waiting for instance (%s) to stop: %s, proceeding to delete", d.Id(), err) 840 } 841 } 842 } 843 844 err = servers.Delete(computeClient, d.Id()).ExtractErr() 845 if err != nil { 846 return fmt.Errorf("Error deleting OpenStack server: %s", err) 847 } 848 849 // Wait for the instance to delete before moving on. 850 log.Printf("[DEBUG] Waiting for instance (%s) to delete", d.Id()) 851 852 stateConf := &resource.StateChangeConf{ 853 Pending: []string{"ACTIVE", "SHUTOFF"}, 854 Target: []string{"DELETED"}, 855 Refresh: ServerV2StateRefreshFunc(computeClient, d.Id()), 856 Timeout: 30 * time.Minute, 857 Delay: 10 * time.Second, 858 MinTimeout: 3 * time.Second, 859 } 860 861 _, err = stateConf.WaitForState() 862 if err != nil { 863 return fmt.Errorf( 864 "Error waiting for instance (%s) to delete: %s", 865 d.Id(), err) 866 } 867 868 d.SetId("") 869 return nil 870 } 871 872 // ServerV2StateRefreshFunc returns a resource.StateRefreshFunc that is used to watch 873 // an OpenStack instance. 874 func ServerV2StateRefreshFunc(client *gophercloud.ServiceClient, instanceID string) resource.StateRefreshFunc { 875 return func() (interface{}, string, error) { 876 s, err := servers.Get(client, instanceID).Extract() 877 if err != nil { 878 if _, ok := err.(gophercloud.ErrDefault404); ok { 879 return s, "DELETED", nil 880 } 881 return nil, "", err 882 } 883 884 return s, s.Status, nil 885 } 886 } 887 888 func resourceInstanceSecGroupsV2(d *schema.ResourceData) []string { 889 rawSecGroups := d.Get("security_groups").(*schema.Set).List() 890 secgroups := make([]string, len(rawSecGroups)) 891 for i, raw := range rawSecGroups { 892 secgroups[i] = raw.(string) 893 } 894 return secgroups 895 } 896 897 // getInstanceNetworks collects instance network information from different sources 898 // and aggregates it all together. 899 func getInstanceNetworksAndAddresses(computeClient *gophercloud.ServiceClient, d *schema.ResourceData) ([]map[string]interface{}, error) { 900 server, err := servers.Get(computeClient, d.Id()).Extract() 901 902 if err != nil { 903 return nil, CheckDeleted(d, err, "server") 904 } 905 906 networkDetails, err := getInstanceNetworks(computeClient, d) 907 addresses := getInstanceAddresses(server.Addresses) 908 if err != nil { 909 return nil, err 910 } 911 912 // if there are no networkDetails, make networks at least a length of 1 913 networkLength := 1 914 if len(networkDetails) > 0 { 915 networkLength = len(networkDetails) 916 } 917 networks := make([]map[string]interface{}, networkLength) 918 919 // Loop through all networks and addresses, 920 // merge relevant address details. 921 if len(networkDetails) == 0 { 922 for netName, n := range addresses { 923 networks[0] = map[string]interface{}{ 924 "name": netName, 925 "fixed_ip_v4": n["fixed_ip_v4"], 926 "fixed_ip_v6": n["fixed_ip_v6"], 927 "floating_ip": n["floating_ip"], 928 "mac": n["mac"], 929 } 930 } 931 } else { 932 for i, net := range networkDetails { 933 n := addresses[net["name"].(string)] 934 935 networks[i] = map[string]interface{}{ 936 "uuid": networkDetails[i]["uuid"], 937 "name": networkDetails[i]["name"], 938 "port": networkDetails[i]["port"], 939 "fixed_ip_v4": n["fixed_ip_v4"], 940 "fixed_ip_v6": n["fixed_ip_v6"], 941 "floating_ip": n["floating_ip"], 942 "mac": n["mac"], 943 "access_network": networkDetails[i]["access_network"], 944 } 945 } 946 } 947 948 log.Printf("[DEBUG] networks: %+v", networks) 949 950 return networks, nil 951 } 952 953 func getInstanceNetworks(computeClient *gophercloud.ServiceClient, d *schema.ResourceData) ([]map[string]interface{}, error) { 954 rawNetworks := d.Get("network").([]interface{}) 955 newNetworks := make([]map[string]interface{}, 0, len(rawNetworks)) 956 var tenantnet tenantnetworks.Network 957 958 tenantNetworkExt := true 959 for _, raw := range rawNetworks { 960 // Not sure what causes this, but it is a possibility (see GH-2323). 961 // Since we call this function to reconcile what we'll save in the 962 // state anyways, we just ignore it. 963 if raw == nil { 964 continue 965 } 966 967 rawMap := raw.(map[string]interface{}) 968 969 allPages, err := tenantnetworks.List(computeClient).AllPages() 970 if err != nil { 971 if _, ok := err.(gophercloud.ErrDefault404); ok { 972 log.Printf("[DEBUG] os-tenant-networks disabled") 973 tenantNetworkExt = false 974 } 975 976 log.Printf("[DEBUG] Err looks like: %+v", err) 977 if errCode, ok := err.(gophercloud.ErrUnexpectedResponseCode); ok { 978 if errCode.Actual == 403 { 979 log.Printf("[DEBUG] os-tenant-networks disabled.") 980 tenantNetworkExt = false 981 } else { 982 return nil, err 983 } 984 } 985 } 986 987 networkID := "" 988 networkName := "" 989 if tenantNetworkExt { 990 networkList, err := tenantnetworks.ExtractNetworks(allPages) 991 if err != nil { 992 return nil, err 993 } 994 995 for _, network := range networkList { 996 if network.Name == rawMap["name"] { 997 tenantnet = network 998 } 999 if network.ID == rawMap["uuid"] { 1000 tenantnet = network 1001 } 1002 } 1003 1004 networkID = tenantnet.ID 1005 networkName = tenantnet.Name 1006 } else { 1007 networkID = rawMap["uuid"].(string) 1008 networkName = rawMap["name"].(string) 1009 } 1010 1011 newNetworks = append(newNetworks, map[string]interface{}{ 1012 "uuid": networkID, 1013 "name": networkName, 1014 "port": rawMap["port"].(string), 1015 "fixed_ip_v4": rawMap["fixed_ip_v4"].(string), 1016 "access_network": rawMap["access_network"].(bool), 1017 }) 1018 } 1019 1020 log.Printf("[DEBUG] networks: %+v", newNetworks) 1021 return newNetworks, nil 1022 } 1023 1024 func getInstanceAddresses(addresses map[string]interface{}) map[string]map[string]interface{} { 1025 addrs := make(map[string]map[string]interface{}) 1026 for n, networkAddresses := range addresses { 1027 addrs[n] = make(map[string]interface{}) 1028 for _, element := range networkAddresses.([]interface{}) { 1029 address := element.(map[string]interface{}) 1030 if address["OS-EXT-IPS:type"] == "floating" { 1031 addrs[n]["floating_ip"] = address["addr"] 1032 } else { 1033 if address["version"].(float64) == 4 { 1034 addrs[n]["fixed_ip_v4"] = address["addr"].(string) 1035 } else { 1036 addrs[n]["fixed_ip_v6"] = fmt.Sprintf("[%s]", address["addr"].(string)) 1037 } 1038 } 1039 if mac, ok := address["OS-EXT-IPS-MAC:mac_addr"]; ok { 1040 addrs[n]["mac"] = mac.(string) 1041 } 1042 } 1043 } 1044 1045 log.Printf("[DEBUG] Addresses: %+v", addresses) 1046 1047 return addrs 1048 } 1049 1050 func getInstanceAccessAddresses(d *schema.ResourceData, networks []map[string]interface{}) (string, string) { 1051 var hostv4, hostv6 string 1052 1053 // Start with a global floating IP 1054 floatingIP := d.Get("floating_ip").(string) 1055 if floatingIP != "" { 1056 hostv4 = floatingIP 1057 } 1058 1059 // Loop through all networks 1060 // If the network has a valid floating, fixed v4, or fixed v6 address 1061 // and hostv4 or hostv6 is not set, set hostv4/hostv6. 1062 // If the network is an "access_network" overwrite hostv4/hostv6. 1063 for _, n := range networks { 1064 var accessNetwork bool 1065 1066 if an, ok := n["access_network"].(bool); ok && an { 1067 accessNetwork = true 1068 } 1069 1070 if fixedIPv4, ok := n["fixed_ip_v4"].(string); ok && fixedIPv4 != "" { 1071 if hostv4 == "" || accessNetwork { 1072 hostv4 = fixedIPv4 1073 } 1074 } 1075 1076 if floatingIP, ok := n["floating_ip"].(string); ok && floatingIP != "" { 1077 if hostv4 == "" || accessNetwork { 1078 hostv4 = floatingIP 1079 } 1080 } 1081 1082 if fixedIPv6, ok := n["fixed_ip_v6"].(string); ok && fixedIPv6 != "" { 1083 if hostv6 == "" || accessNetwork { 1084 hostv6 = fixedIPv6 1085 } 1086 } 1087 } 1088 1089 log.Printf("[DEBUG] OpenStack Instance Network Access Addresses: %s, %s", hostv4, hostv6) 1090 1091 return hostv4, hostv6 1092 } 1093 1094 func checkInstanceFloatingIPs(d *schema.ResourceData) error { 1095 rawNetworks := d.Get("network").([]interface{}) 1096 floatingIP := d.Get("floating_ip").(string) 1097 1098 for _, raw := range rawNetworks { 1099 if raw == nil { 1100 continue 1101 } 1102 1103 rawMap := raw.(map[string]interface{}) 1104 1105 // Error if a floating IP was specified both globally and in the network block. 1106 if floatingIP != "" && rawMap["floating_ip"] != "" { 1107 return fmt.Errorf("Cannot specify a floating IP both globally and in a network block.") 1108 } 1109 } 1110 return nil 1111 } 1112 1113 func associateFloatingIPsToInstance(computeClient *gophercloud.ServiceClient, d *schema.ResourceData) error { 1114 floatingIP := d.Get("floating_ip").(string) 1115 rawNetworks := d.Get("network").([]interface{}) 1116 instanceID := d.Id() 1117 1118 if floatingIP != "" { 1119 if err := associateFloatingIPToInstance(computeClient, floatingIP, instanceID, ""); err != nil { 1120 return err 1121 } 1122 } else { 1123 for _, raw := range rawNetworks { 1124 if raw == nil { 1125 continue 1126 } 1127 1128 rawMap := raw.(map[string]interface{}) 1129 if rawMap["floating_ip"].(string) != "" { 1130 floatingIP := rawMap["floating_ip"].(string) 1131 fixedIP := rawMap["fixed_ip_v4"].(string) 1132 if err := associateFloatingIPToInstance(computeClient, floatingIP, instanceID, fixedIP); err != nil { 1133 return err 1134 } 1135 } 1136 } 1137 } 1138 return nil 1139 } 1140 1141 func associateFloatingIPToInstance(computeClient *gophercloud.ServiceClient, floatingIP string, instanceID string, fixedIP string) error { 1142 associateOpts := floatingips.AssociateOpts{ 1143 FloatingIP: floatingIP, 1144 FixedIP: fixedIP, 1145 } 1146 1147 if err := floatingips.AssociateInstance(computeClient, instanceID, associateOpts).ExtractErr(); err != nil { 1148 return fmt.Errorf("Error associating floating IP: %s", err) 1149 } 1150 1151 return nil 1152 } 1153 1154 func disassociateFloatingIPFromInstance(computeClient *gophercloud.ServiceClient, floatingIP string, instanceID string, fixedIP string) error { 1155 disassociateOpts := floatingips.DisassociateOpts{ 1156 FloatingIP: floatingIP, 1157 } 1158 1159 if err := floatingips.DisassociateInstance(computeClient, instanceID, disassociateOpts).ExtractErr(); err != nil { 1160 return fmt.Errorf("Error disassociating floating IP: %s", err) 1161 } 1162 1163 return nil 1164 } 1165 1166 func resourceInstanceMetadataV2(d *schema.ResourceData) map[string]string { 1167 m := make(map[string]string) 1168 for key, val := range d.Get("metadata").(map[string]interface{}) { 1169 m[key] = val.(string) 1170 } 1171 return m 1172 } 1173 1174 func resourceInstanceBlockDevicesV2(d *schema.ResourceData, bds []interface{}) ([]bootfromvolume.BlockDevice, error) { 1175 blockDeviceOpts := make([]bootfromvolume.BlockDevice, len(bds)) 1176 for i, bd := range bds { 1177 bdM := bd.(map[string]interface{}) 1178 blockDeviceOpts[i] = bootfromvolume.BlockDevice{ 1179 UUID: bdM["uuid"].(string), 1180 VolumeSize: bdM["volume_size"].(int), 1181 BootIndex: bdM["boot_index"].(int), 1182 DeleteOnTermination: bdM["delete_on_termination"].(bool), 1183 GuestFormat: bdM["guest_format"].(string), 1184 } 1185 1186 sourceType := bdM["source_type"].(string) 1187 switch sourceType { 1188 case "blank": 1189 blockDeviceOpts[i].SourceType = bootfromvolume.SourceBlank 1190 case "image": 1191 blockDeviceOpts[i].SourceType = bootfromvolume.SourceImage 1192 case "snapshot": 1193 blockDeviceOpts[i].SourceType = bootfromvolume.SourceSnapshot 1194 case "volume": 1195 blockDeviceOpts[i].SourceType = bootfromvolume.SourceVolume 1196 default: 1197 return blockDeviceOpts, fmt.Errorf("unknown block device source type %s", sourceType) 1198 } 1199 1200 destinationType := bdM["destination_type"].(string) 1201 switch destinationType { 1202 case "local": 1203 blockDeviceOpts[i].DestinationType = bootfromvolume.DestinationLocal 1204 case "volume": 1205 blockDeviceOpts[i].DestinationType = bootfromvolume.DestinationVolume 1206 default: 1207 return blockDeviceOpts, fmt.Errorf("unknown block device destination type %s", destinationType) 1208 } 1209 } 1210 1211 log.Printf("[DEBUG] Block Device Options: %+v", blockDeviceOpts) 1212 return blockDeviceOpts, nil 1213 } 1214 1215 func resourceInstanceSchedulerHintsV2(d *schema.ResourceData, schedulerHintsRaw map[string]interface{}) schedulerhints.SchedulerHints { 1216 differentHost := []string{} 1217 if len(schedulerHintsRaw["different_host"].([]interface{})) > 0 { 1218 for _, dh := range schedulerHintsRaw["different_host"].([]interface{}) { 1219 differentHost = append(differentHost, dh.(string)) 1220 } 1221 } 1222 1223 sameHost := []string{} 1224 if len(schedulerHintsRaw["same_host"].([]interface{})) > 0 { 1225 for _, sh := range schedulerHintsRaw["same_host"].([]interface{}) { 1226 sameHost = append(sameHost, sh.(string)) 1227 } 1228 } 1229 1230 query := make([]interface{}, len(schedulerHintsRaw["query"].([]interface{}))) 1231 if len(schedulerHintsRaw["query"].([]interface{})) > 0 { 1232 for _, q := range schedulerHintsRaw["query"].([]interface{}) { 1233 query = append(query, q.(string)) 1234 } 1235 } 1236 1237 schedulerHints := schedulerhints.SchedulerHints{ 1238 Group: schedulerHintsRaw["group"].(string), 1239 DifferentHost: differentHost, 1240 SameHost: sameHost, 1241 Query: query, 1242 TargetCell: schedulerHintsRaw["target_cell"].(string), 1243 BuildNearHostIP: schedulerHintsRaw["build_near_host_ip"].(string), 1244 } 1245 1246 return schedulerHints 1247 } 1248 1249 func getImageIDFromConfig(computeClient *gophercloud.ServiceClient, d *schema.ResourceData) (string, error) { 1250 // If block_device was used, an Image does not need to be specified, unless an image/local 1251 // combination was used. This emulates normal boot behavior. Otherwise, ignore the image altogether. 1252 if vL, ok := d.GetOk("block_device"); ok { 1253 needImage := false 1254 for _, v := range vL.([]interface{}) { 1255 vM := v.(map[string]interface{}) 1256 if vM["source_type"] == "image" && vM["destination_type"] == "local" { 1257 needImage = true 1258 } 1259 } 1260 if !needImage { 1261 return "", nil 1262 } 1263 } 1264 1265 if imageId := d.Get("image_id").(string); imageId != "" { 1266 return imageId, nil 1267 } else { 1268 // try the OS_IMAGE_ID environment variable 1269 if v := os.Getenv("OS_IMAGE_ID"); v != "" { 1270 return v, nil 1271 } 1272 } 1273 1274 imageName := d.Get("image_name").(string) 1275 if imageName == "" { 1276 // try the OS_IMAGE_NAME environment variable 1277 if v := os.Getenv("OS_IMAGE_NAME"); v != "" { 1278 imageName = v 1279 } 1280 } 1281 1282 if imageName != "" { 1283 imageId, err := images.IDFromName(computeClient, imageName) 1284 if err != nil { 1285 return "", err 1286 } 1287 return imageId, nil 1288 } 1289 1290 return "", fmt.Errorf("Neither a boot device, image ID, or image name were able to be determined.") 1291 } 1292 1293 func setImageInformation(computeClient *gophercloud.ServiceClient, server *servers.Server, d *schema.ResourceData) error { 1294 // If block_device was used, an Image does not need to be specified, unless an image/local 1295 // combination was used. This emulates normal boot behavior. Otherwise, ignore the image altogether. 1296 if vL, ok := d.GetOk("block_device"); ok { 1297 needImage := false 1298 for _, v := range vL.([]interface{}) { 1299 vM := v.(map[string]interface{}) 1300 if vM["source_type"] == "image" && vM["destination_type"] == "local" { 1301 needImage = true 1302 } 1303 } 1304 if !needImage { 1305 d.Set("image_id", "Attempt to boot from volume - no image supplied") 1306 return nil 1307 } 1308 } 1309 1310 imageId := server.Image["id"].(string) 1311 if imageId != "" { 1312 d.Set("image_id", imageId) 1313 if image, err := images.Get(computeClient, imageId).Extract(); err != nil { 1314 if _, ok := err.(gophercloud.ErrDefault404); ok { 1315 // If the image name can't be found, set the value to "Image not found". 1316 // The most likely scenario is that the image no longer exists in the Image Service 1317 // but the instance still has a record from when it existed. 1318 d.Set("image_name", "Image not found") 1319 return nil 1320 } 1321 return err 1322 } else { 1323 d.Set("image_name", image.Name) 1324 } 1325 } 1326 1327 return nil 1328 } 1329 1330 func getFlavorID(client *gophercloud.ServiceClient, d *schema.ResourceData) (string, error) { 1331 flavorId := d.Get("flavor_id").(string) 1332 1333 if flavorId != "" { 1334 return flavorId, nil 1335 } 1336 1337 flavorName := d.Get("flavor_name").(string) 1338 return flavors.IDFromName(client, flavorName) 1339 } 1340 1341 func resourceComputeVolumeAttachmentHash(v interface{}) int { 1342 var buf bytes.Buffer 1343 m := v.(map[string]interface{}) 1344 buf.WriteString(fmt.Sprintf("%s-", m["volume_id"].(string))) 1345 1346 return hashcode.String(buf.String()) 1347 } 1348 1349 func resourceComputeSchedulerHintsHash(v interface{}) int { 1350 var buf bytes.Buffer 1351 m := v.(map[string]interface{}) 1352 1353 if m["group"] != nil { 1354 buf.WriteString(fmt.Sprintf("%s-", m["group"].(string))) 1355 } 1356 1357 if m["target_cell"] != nil { 1358 buf.WriteString(fmt.Sprintf("%s-", m["target_cell"].(string))) 1359 } 1360 1361 if m["build_host_near_ip"] != nil { 1362 buf.WriteString(fmt.Sprintf("%s-", m["build_host_near_ip"].(string))) 1363 } 1364 1365 buf.WriteString(fmt.Sprintf("%s-", m["different_host"].([]interface{}))) 1366 buf.WriteString(fmt.Sprintf("%s-", m["same_host"].([]interface{}))) 1367 buf.WriteString(fmt.Sprintf("%s-", m["query"].([]interface{}))) 1368 1369 return hashcode.String(buf.String()) 1370 } 1371 1372 func attachVolumesToInstance(computeClient *gophercloud.ServiceClient, blockClient *gophercloud.ServiceClient, serverId string, vols []interface{}) error { 1373 for _, v := range vols { 1374 va := v.(map[string]interface{}) 1375 volumeId := va["volume_id"].(string) 1376 device := va["device"].(string) 1377 1378 s := "" 1379 if serverId != "" { 1380 s = serverId 1381 } else if va["server_id"] != "" { 1382 s = va["server_id"].(string) 1383 } else { 1384 return fmt.Errorf("Unable to determine server ID to attach volume.") 1385 } 1386 1387 vaOpts := &volumeattach.CreateOpts{ 1388 Device: device, 1389 VolumeID: volumeId, 1390 } 1391 1392 if _, err := volumeattach.Create(computeClient, s, vaOpts).Extract(); err != nil { 1393 return err 1394 } 1395 1396 stateConf := &resource.StateChangeConf{ 1397 Pending: []string{"attaching", "available"}, 1398 Target: []string{"in-use"}, 1399 Refresh: VolumeV1StateRefreshFunc(blockClient, va["volume_id"].(string)), 1400 Timeout: 30 * time.Minute, 1401 Delay: 5 * time.Second, 1402 MinTimeout: 2 * time.Second, 1403 } 1404 1405 if _, err := stateConf.WaitForState(); err != nil { 1406 return err 1407 } 1408 1409 log.Printf("[INFO] Attached volume %s to instance %s", volumeId, serverId) 1410 } 1411 return nil 1412 } 1413 1414 func detachVolumesFromInstance(computeClient *gophercloud.ServiceClient, blockClient *gophercloud.ServiceClient, serverId string, vols []interface{}) error { 1415 for _, v := range vols { 1416 va := v.(map[string]interface{}) 1417 aId := va["id"].(string) 1418 1419 log.Printf("[INFO] Attempting to detach volume %s", va["volume_id"]) 1420 if err := volumeattach.Delete(computeClient, serverId, aId).ExtractErr(); err != nil { 1421 return err 1422 } 1423 1424 stateConf := &resource.StateChangeConf{ 1425 Pending: []string{"detaching", "in-use"}, 1426 Target: []string{"available"}, 1427 Refresh: VolumeV1StateRefreshFunc(blockClient, va["volume_id"].(string)), 1428 Timeout: 30 * time.Minute, 1429 Delay: 5 * time.Second, 1430 MinTimeout: 2 * time.Second, 1431 } 1432 1433 if _, err := stateConf.WaitForState(); err != nil { 1434 return err 1435 } 1436 log.Printf("[INFO] Detached volume %s from instance %s", va["volume_id"], serverId) 1437 } 1438 1439 return nil 1440 } 1441 1442 func getVolumeAttachments(computeClient *gophercloud.ServiceClient, d *schema.ResourceData) error { 1443 var vols []map[string]interface{} 1444 1445 allPages, err := volumeattach.List(computeClient, d.Id()).AllPages() 1446 if err != nil { 1447 return err 1448 } 1449 1450 allVolumeAttachments, err := volumeattach.ExtractVolumeAttachments(allPages) 1451 if err != nil { 1452 return err 1453 } 1454 1455 if v, ok := d.GetOk("volume"); ok { 1456 volumes := v.(*schema.Set).List() 1457 for _, volume := range volumes { 1458 if volumeMap, ok := volume.(map[string]interface{}); ok { 1459 if v, ok := volumeMap["volume_id"].(string); ok { 1460 for _, volumeAttachment := range allVolumeAttachments { 1461 if v == volumeAttachment.ID { 1462 vol := make(map[string]interface{}) 1463 vol["id"] = volumeAttachment.ID 1464 vol["volume_id"] = volumeAttachment.VolumeID 1465 vol["device"] = volumeAttachment.Device 1466 vols = append(vols, vol) 1467 } 1468 } 1469 } 1470 } 1471 } 1472 } 1473 1474 log.Printf("[INFO] Volume attachments: %v", vols) 1475 d.Set("volume", vols) 1476 1477 return nil 1478 } 1479 1480 func checkBlockDeviceConfig(d *schema.ResourceData) error { 1481 if vL, ok := d.GetOk("block_device"); ok { 1482 for _, v := range vL.([]interface{}) { 1483 vM := v.(map[string]interface{}) 1484 1485 if vM["source_type"] != "blank" && vM["uuid"] == "" { 1486 return fmt.Errorf("You must specify a uuid for %s block device types", vM["source_type"]) 1487 } 1488 1489 if vM["source_type"] == "image" && vM["destination_type"] == "volume" { 1490 if vM["volume_size"] == 0 { 1491 return fmt.Errorf("You must specify a volume_size when creating a volume from an image") 1492 } 1493 } 1494 1495 if vM["source_type"] == "blank" && vM["destination_type"] == "local" { 1496 if vM["volume_size"] == 0 { 1497 return fmt.Errorf("You must specify a volume_size when creating a blank block device") 1498 } 1499 } 1500 } 1501 } 1502 1503 return nil 1504 } 1505 1506 func resourceComputeInstancePersonalityHash(v interface{}) int { 1507 var buf bytes.Buffer 1508 m := v.(map[string]interface{}) 1509 buf.WriteString(fmt.Sprintf("%s-", m["file"].(string))) 1510 1511 return hashcode.String(buf.String()) 1512 } 1513 1514 func resourceInstancePersonalityV2(d *schema.ResourceData) servers.Personality { 1515 var personalities servers.Personality 1516 1517 if v := d.Get("personality"); v != nil { 1518 personalityList := v.(*schema.Set).List() 1519 if len(personalityList) > 0 { 1520 for _, p := range personalityList { 1521 rawPersonality := p.(map[string]interface{}) 1522 file := servers.File{ 1523 Path: rawPersonality["file"].(string), 1524 Contents: []byte(rawPersonality["content"].(string)), 1525 } 1526 1527 log.Printf("[DEBUG] OpenStack Compute Instance Personality: %+v", file) 1528 1529 personalities = append(personalities, &file) 1530 } 1531 } 1532 } 1533 1534 return personalities 1535 }