github.com/turtlemonvh/terraform@v0.6.9-0.20151204001754-8e40b6b855e8/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 ID
   104  	serviceofferingid, e := retrieveID(cs, "service_offering", d.Get("service_offering").(string))
   105  	if e != nil {
   106  		return e.Error()
   107  	}
   108  
   109  	// Retrieve the zone ID
   110  	zoneid, e := retrieveID(cs, "zone", d.Get("zone").(string))
   111  	if e != nil {
   112  		return e.Error()
   113  	}
   114  
   115  	// Retrieve the zone object
   116  	zone, _, err := cs.Zone.GetZoneByID(zoneid)
   117  	if err != nil {
   118  		return err
   119  	}
   120  
   121  	// Retrieve the template ID
   122  	templateid, e := retrieveTemplateID(cs, zone.Id, d.Get("template").(string))
   123  	if e != nil {
   124  		return e.Error()
   125  	}
   126  
   127  	// Create a new parameter struct
   128  	p := cs.VirtualMachine.NewDeployVirtualMachineParams(serviceofferingid, templateid, zone.Id)
   129  
   130  	// Set the name
   131  	name := d.Get("name").(string)
   132  	p.SetName(name)
   133  
   134  	// Set the display name
   135  	if displayname, ok := d.GetOk("display_name"); ok {
   136  		p.SetDisplayname(displayname.(string))
   137  	} else {
   138  		p.SetDisplayname(name)
   139  	}
   140  
   141  	if zone.Networktype == "Advanced" {
   142  		// Retrieve the network ID
   143  		networkid, e := retrieveID(cs, "network", d.Get("network").(string))
   144  		if e != nil {
   145  			return e.Error()
   146  		}
   147  		// Set the default network ID
   148  		p.SetNetworkids([]string{networkid})
   149  	}
   150  
   151  	// If there is a ipaddres supplied, add it to the parameter struct
   152  	if ipaddres, ok := d.GetOk("ipaddress"); ok {
   153  		p.SetIpaddress(ipaddres.(string))
   154  	}
   155  
   156  	// If there is a project supplied, we retrieve and set the project id
   157  	if project, ok := d.GetOk("project"); ok {
   158  		// Retrieve the project ID
   159  		projectid, e := retrieveID(cs, "project", project.(string))
   160  		if e != nil {
   161  			return e.Error()
   162  		}
   163  		// Set the default project ID
   164  		p.SetProjectid(projectid)
   165  	}
   166  
   167  	// If a keypair is supplied, add it to the parameter struct
   168  	if keypair, ok := d.GetOk("keypair"); ok {
   169  		p.SetKeypair(keypair.(string))
   170  	}
   171  
   172  	// If the user data contains any info, it needs to be base64 encoded and
   173  	// added to the parameter struct
   174  	if userData, ok := d.GetOk("user_data"); ok {
   175  		ud := base64.StdEncoding.EncodeToString([]byte(userData.(string)))
   176  
   177  		// deployVirtualMachine uses POST by default, so max userdata is 32K
   178  		maxUD := 32768
   179  
   180  		if cs.HTTPGETOnly {
   181  			// deployVirtualMachine using GET instead, so max userdata is 2K
   182  			maxUD = 2048
   183  		}
   184  
   185  		if len(ud) > maxUD {
   186  			return fmt.Errorf(
   187  				"The supplied user_data contains %d bytes after encoding, "+
   188  					"this exeeds the limit of %d bytes", len(ud), maxUD)
   189  		}
   190  
   191  		p.SetUserdata(ud)
   192  	}
   193  
   194  	// Create the new instance
   195  	r, err := cs.VirtualMachine.DeployVirtualMachine(p)
   196  	if err != nil {
   197  		return fmt.Errorf("Error creating the new instance %s: %s", name, err)
   198  	}
   199  
   200  	d.SetId(r.Id)
   201  
   202  	// Set the connection info for any configured provisioners
   203  	d.SetConnInfo(map[string]string{
   204  		"host":     r.Nic[0].Ipaddress,
   205  		"password": r.Password,
   206  	})
   207  
   208  	return resourceCloudStackInstanceRead(d, meta)
   209  }
   210  
   211  func resourceCloudStackInstanceRead(d *schema.ResourceData, meta interface{}) error {
   212  	cs := meta.(*cloudstack.CloudStackClient)
   213  
   214  	// Get the virtual machine details
   215  	vm, count, err := cs.VirtualMachine.GetVirtualMachineByID(d.Id())
   216  	if err != nil {
   217  		if count == 0 {
   218  			log.Printf("[DEBUG] Instance %s does no longer exist", d.Get("name").(string))
   219  			d.SetId("")
   220  			return nil
   221  		}
   222  
   223  		return err
   224  	}
   225  
   226  	// Update the config
   227  	d.Set("name", vm.Name)
   228  	d.Set("display_name", vm.Displayname)
   229  	d.Set("ipaddress", vm.Nic[0].Ipaddress)
   230  	//NB cloudstack sometimes sends back the wrong keypair name, so dont update it
   231  
   232  	setValueOrID(d, "network", vm.Nic[0].Networkname, vm.Nic[0].Networkid)
   233  	setValueOrID(d, "service_offering", vm.Serviceofferingname, vm.Serviceofferingid)
   234  	setValueOrID(d, "template", vm.Templatename, vm.Templateid)
   235  	setValueOrID(d, "project", vm.Project, vm.Projectid)
   236  	setValueOrID(d, "zone", vm.Zonename, vm.Zoneid)
   237  
   238  	return nil
   239  }
   240  
   241  func resourceCloudStackInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
   242  	cs := meta.(*cloudstack.CloudStackClient)
   243  	d.Partial(true)
   244  
   245  	name := d.Get("name").(string)
   246  
   247  	// Check if the display name is changed and if so, update the virtual machine
   248  	if d.HasChange("display_name") {
   249  		log.Printf("[DEBUG] Display name changed for %s, starting update", name)
   250  
   251  		// Create a new parameter struct
   252  		p := cs.VirtualMachine.NewUpdateVirtualMachineParams(d.Id())
   253  
   254  		// Set the new display name
   255  		p.SetDisplayname(d.Get("display_name").(string))
   256  
   257  		// Update the display name
   258  		_, err := cs.VirtualMachine.UpdateVirtualMachine(p)
   259  		if err != nil {
   260  			return fmt.Errorf(
   261  				"Error updating the display name for instance %s: %s", name, err)
   262  		}
   263  
   264  		d.SetPartial("display_name")
   265  	}
   266  
   267  	// Attributes that require reboot to update
   268  	if d.HasChange("service_offering") || d.HasChange("keypair") {
   269  		// Before we can actually make these changes, the virtual machine must be stopped
   270  		_, err := cs.VirtualMachine.StopVirtualMachine(
   271  			cs.VirtualMachine.NewStopVirtualMachineParams(d.Id()))
   272  		if err != nil {
   273  			return fmt.Errorf(
   274  				"Error stopping instance %s before making changes: %s", name, err)
   275  		}
   276  
   277  		// Check if the service offering is changed and if so, update the offering
   278  		if d.HasChange("service_offering") {
   279  			log.Printf("[DEBUG] Service offering changed for %s, starting update", name)
   280  
   281  			// Retrieve the service_offering ID
   282  			serviceofferingid, e := retrieveID(cs, "service_offering", d.Get("service_offering").(string))
   283  			if e != nil {
   284  				return e.Error()
   285  			}
   286  
   287  			// Create a new parameter struct
   288  			p := cs.VirtualMachine.NewChangeServiceForVirtualMachineParams(d.Id(), serviceofferingid)
   289  
   290  			// Change the service offering
   291  			_, err = cs.VirtualMachine.ChangeServiceForVirtualMachine(p)
   292  			if err != nil {
   293  				return fmt.Errorf(
   294  					"Error changing the service offering for instance %s: %s", name, err)
   295  			}
   296  			d.SetPartial("service_offering")
   297  		}
   298  
   299  		if d.HasChange("keypair") {
   300  			log.Printf("[DEBUG] SSH keypair changed for %s, starting update", name)
   301  
   302  			p := cs.SSH.NewResetSSHKeyForVirtualMachineParams(d.Id(), d.Get("keypair").(string))
   303  
   304  			// Change the ssh keypair
   305  			_, err = cs.SSH.ResetSSHKeyForVirtualMachine(p)
   306  			if err != nil {
   307  				return fmt.Errorf(
   308  					"Error changing the SSH keypair for instance %s: %s", name, err)
   309  			}
   310  			d.SetPartial("keypair")
   311  		}
   312  
   313  		// Start the virtual machine again
   314  		_, err = cs.VirtualMachine.StartVirtualMachine(
   315  			cs.VirtualMachine.NewStartVirtualMachineParams(d.Id()))
   316  		if err != nil {
   317  			return fmt.Errorf(
   318  				"Error starting instance %s after making changes", name)
   319  		}
   320  	}
   321  
   322  	d.Partial(false)
   323  	return resourceCloudStackInstanceRead(d, meta)
   324  }
   325  
   326  func resourceCloudStackInstanceDelete(d *schema.ResourceData, meta interface{}) error {
   327  	cs := meta.(*cloudstack.CloudStackClient)
   328  
   329  	// Create a new parameter struct
   330  	p := cs.VirtualMachine.NewDestroyVirtualMachineParams(d.Id())
   331  
   332  	if d.Get("expunge").(bool) {
   333  		p.SetExpunge(true)
   334  	}
   335  
   336  	log.Printf("[INFO] Destroying instance: %s", d.Get("name").(string))
   337  	if _, err := cs.VirtualMachine.DestroyVirtualMachine(p); err != nil {
   338  		// This is a very poor way to be told the ID does no longer exist :(
   339  		if strings.Contains(err.Error(), fmt.Sprintf(
   340  			"Invalid parameter id value=%s due to incorrect long value format, "+
   341  				"or entity does not exist", d.Id())) {
   342  			return nil
   343  		}
   344  
   345  		return fmt.Errorf("Error destroying instance: %s", err)
   346  	}
   347  
   348  	return nil
   349  }