github.com/shvar/terraform@v0.6.9-0.20151215234924-3365cd2231df/builtin/providers/google/resource_compute_instance.go (about)

     1  package google
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/hashicorp/terraform/helper/hashcode"
     8  	"github.com/hashicorp/terraform/helper/schema"
     9  	"google.golang.org/api/compute/v1"
    10  	"google.golang.org/api/googleapi"
    11  	"strings"
    12  )
    13  
    14  func stringHashcode(v interface{}) int {
    15  	return hashcode.String(v.(string))
    16  }
    17  
    18  func stringScopeHashcode(v interface{}) int {
    19  	v = canonicalizeServiceScope(v.(string))
    20  	return hashcode.String(v.(string))
    21  }
    22  
    23  func resourceComputeInstance() *schema.Resource {
    24  	return &schema.Resource{
    25  		Create: resourceComputeInstanceCreate,
    26  		Read:   resourceComputeInstanceRead,
    27  		Update: resourceComputeInstanceUpdate,
    28  		Delete: resourceComputeInstanceDelete,
    29  
    30  		SchemaVersion: 2,
    31  		MigrateState:  resourceComputeInstanceMigrateState,
    32  
    33  		Schema: map[string]*schema.Schema{
    34  			"name": &schema.Schema{
    35  				Type:     schema.TypeString,
    36  				Required: true,
    37  				ForceNew: true,
    38  			},
    39  
    40  			"description": &schema.Schema{
    41  				Type:     schema.TypeString,
    42  				Optional: true,
    43  				ForceNew: true,
    44  			},
    45  
    46  			"machine_type": &schema.Schema{
    47  				Type:     schema.TypeString,
    48  				Required: true,
    49  				ForceNew: true,
    50  			},
    51  
    52  			"zone": &schema.Schema{
    53  				Type:     schema.TypeString,
    54  				Required: true,
    55  				ForceNew: true,
    56  			},
    57  
    58  			"disk": &schema.Schema{
    59  				Type:     schema.TypeList,
    60  				Required: true,
    61  				ForceNew: true,
    62  				Elem: &schema.Resource{
    63  					Schema: map[string]*schema.Schema{
    64  						// TODO(mitchellh): one of image or disk is required
    65  
    66  						"disk": &schema.Schema{
    67  							Type:     schema.TypeString,
    68  							Optional: true,
    69  							ForceNew: true,
    70  						},
    71  
    72  						"image": &schema.Schema{
    73  							Type:     schema.TypeString,
    74  							Optional: true,
    75  							ForceNew: true,
    76  						},
    77  
    78  						"type": &schema.Schema{
    79  							Type:     schema.TypeString,
    80  							Optional: true,
    81  							ForceNew: true,
    82  						},
    83  
    84  						"scratch": &schema.Schema{
    85  							Type:     schema.TypeBool,
    86  							Optional: true,
    87  							ForceNew: true,
    88  						},
    89  
    90  						"auto_delete": &schema.Schema{
    91  							Type:     schema.TypeBool,
    92  							Optional: true,
    93  							Default:  true,
    94  							ForceNew: true,
    95  						},
    96  
    97  						"size": &schema.Schema{
    98  							Type:     schema.TypeInt,
    99  							Optional: true,
   100  							ForceNew: true,
   101  						},
   102  
   103  						"device_name": &schema.Schema{
   104  							Type:     schema.TypeString,
   105  							Optional: true,
   106  						},
   107  					},
   108  				},
   109  			},
   110  
   111  			"network_interface": &schema.Schema{
   112  				Type:     schema.TypeList,
   113  				Optional: true,
   114  				ForceNew: true,
   115  				Elem: &schema.Resource{
   116  					Schema: map[string]*schema.Schema{
   117  						"network": &schema.Schema{
   118  							Type:     schema.TypeString,
   119  							Required: true,
   120  							ForceNew: true,
   121  						},
   122  
   123  						"name": &schema.Schema{
   124  							Type:     schema.TypeString,
   125  							Computed: true,
   126  						},
   127  
   128  						"address": &schema.Schema{
   129  							Type:     schema.TypeString,
   130  							Computed: true,
   131  						},
   132  
   133  						"access_config": &schema.Schema{
   134  							Type:     schema.TypeList,
   135  							Optional: true,
   136  							Elem: &schema.Resource{
   137  								Schema: map[string]*schema.Schema{
   138  									"nat_ip": &schema.Schema{
   139  										Type:     schema.TypeString,
   140  										Computed: true,
   141  										Optional: true,
   142  									},
   143  								},
   144  							},
   145  						},
   146  					},
   147  				},
   148  			},
   149  
   150  			"network": &schema.Schema{
   151  				Type:       schema.TypeList,
   152  				Optional:   true,
   153  				ForceNew:   true,
   154  				Deprecated: "Please use network_interface",
   155  				Elem: &schema.Resource{
   156  					Schema: map[string]*schema.Schema{
   157  						"source": &schema.Schema{
   158  							Type:     schema.TypeString,
   159  							Required: true,
   160  							ForceNew: true,
   161  						},
   162  
   163  						"address": &schema.Schema{
   164  							Type:     schema.TypeString,
   165  							Optional: true,
   166  							ForceNew: true,
   167  						},
   168  
   169  						"name": &schema.Schema{
   170  							Type:     schema.TypeString,
   171  							Computed: true,
   172  						},
   173  
   174  						"internal_address": &schema.Schema{
   175  							Type:     schema.TypeString,
   176  							Computed: true,
   177  						},
   178  
   179  						"external_address": &schema.Schema{
   180  							Type:     schema.TypeString,
   181  							Computed: true,
   182  						},
   183  					},
   184  				},
   185  			},
   186  
   187  			"can_ip_forward": &schema.Schema{
   188  				Type:     schema.TypeBool,
   189  				Optional: true,
   190  				Default:  false,
   191  				ForceNew: true,
   192  			},
   193  
   194  			"metadata_startup_script": &schema.Schema{
   195  				Type:     schema.TypeString,
   196  				Optional: true,
   197  				ForceNew: true,
   198  			},
   199  
   200  			"metadata": &schema.Schema{
   201  				Type:         schema.TypeMap,
   202  				Optional:     true,
   203  				Elem:         schema.TypeString,
   204  				ValidateFunc: validateInstanceMetadata,
   205  			},
   206  
   207  			"service_account": &schema.Schema{
   208  				Type:     schema.TypeList,
   209  				Optional: true,
   210  				ForceNew: true,
   211  				Elem: &schema.Resource{
   212  					Schema: map[string]*schema.Schema{
   213  						"email": &schema.Schema{
   214  							Type:     schema.TypeString,
   215  							Computed: true,
   216  							ForceNew: true,
   217  						},
   218  
   219  						"scopes": &schema.Schema{
   220  							Type:     schema.TypeSet,
   221  							Required: true,
   222  							ForceNew: true,
   223  							Elem: &schema.Schema{
   224  								Type: schema.TypeString,
   225  								StateFunc: func(v interface{}) string {
   226  									return canonicalizeServiceScope(v.(string))
   227  								},
   228  							},
   229  							Set: stringScopeHashcode,
   230  						},
   231  					},
   232  				},
   233  			},
   234  
   235  			"scheduling": &schema.Schema{
   236  				Type:     schema.TypeList,
   237  				Optional: true,
   238  				Elem: &schema.Resource{
   239  					Schema: map[string]*schema.Schema{
   240  						"on_host_maintenance": &schema.Schema{
   241  							Type:     schema.TypeString,
   242  							Optional: true,
   243  						},
   244  
   245  						"automatic_restart": &schema.Schema{
   246  							Type:     schema.TypeBool,
   247  							Optional: true,
   248  						},
   249  
   250  						"preemptible": &schema.Schema{
   251  							Type:     schema.TypeBool,
   252  							Optional: true,
   253  						},
   254  					},
   255  				},
   256  			},
   257  
   258  			"tags": &schema.Schema{
   259  				Type:     schema.TypeSet,
   260  				Optional: true,
   261  				Elem:     &schema.Schema{Type: schema.TypeString},
   262  				Set:      stringHashcode,
   263  			},
   264  
   265  			"metadata_fingerprint": &schema.Schema{
   266  				Type:     schema.TypeString,
   267  				Computed: true,
   268  			},
   269  
   270  			"tags_fingerprint": &schema.Schema{
   271  				Type:     schema.TypeString,
   272  				Computed: true,
   273  			},
   274  
   275  			"self_link": &schema.Schema{
   276  				Type:     schema.TypeString,
   277  				Computed: true,
   278  			},
   279  		},
   280  	}
   281  }
   282  
   283  func getInstance(config *Config, d *schema.ResourceData) (*compute.Instance, error) {
   284  	instance, err := config.clientCompute.Instances.Get(
   285  		config.Project, d.Get("zone").(string), d.Id()).Do()
   286  	if err != nil {
   287  		if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 {
   288  			// The resource doesn't exist anymore
   289  			id := d.Id()
   290  			d.SetId("")
   291  
   292  			return nil, fmt.Errorf("Resource %s no longer exists", id)
   293  		}
   294  
   295  		return nil, fmt.Errorf("Error reading instance: %s", err)
   296  	}
   297  
   298  	return instance, nil
   299  }
   300  
   301  func resourceComputeInstanceCreate(d *schema.ResourceData, meta interface{}) error {
   302  	config := meta.(*Config)
   303  
   304  	// Get the zone
   305  	log.Printf("[DEBUG] Loading zone: %s", d.Get("zone").(string))
   306  	zone, err := config.clientCompute.Zones.Get(
   307  		config.Project, d.Get("zone").(string)).Do()
   308  	if err != nil {
   309  		return fmt.Errorf(
   310  			"Error loading zone '%s': %s", d.Get("zone").(string), err)
   311  	}
   312  
   313  	// Get the machine type
   314  	log.Printf("[DEBUG] Loading machine type: %s", d.Get("machine_type").(string))
   315  	machineType, err := config.clientCompute.MachineTypes.Get(
   316  		config.Project, zone.Name, d.Get("machine_type").(string)).Do()
   317  	if err != nil {
   318  		return fmt.Errorf(
   319  			"Error loading machine type: %s",
   320  			err)
   321  	}
   322  
   323  	// Build up the list of disks
   324  	disksCount := d.Get("disk.#").(int)
   325  	disks := make([]*compute.AttachedDisk, 0, disksCount)
   326  	for i := 0; i < disksCount; i++ {
   327  		prefix := fmt.Sprintf("disk.%d", i)
   328  
   329  		// var sourceLink string
   330  
   331  		// Build the disk
   332  		var disk compute.AttachedDisk
   333  		disk.Type = "PERSISTENT"
   334  		disk.Mode = "READ_WRITE"
   335  		disk.Boot = i == 0
   336  		disk.AutoDelete = d.Get(prefix + ".auto_delete").(bool)
   337  
   338  		// Load up the disk for this disk if specified
   339  		if v, ok := d.GetOk(prefix + ".disk"); ok {
   340  			diskName := v.(string)
   341  			diskData, err := config.clientCompute.Disks.Get(
   342  				config.Project, zone.Name, diskName).Do()
   343  			if err != nil {
   344  				return fmt.Errorf(
   345  					"Error loading disk '%s': %s",
   346  					diskName, err)
   347  			}
   348  
   349  			disk.Source = diskData.SelfLink
   350  		} else {
   351  			// Create a new disk
   352  			disk.InitializeParams = &compute.AttachedDiskInitializeParams{}
   353  		}
   354  
   355  		if v, ok := d.GetOk(prefix + ".scratch"); ok {
   356  			if v.(bool) {
   357  				disk.Type = "SCRATCH"
   358  			}
   359  		}
   360  
   361  		// Load up the image for this disk if specified
   362  		if v, ok := d.GetOk(prefix + ".image"); ok {
   363  			imageName := v.(string)
   364  
   365  			imageUrl, err := resolveImage(config, imageName)
   366  			if err != nil {
   367  				return fmt.Errorf(
   368  					"Error resolving image name '%s': %s",
   369  					imageName, err)
   370  			}
   371  
   372  			disk.InitializeParams.SourceImage = imageUrl
   373  		}
   374  
   375  		if v, ok := d.GetOk(prefix + ".type"); ok {
   376  			diskTypeName := v.(string)
   377  			diskType, err := readDiskType(config, zone, diskTypeName)
   378  			if err != nil {
   379  				return fmt.Errorf(
   380  					"Error loading disk type '%s': %s",
   381  					diskTypeName, err)
   382  			}
   383  
   384  			disk.InitializeParams.DiskType = diskType.SelfLink
   385  		}
   386  
   387  		if v, ok := d.GetOk(prefix + ".size"); ok {
   388  			diskSizeGb := v.(int)
   389  			disk.InitializeParams.DiskSizeGb = int64(diskSizeGb)
   390  		}
   391  
   392  		if v, ok := d.GetOk(prefix + ".device_name"); ok {
   393  			disk.DeviceName = v.(string)
   394  		}
   395  
   396  		disks = append(disks, &disk)
   397  	}
   398  
   399  	networksCount := d.Get("network.#").(int)
   400  	networkInterfacesCount := d.Get("network_interface.#").(int)
   401  
   402  	if networksCount > 0 && networkInterfacesCount > 0 {
   403  		return fmt.Errorf("Error: cannot define both networks and network_interfaces.")
   404  	}
   405  	if networksCount == 0 && networkInterfacesCount == 0 {
   406  		return fmt.Errorf("Error: Must define at least one network_interface.")
   407  	}
   408  
   409  	var networkInterfaces []*compute.NetworkInterface
   410  
   411  	if networksCount > 0 {
   412  		// TODO: Delete this block when removing network { }
   413  		// Build up the list of networkInterfaces
   414  		networkInterfaces = make([]*compute.NetworkInterface, 0, networksCount)
   415  		for i := 0; i < networksCount; i++ {
   416  			prefix := fmt.Sprintf("network.%d", i)
   417  			// Load up the name of this network
   418  			networkName := d.Get(prefix + ".source").(string)
   419  			network, err := config.clientCompute.Networks.Get(
   420  				config.Project, networkName).Do()
   421  			if err != nil {
   422  				return fmt.Errorf(
   423  					"Error loading network '%s': %s",
   424  					networkName, err)
   425  			}
   426  
   427  			// Build the networkInterface
   428  			var iface compute.NetworkInterface
   429  			iface.AccessConfigs = []*compute.AccessConfig{
   430  				&compute.AccessConfig{
   431  					Type:  "ONE_TO_ONE_NAT",
   432  					NatIP: d.Get(prefix + ".address").(string),
   433  				},
   434  			}
   435  			iface.Network = network.SelfLink
   436  
   437  			networkInterfaces = append(networkInterfaces, &iface)
   438  		}
   439  	}
   440  
   441  	if networkInterfacesCount > 0 {
   442  		// Build up the list of networkInterfaces
   443  		networkInterfaces = make([]*compute.NetworkInterface, 0, networkInterfacesCount)
   444  		for i := 0; i < networkInterfacesCount; i++ {
   445  			prefix := fmt.Sprintf("network_interface.%d", i)
   446  			// Load up the name of this network_interfac
   447  			networkName := d.Get(prefix + ".network").(string)
   448  			network, err := config.clientCompute.Networks.Get(
   449  				config.Project, networkName).Do()
   450  			if err != nil {
   451  				return fmt.Errorf(
   452  					"Error referencing network '%s': %s",
   453  					networkName, err)
   454  			}
   455  
   456  			// Build the networkInterface
   457  			var iface compute.NetworkInterface
   458  			iface.Network = network.SelfLink
   459  
   460  			// Handle access_config structs
   461  			accessConfigsCount := d.Get(prefix + ".access_config.#").(int)
   462  			iface.AccessConfigs = make([]*compute.AccessConfig, accessConfigsCount)
   463  			for j := 0; j < accessConfigsCount; j++ {
   464  				acPrefix := fmt.Sprintf("%s.access_config.%d", prefix, j)
   465  				iface.AccessConfigs[j] = &compute.AccessConfig{
   466  					Type:  "ONE_TO_ONE_NAT",
   467  					NatIP: d.Get(acPrefix + ".nat_ip").(string),
   468  				}
   469  			}
   470  
   471  			networkInterfaces = append(networkInterfaces, &iface)
   472  		}
   473  	}
   474  
   475  	serviceAccountsCount := d.Get("service_account.#").(int)
   476  	serviceAccounts := make([]*compute.ServiceAccount, 0, serviceAccountsCount)
   477  	for i := 0; i < serviceAccountsCount; i++ {
   478  		prefix := fmt.Sprintf("service_account.%d", i)
   479  
   480  		scopesSet := d.Get(prefix + ".scopes").(*schema.Set)
   481  		scopes := make([]string, scopesSet.Len())
   482  		for i, v := range scopesSet.List() {
   483  			scopes[i] = canonicalizeServiceScope(v.(string))
   484  		}
   485  
   486  		serviceAccount := &compute.ServiceAccount{
   487  			Email:  "default",
   488  			Scopes: scopes,
   489  		}
   490  
   491  		serviceAccounts = append(serviceAccounts, serviceAccount)
   492  	}
   493  
   494  	prefix := "scheduling.0"
   495  	scheduling := &compute.Scheduling{}
   496  
   497  	if val, ok := d.GetOk(prefix + ".automatic_restart"); ok {
   498  		scheduling.AutomaticRestart = val.(bool)
   499  	}
   500  
   501  	if val, ok := d.GetOk(prefix + ".preemptible"); ok {
   502  		scheduling.Preemptible = val.(bool)
   503  	}
   504  
   505  	if val, ok := d.GetOk(prefix + ".on_host_maintenance"); ok {
   506  		scheduling.OnHostMaintenance = val.(string)
   507  	}
   508  
   509  	metadata, err := resourceInstanceMetadata(d)
   510  	if err != nil {
   511  		return fmt.Errorf("Error creating metadata: %s", err)
   512  	}
   513  
   514  	// Create the instance information
   515  	instance := compute.Instance{
   516  		CanIpForward:      d.Get("can_ip_forward").(bool),
   517  		Description:       d.Get("description").(string),
   518  		Disks:             disks,
   519  		MachineType:       machineType.SelfLink,
   520  		Metadata:          metadata,
   521  		Name:              d.Get("name").(string),
   522  		NetworkInterfaces: networkInterfaces,
   523  		Tags:              resourceInstanceTags(d),
   524  		ServiceAccounts:   serviceAccounts,
   525  		Scheduling:        scheduling,
   526  	}
   527  
   528  	log.Printf("[INFO] Requesting instance creation")
   529  	op, err := config.clientCompute.Instances.Insert(
   530  		config.Project, zone.Name, &instance).Do()
   531  	if err != nil {
   532  		return fmt.Errorf("Error creating instance: %s", err)
   533  	}
   534  
   535  	// Store the ID now
   536  	d.SetId(instance.Name)
   537  
   538  	// Wait for the operation to complete
   539  	waitErr := computeOperationWaitZone(config, op, zone.Name, "instance to create")
   540  	if waitErr != nil {
   541  		// The resource didn't actually create
   542  		d.SetId("")
   543  		return waitErr
   544  	}
   545  
   546  	return resourceComputeInstanceRead(d, meta)
   547  }
   548  
   549  func resourceComputeInstanceRead(d *schema.ResourceData, meta interface{}) error {
   550  	config := meta.(*Config)
   551  
   552  	id := d.Id()
   553  	instance, err := getInstance(config, d)
   554  	if err != nil {
   555  		if strings.Contains(err.Error(), "no longer exists") {
   556  			log.Printf("[WARN] Google Compute Instance (%s) not found", id)
   557  			return nil
   558  		}
   559  		return err
   560  	}
   561  
   562  	// Synch metadata
   563  	md := instance.Metadata
   564  
   565  	_md := MetadataFormatSchema(md)
   566  	delete(_md, "startup-script")
   567  
   568  	if script, scriptExists := d.GetOk("metadata_startup_script"); scriptExists {
   569  		d.Set("metadata_startup_script", script)
   570  	}
   571  
   572  	if err = d.Set("metadata", _md); err != nil {
   573  		return fmt.Errorf("Error setting metadata: %s", err)
   574  	}
   575  
   576  	d.Set("can_ip_forward", instance.CanIpForward)
   577  
   578  	// Set the service accounts
   579  	serviceAccounts := make([]map[string]interface{}, 0, 1)
   580  	for _, serviceAccount := range instance.ServiceAccounts {
   581  		scopes := make([]interface{}, len(serviceAccount.Scopes))
   582  		for i, scope := range serviceAccount.Scopes {
   583  			scopes[i] = scope
   584  		}
   585  		serviceAccounts = append(serviceAccounts, map[string]interface{}{
   586  			"email":  serviceAccount.Email,
   587  			"scopes": schema.NewSet(stringScopeHashcode, scopes),
   588  		})
   589  	}
   590  	d.Set("service_account", serviceAccounts)
   591  
   592  	networksCount := d.Get("network.#").(int)
   593  	networkInterfacesCount := d.Get("network_interface.#").(int)
   594  
   595  	if networksCount > 0 && networkInterfacesCount > 0 {
   596  		return fmt.Errorf("Error: cannot define both networks and network_interfaces.")
   597  	}
   598  	if networksCount == 0 && networkInterfacesCount == 0 {
   599  		return fmt.Errorf("Error: Must define at least one network_interface.")
   600  	}
   601  
   602  	// Set the networks
   603  	// Use the first external IP found for the default connection info.
   604  	externalIP := ""
   605  	internalIP := ""
   606  	networks := make([]map[string]interface{}, 0, 1)
   607  	if networksCount > 0 {
   608  		// TODO: Remove this when realizing deprecation of .network
   609  		for i, iface := range instance.NetworkInterfaces {
   610  			var natIP string
   611  			for _, config := range iface.AccessConfigs {
   612  				if config.Type == "ONE_TO_ONE_NAT" {
   613  					natIP = config.NatIP
   614  					break
   615  				}
   616  			}
   617  
   618  			if externalIP == "" && natIP != "" {
   619  				externalIP = natIP
   620  			}
   621  
   622  			network := make(map[string]interface{})
   623  			network["name"] = iface.Name
   624  			network["external_address"] = natIP
   625  			network["internal_address"] = iface.NetworkIP
   626  			network["source"] = d.Get(fmt.Sprintf("network.%d.source", i))
   627  			networks = append(networks, network)
   628  		}
   629  	}
   630  	d.Set("network", networks)
   631  
   632  	networkInterfaces := make([]map[string]interface{}, 0, 1)
   633  	if networkInterfacesCount > 0 {
   634  		for i, iface := range instance.NetworkInterfaces {
   635  			// The first non-empty ip is left in natIP
   636  			var natIP string
   637  			accessConfigs := make(
   638  				[]map[string]interface{}, 0, len(iface.AccessConfigs))
   639  			for _, config := range iface.AccessConfigs {
   640  				accessConfigs = append(accessConfigs, map[string]interface{}{
   641  					"nat_ip": config.NatIP,
   642  				})
   643  
   644  				if natIP == "" {
   645  					natIP = config.NatIP
   646  				}
   647  			}
   648  
   649  			if externalIP == "" {
   650  				externalIP = natIP
   651  			}
   652  
   653  			if internalIP == "" {
   654  				internalIP = iface.NetworkIP
   655  			}
   656  
   657  			networkInterfaces = append(networkInterfaces, map[string]interface{}{
   658  				"name":          iface.Name,
   659  				"address":       iface.NetworkIP,
   660  				"network":       d.Get(fmt.Sprintf("network_interface.%d.network", i)),
   661  				"access_config": accessConfigs,
   662  			})
   663  		}
   664  	}
   665  	d.Set("network_interface", networkInterfaces)
   666  
   667  	// Fall back on internal ip if there is no external ip.  This makes sense in the situation where
   668  	// terraform is being used on a cloud instance and can therefore access the instances it creates
   669  	// via their internal ips.
   670  	sshIP := externalIP
   671  	if sshIP == "" {
   672  		sshIP = internalIP
   673  	}
   674  
   675  	// Initialize the connection info
   676  	d.SetConnInfo(map[string]string{
   677  		"type": "ssh",
   678  		"host": sshIP,
   679  	})
   680  
   681  	// Set the metadata fingerprint if there is one.
   682  	if instance.Metadata != nil {
   683  		d.Set("metadata_fingerprint", instance.Metadata.Fingerprint)
   684  	}
   685  
   686  	// Set the tags fingerprint if there is one.
   687  	if instance.Tags != nil {
   688  		d.Set("tags_fingerprint", instance.Tags.Fingerprint)
   689  	}
   690  
   691  	d.Set("self_link", instance.SelfLink)
   692  	d.SetId(instance.Name)
   693  
   694  	return nil
   695  }
   696  
   697  func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
   698  	config := meta.(*Config)
   699  
   700  	zone := d.Get("zone").(string)
   701  
   702  	instance, err := getInstance(config, d)
   703  	if err != nil {
   704  		return err
   705  	}
   706  
   707  	// Enable partial mode for the resource since it is possible
   708  	d.Partial(true)
   709  
   710  	// If the Metadata has changed, then update that.
   711  	if d.HasChange("metadata") {
   712  		o, n := d.GetChange("metadata")
   713  		if script, scriptExists := d.GetOk("metadata_startup_script"); scriptExists {
   714  			if _, ok := n.(map[string]interface{})["startup-script"]; ok {
   715  				return fmt.Errorf("Only one of metadata.startup-script and metadata_startup_script may be defined")
   716  			}
   717  
   718  			n.(map[string]interface{})["startup-script"] = script
   719  		}
   720  
   721  		updateMD := func() error {
   722  			// Reload the instance in the case of a fingerprint mismatch
   723  			instance, err = getInstance(config, d)
   724  			if err != nil {
   725  				return err
   726  			}
   727  
   728  			md := instance.Metadata
   729  
   730  			MetadataUpdate(o.(map[string]interface{}), n.(map[string]interface{}), md)
   731  
   732  			if err != nil {
   733  				return fmt.Errorf("Error updating metadata: %s", err)
   734  			}
   735  			op, err := config.clientCompute.Instances.SetMetadata(
   736  				config.Project, zone, d.Id(), md).Do()
   737  			if err != nil {
   738  				return fmt.Errorf("Error updating metadata: %s", err)
   739  			}
   740  
   741  			opErr := computeOperationWaitZone(config, op, zone, "metadata to update")
   742  			if opErr != nil {
   743  				return opErr
   744  			}
   745  
   746  			d.SetPartial("metadata")
   747  			return nil
   748  		}
   749  
   750  		MetadataRetryWrapper(updateMD)
   751  	}
   752  
   753  	if d.HasChange("tags") {
   754  		tags := resourceInstanceTags(d)
   755  		op, err := config.clientCompute.Instances.SetTags(
   756  			config.Project, zone, d.Id(), tags).Do()
   757  		if err != nil {
   758  			return fmt.Errorf("Error updating tags: %s", err)
   759  		}
   760  
   761  		opErr := computeOperationWaitZone(config, op, zone, "tags to update")
   762  		if opErr != nil {
   763  			return opErr
   764  		}
   765  
   766  		d.SetPartial("tags")
   767  	}
   768  
   769  	if d.HasChange("scheduling") {
   770  		prefix := "scheduling.0"
   771  		scheduling := &compute.Scheduling{}
   772  
   773  		if val, ok := d.GetOk(prefix + ".automatic_restart"); ok {
   774  			scheduling.AutomaticRestart = val.(bool)
   775  		}
   776  
   777  		if val, ok := d.GetOk(prefix + ".preemptible"); ok {
   778  			scheduling.Preemptible = val.(bool)
   779  		}
   780  
   781  		if val, ok := d.GetOk(prefix + ".on_host_maintenance"); ok {
   782  			scheduling.OnHostMaintenance = val.(string)
   783  		}
   784  
   785  		op, err := config.clientCompute.Instances.SetScheduling(config.Project,
   786  			zone, d.Id(), scheduling).Do()
   787  
   788  		if err != nil {
   789  			return fmt.Errorf("Error updating scheduling policy: %s", err)
   790  		}
   791  
   792  		opErr := computeOperationWaitZone(config, op, zone,
   793  			"scheduling policy update")
   794  		if opErr != nil {
   795  			return opErr
   796  		}
   797  
   798  		d.SetPartial("scheduling")
   799  	}
   800  
   801  	networkInterfacesCount := d.Get("network_interface.#").(int)
   802  	if networkInterfacesCount > 0 {
   803  		// Sanity check
   804  		if networkInterfacesCount != len(instance.NetworkInterfaces) {
   805  			return fmt.Errorf("Instance had unexpected number of network interfaces: %d", len(instance.NetworkInterfaces))
   806  		}
   807  		for i := 0; i < networkInterfacesCount; i++ {
   808  			prefix := fmt.Sprintf("network_interface.%d", i)
   809  			instNetworkInterface := instance.NetworkInterfaces[i]
   810  			networkName := d.Get(prefix + ".name").(string)
   811  
   812  			// TODO: This sanity check is broken by #929, disabled for now (by forcing the equality)
   813  			networkName = instNetworkInterface.Name
   814  			// Sanity check
   815  			if networkName != instNetworkInterface.Name {
   816  				return fmt.Errorf("Instance networkInterface had unexpected name: %s", instNetworkInterface.Name)
   817  			}
   818  
   819  			if d.HasChange(prefix + ".access_config") {
   820  
   821  				// TODO: This code deletes then recreates accessConfigs.  This is bad because it may
   822  				// leave the machine inaccessible from either ip if the creation part fails (network
   823  				// timeout etc).  However right now there is a GCE limit of 1 accessConfig so it is
   824  				// the only way to do it.  In future this should be revised to only change what is
   825  				// necessary, and also add before removing.
   826  
   827  				// Delete any accessConfig that currently exists in instNetworkInterface
   828  				for _, ac := range instNetworkInterface.AccessConfigs {
   829  					op, err := config.clientCompute.Instances.DeleteAccessConfig(
   830  						config.Project, zone, d.Id(), ac.Name, networkName).Do()
   831  					if err != nil {
   832  						return fmt.Errorf("Error deleting old access_config: %s", err)
   833  					}
   834  					opErr := computeOperationWaitZone(config, op, zone, "old access_config to delete")
   835  					if opErr != nil {
   836  						return opErr
   837  					}
   838  				}
   839  
   840  				// Create new ones
   841  				accessConfigsCount := d.Get(prefix + ".access_config.#").(int)
   842  				for j := 0; j < accessConfigsCount; j++ {
   843  					acPrefix := fmt.Sprintf("%s.access_config.%d", prefix, j)
   844  					ac := &compute.AccessConfig{
   845  						Type:  "ONE_TO_ONE_NAT",
   846  						NatIP: d.Get(acPrefix + ".nat_ip").(string),
   847  					}
   848  					op, err := config.clientCompute.Instances.AddAccessConfig(
   849  						config.Project, zone, d.Id(), networkName, ac).Do()
   850  					if err != nil {
   851  						return fmt.Errorf("Error adding new access_config: %s", err)
   852  					}
   853  					opErr := computeOperationWaitZone(config, op, zone, "new access_config to add")
   854  					if opErr != nil {
   855  						return opErr
   856  					}
   857  				}
   858  			}
   859  		}
   860  	}
   861  
   862  	// We made it, disable partial mode
   863  	d.Partial(false)
   864  
   865  	return resourceComputeInstanceRead(d, meta)
   866  }
   867  
   868  func resourceComputeInstanceDelete(d *schema.ResourceData, meta interface{}) error {
   869  	config := meta.(*Config)
   870  
   871  	zone := d.Get("zone").(string)
   872  	log.Printf("[INFO] Requesting instance deletion: %s", d.Id())
   873  	op, err := config.clientCompute.Instances.Delete(config.Project, zone, d.Id()).Do()
   874  	if err != nil {
   875  		return fmt.Errorf("Error deleting instance: %s", err)
   876  	}
   877  
   878  	// Wait for the operation to complete
   879  	opErr := computeOperationWaitZone(config, op, zone, "instance to delete")
   880  	if opErr != nil {
   881  		return opErr
   882  	}
   883  
   884  	d.SetId("")
   885  	return nil
   886  }
   887  
   888  func resourceInstanceMetadata(d *schema.ResourceData) (*compute.Metadata, error) {
   889  	m := &compute.Metadata{}
   890  	mdMap := d.Get("metadata").(map[string]interface{})
   891  	if v, ok := d.GetOk("metadata_startup_script"); ok && v.(string) != "" {
   892  		mdMap["startup-script"] = v
   893  	}
   894  	if len(mdMap) > 0 {
   895  		m.Items = make([]*compute.MetadataItems, 0, len(mdMap))
   896  		for key, val := range mdMap {
   897  			v := val.(string)
   898  			m.Items = append(m.Items, &compute.MetadataItems{
   899  				Key:   key,
   900  				Value: &v,
   901  			})
   902  		}
   903  
   904  		// Set the fingerprint. If the metadata has never been set before
   905  		// then this will just be blank.
   906  		m.Fingerprint = d.Get("metadata_fingerprint").(string)
   907  	}
   908  
   909  	return m, nil
   910  }
   911  
   912  func resourceInstanceTags(d *schema.ResourceData) *compute.Tags {
   913  	// Calculate the tags
   914  	var tags *compute.Tags
   915  	if v := d.Get("tags"); v != nil {
   916  		vs := v.(*schema.Set)
   917  		tags = new(compute.Tags)
   918  		tags.Items = make([]string, vs.Len())
   919  		for i, v := range vs.List() {
   920  			tags.Items[i] = v.(string)
   921  		}
   922  
   923  		tags.Fingerprint = d.Get("tags_fingerprint").(string)
   924  	}
   925  
   926  	return tags
   927  }
   928  
   929  func validateInstanceMetadata(v interface{}, k string) (ws []string, es []error) {
   930  	mdMap := v.(map[string]interface{})
   931  	if _, ok := mdMap["startup-script"]; ok {
   932  		es = append(es, fmt.Errorf(
   933  			"Use metadata_startup_script instead of a startup-script key in %q.", k))
   934  	}
   935  	return
   936  }