github.com/bendemaree/terraform@v0.5.4-0.20150613200311-f50d97d6eee6/builtin/providers/cloudstack/resource_cloudstack_instance.go (about)

     1  package cloudstack
     2  
     3  import (
     4  	"crypto/sha1"
     5  	"encoding/base64"
     6  	"encoding/hex"
     7  	"fmt"
     8  	"log"
     9  	"strings"
    10  
    11  	"github.com/hashicorp/terraform/helper/schema"
    12  	"github.com/xanzy/go-cloudstack/cloudstack"
    13  )
    14  
    15  func resourceCloudStackInstance() *schema.Resource {
    16  	return &schema.Resource{
    17  		Create: resourceCloudStackInstanceCreate,
    18  		Read:   resourceCloudStackInstanceRead,
    19  		Update: resourceCloudStackInstanceUpdate,
    20  		Delete: resourceCloudStackInstanceDelete,
    21  
    22  		Schema: map[string]*schema.Schema{
    23  			"name": &schema.Schema{
    24  				Type:     schema.TypeString,
    25  				Required: true,
    26  				ForceNew: true,
    27  			},
    28  
    29  			"display_name": &schema.Schema{
    30  				Type:     schema.TypeString,
    31  				Optional: true,
    32  				Computed: true,
    33  			},
    34  
    35  			"service_offering": &schema.Schema{
    36  				Type:     schema.TypeString,
    37  				Required: true,
    38  			},
    39  
    40  			"network": &schema.Schema{
    41  				Type:     schema.TypeString,
    42  				Optional: true,
    43  				ForceNew: true,
    44  			},
    45  
    46  			"ipaddress": &schema.Schema{
    47  				Type:     schema.TypeString,
    48  				Optional: true,
    49  				Computed: true,
    50  				ForceNew: true,
    51  			},
    52  
    53  			"template": &schema.Schema{
    54  				Type:     schema.TypeString,
    55  				Required: true,
    56  				ForceNew: true,
    57  			},
    58  
    59  			"project": &schema.Schema{
    60  				Type:     schema.TypeString,
    61  				Optional: true,
    62  				ForceNew: true,
    63  			},
    64  
    65  			"zone": &schema.Schema{
    66  				Type:     schema.TypeString,
    67  				Required: true,
    68  				ForceNew: true,
    69  			},
    70  
    71  			"keypair": &schema.Schema{
    72  				Type:     schema.TypeString,
    73  				Optional: true,
    74  			},
    75  
    76  			"user_data": &schema.Schema{
    77  				Type:     schema.TypeString,
    78  				Optional: true,
    79  				ForceNew: true,
    80  				StateFunc: func(v interface{}) string {
    81  					switch v.(type) {
    82  					case string:
    83  						hash := sha1.Sum([]byte(v.(string)))
    84  						return hex.EncodeToString(hash[:])
    85  					default:
    86  						return ""
    87  					}
    88  				},
    89  			},
    90  
    91  			"expunge": &schema.Schema{
    92  				Type:     schema.TypeBool,
    93  				Optional: true,
    94  				Default:  false,
    95  			},
    96  		},
    97  	}
    98  }
    99  
   100  func resourceCloudStackInstanceCreate(d *schema.ResourceData, meta interface{}) error {
   101  	cs := meta.(*cloudstack.CloudStackClient)
   102  
   103  	// Retrieve the service_offering UUID
   104  	serviceofferingid, e := retrieveUUID(cs, "service_offering", d.Get("service_offering").(string))
   105  	if e != nil {
   106  		return e.Error()
   107  	}
   108  
   109  	// Retrieve the zone object
   110  	zone, _, err := cs.Zone.GetZoneByName(d.Get("zone").(string))
   111  	if err != nil {
   112  		return err
   113  	}
   114  
   115  	// Retrieve the template UUID
   116  	templateid, e := retrieveTemplateUUID(cs, zone.Id, d.Get("template").(string))
   117  	if e != nil {
   118  		return e.Error()
   119  	}
   120  
   121  	// Create a new parameter struct
   122  	p := cs.VirtualMachine.NewDeployVirtualMachineParams(serviceofferingid, templateid, zone.Id)
   123  
   124  	// Set the name
   125  	name := d.Get("name").(string)
   126  	p.SetName(name)
   127  
   128  	// Set the display name
   129  	if displayname, ok := d.GetOk("display_name"); ok {
   130  		p.SetDisplayname(displayname.(string))
   131  	} else {
   132  		p.SetDisplayname(name)
   133  	}
   134  
   135  	if zone.Networktype == "Advanced" {
   136  		// Retrieve the network UUID
   137  		networkid, e := retrieveUUID(cs, "network", d.Get("network").(string))
   138  		if e != nil {
   139  			return e.Error()
   140  		}
   141  		// Set the default network ID
   142  		p.SetNetworkids([]string{networkid})
   143  	}
   144  
   145  	// If there is a ipaddres supplied, add it to the parameter struct
   146  	if ipaddres, ok := d.GetOk("ipaddress"); ok {
   147  		p.SetIpaddress(ipaddres.(string))
   148  	}
   149  
   150  	// If there is a project supplied, we retreive and set the project id
   151  	if project, ok := d.GetOk("project"); ok {
   152  		// Retrieve the project UUID
   153  		projectid, e := retrieveUUID(cs, "project", project.(string))
   154  		if e != nil {
   155  			return e.Error()
   156  		}
   157  		// Set the default project ID
   158  		p.SetProjectid(projectid)
   159  	}
   160  
   161  	// If a keypair is supplied, add it to the parameter struct
   162  	if keypair, ok := d.GetOk("keypair"); ok {
   163  		p.SetKeypair(keypair.(string))
   164  	}
   165  
   166  	// If the user data contains any info, it needs to be base64 encoded and
   167  	// added to the parameter struct
   168  	if userData, ok := d.GetOk("user_data"); ok {
   169  		ud := base64.StdEncoding.EncodeToString([]byte(userData.(string)))
   170  		if len(ud) > 2048 {
   171  			return fmt.Errorf(
   172  				"The supplied user_data contains %d bytes after encoding, "+
   173  					"this exeeds the limit of 2048 bytes", len(ud))
   174  		}
   175  		p.SetUserdata(ud)
   176  	}
   177  
   178  	// Create the new instance
   179  	r, err := cs.VirtualMachine.DeployVirtualMachine(p)
   180  	if err != nil {
   181  		return fmt.Errorf("Error creating the new instance %s: %s", name, err)
   182  	}
   183  
   184  	d.SetId(r.Id)
   185  
   186  	// Set the connection info for any configured provisioners
   187  	d.SetConnInfo(map[string]string{
   188  		"host":     r.Nic[0].Ipaddress,
   189  		"password": r.Password,
   190  	})
   191  
   192  	return resourceCloudStackInstanceRead(d, meta)
   193  }
   194  
   195  func resourceCloudStackInstanceRead(d *schema.ResourceData, meta interface{}) error {
   196  	cs := meta.(*cloudstack.CloudStackClient)
   197  
   198  	// Get the virtual machine details
   199  	vm, count, err := cs.VirtualMachine.GetVirtualMachineByID(d.Id())
   200  	if err != nil {
   201  		if count == 0 {
   202  			log.Printf("[DEBUG] Instance %s does no longer exist", d.Get("name").(string))
   203  			// Clear out all details so it's obvious the instance is gone
   204  			d.SetId("")
   205  			return nil
   206  		}
   207  
   208  		return err
   209  	}
   210  
   211  	// Update the config
   212  	d.Set("name", vm.Name)
   213  	d.Set("display_name", vm.Displayname)
   214  	d.Set("ipaddress", vm.Nic[0].Ipaddress)
   215  	d.Set("zone", vm.Zonename)
   216  	//NB cloudstack sometimes sends back the wrong keypair name, so dont update it
   217  
   218  	setValueOrUUID(d, "network", vm.Nic[0].Networkname, vm.Nic[0].Networkid)
   219  	setValueOrUUID(d, "service_offering", vm.Serviceofferingname, vm.Serviceofferingid)
   220  	setValueOrUUID(d, "template", vm.Templatename, vm.Templateid)
   221  	setValueOrUUID(d, "project", vm.Project, vm.Projectid)
   222  
   223  	return nil
   224  }
   225  
   226  func resourceCloudStackInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
   227  	cs := meta.(*cloudstack.CloudStackClient)
   228  	d.Partial(true)
   229  
   230  	name := d.Get("name").(string)
   231  
   232  	// Check if the display name is changed and if so, update the virtual machine
   233  	if d.HasChange("display_name") {
   234  		log.Printf("[DEBUG] Display name changed for %s, starting update", name)
   235  
   236  		// Create a new parameter struct
   237  		p := cs.VirtualMachine.NewUpdateVirtualMachineParams(d.Id())
   238  
   239  		// Set the new display name
   240  		p.SetDisplayname(d.Get("display_name").(string))
   241  
   242  		// Update the display name
   243  		_, err := cs.VirtualMachine.UpdateVirtualMachine(p)
   244  		if err != nil {
   245  			return fmt.Errorf(
   246  				"Error updating the display name for instance %s: %s", name, err)
   247  		}
   248  
   249  		d.SetPartial("display_name")
   250  	}
   251  
   252  	// Attributes that require reboot to update
   253  	if d.HasChange("service_offering") || d.HasChange("keypair") {
   254  		// Before we can actually make these changes, the virtual machine must be stopped
   255  		_, err := cs.VirtualMachine.StopVirtualMachine(cs.VirtualMachine.NewStopVirtualMachineParams(d.Id()))
   256  		if err != nil {
   257  			return fmt.Errorf(
   258  				"Error stopping instance %s before making changes: %s", name, err)
   259  		}
   260  
   261  		// Check if the service offering is changed and if so, update the offering
   262  		if d.HasChange("service_offering") {
   263  			log.Printf("[DEBUG] Service offering changed for %s, starting update", name)
   264  
   265  			// Retrieve the service_offering UUID
   266  			serviceofferingid, e := retrieveUUID(cs, "service_offering", d.Get("service_offering").(string))
   267  			if e != nil {
   268  				return e.Error()
   269  			}
   270  
   271  			// Create a new parameter struct
   272  			p := cs.VirtualMachine.NewChangeServiceForVirtualMachineParams(d.Id(), serviceofferingid)
   273  
   274  			// Change the service offering
   275  			_, err = cs.VirtualMachine.ChangeServiceForVirtualMachine(p)
   276  			if err != nil {
   277  				return fmt.Errorf(
   278  					"Error changing the service offering for instance %s: %s", name, err)
   279  			}
   280  			d.SetPartial("service_offering")
   281  		}
   282  
   283  		if d.HasChange("keypair") {
   284  			log.Printf("[DEBUG] SSH keypair changed for %s, starting update", name)
   285  
   286  			p := cs.SSH.NewResetSSHKeyForVirtualMachineParams(d.Id(), d.Get("keypair").(string))
   287  
   288  			// Change the ssh keypair
   289  			_, err = cs.SSH.ResetSSHKeyForVirtualMachine(p)
   290  			if err != nil {
   291  				return fmt.Errorf(
   292  					"Error changing the SSH keypair for instance %s: %s", name, err)
   293  			}
   294  			d.SetPartial("keypair")
   295  		}
   296  
   297  		// Start the virtual machine again
   298  		_, err = cs.VirtualMachine.StartVirtualMachine(cs.VirtualMachine.NewStartVirtualMachineParams(d.Id()))
   299  		if err != nil {
   300  			return fmt.Errorf(
   301  				"Error starting instance %s after making changes", name)
   302  		}
   303  	}
   304  	d.Partial(false)
   305  	return resourceCloudStackInstanceRead(d, meta)
   306  }
   307  
   308  func resourceCloudStackInstanceDelete(d *schema.ResourceData, meta interface{}) error {
   309  	cs := meta.(*cloudstack.CloudStackClient)
   310  
   311  	// Create a new parameter struct
   312  	p := cs.VirtualMachine.NewDestroyVirtualMachineParams(d.Id())
   313  
   314  	if d.Get("expunge").(bool) {
   315  		p.SetExpunge(true)
   316  	}
   317  
   318  	log.Printf("[INFO] Destroying instance: %s", d.Get("name").(string))
   319  	if _, err := cs.VirtualMachine.DestroyVirtualMachine(p); err != nil {
   320  		// This is a very poor way to be told the UUID does no longer exist :(
   321  		if strings.Contains(err.Error(), fmt.Sprintf(
   322  			"Invalid parameter id value=%s due to incorrect long value format, "+
   323  				"or entity does not exist", d.Id())) {
   324  			return nil
   325  		}
   326  
   327  		return fmt.Errorf("Error destroying instance: %s", err)
   328  	}
   329  
   330  	return nil
   331  }