github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/google/resource_compute_instance.go (about)

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