github.com/jrperritt/terraform@v0.1.1-0.20170525065507-96f391dafc38/builtin/providers/aws/resource_aws_instance.go (about)

     1  package aws
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/sha1"
     6  	"encoding/base64"
     7  	"encoding/hex"
     8  	"errors"
     9  	"fmt"
    10  	"log"
    11  	"strings"
    12  	"time"
    13  
    14  	"github.com/aws/aws-sdk-go/aws"
    15  	"github.com/aws/aws-sdk-go/aws/awserr"
    16  	"github.com/aws/aws-sdk-go/service/ec2"
    17  	"github.com/hashicorp/terraform/helper/hashcode"
    18  	"github.com/hashicorp/terraform/helper/resource"
    19  	"github.com/hashicorp/terraform/helper/schema"
    20  )
    21  
    22  func resourceAwsInstance() *schema.Resource {
    23  	return &schema.Resource{
    24  		Create: resourceAwsInstanceCreate,
    25  		Read:   resourceAwsInstanceRead,
    26  		Update: resourceAwsInstanceUpdate,
    27  		Delete: resourceAwsInstanceDelete,
    28  		Importer: &schema.ResourceImporter{
    29  			State: schema.ImportStatePassthrough,
    30  		},
    31  
    32  		SchemaVersion: 1,
    33  		MigrateState:  resourceAwsInstanceMigrateState,
    34  
    35  		Timeouts: &schema.ResourceTimeout{
    36  			Create: schema.DefaultTimeout(10 * time.Minute),
    37  			Update: schema.DefaultTimeout(10 * time.Minute),
    38  			Delete: schema.DefaultTimeout(10 * time.Minute),
    39  		},
    40  
    41  		Schema: map[string]*schema.Schema{
    42  			"ami": {
    43  				Type:     schema.TypeString,
    44  				Required: true,
    45  				ForceNew: true,
    46  			},
    47  
    48  			"associate_public_ip_address": {
    49  				Type:     schema.TypeBool,
    50  				ForceNew: true,
    51  				Computed: true,
    52  				Optional: true,
    53  			},
    54  
    55  			"availability_zone": {
    56  				Type:     schema.TypeString,
    57  				Optional: true,
    58  				Computed: true,
    59  				ForceNew: true,
    60  			},
    61  
    62  			"placement_group": {
    63  				Type:     schema.TypeString,
    64  				Optional: true,
    65  				Computed: true,
    66  				ForceNew: true,
    67  			},
    68  
    69  			"instance_type": {
    70  				Type:     schema.TypeString,
    71  				Required: true,
    72  			},
    73  
    74  			"key_name": {
    75  				Type:     schema.TypeString,
    76  				Optional: true,
    77  				ForceNew: true,
    78  				Computed: true,
    79  			},
    80  
    81  			"subnet_id": {
    82  				Type:     schema.TypeString,
    83  				Optional: true,
    84  				Computed: true,
    85  				ForceNew: true,
    86  			},
    87  
    88  			"private_ip": {
    89  				Type:     schema.TypeString,
    90  				Optional: true,
    91  				ForceNew: true,
    92  				Computed: true,
    93  			},
    94  
    95  			"source_dest_check": {
    96  				Type:     schema.TypeBool,
    97  				Optional: true,
    98  				Default:  true,
    99  				DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
   100  					// Suppress diff if network_interface is set
   101  					_, ok := d.GetOk("network_interface")
   102  					return ok
   103  				},
   104  			},
   105  
   106  			"user_data": {
   107  				Type:     schema.TypeString,
   108  				Optional: true,
   109  				ForceNew: true,
   110  				StateFunc: func(v interface{}) string {
   111  					switch v.(type) {
   112  					case string:
   113  						return userDataHashSum(v.(string))
   114  					default:
   115  						return ""
   116  					}
   117  				},
   118  			},
   119  
   120  			"security_groups": {
   121  				Type:     schema.TypeSet,
   122  				Optional: true,
   123  				Computed: true,
   124  				ForceNew: true,
   125  				Elem:     &schema.Schema{Type: schema.TypeString},
   126  				Set:      schema.HashString,
   127  			},
   128  
   129  			"vpc_security_group_ids": {
   130  				Type:     schema.TypeSet,
   131  				Optional: true,
   132  				Computed: true,
   133  				Elem:     &schema.Schema{Type: schema.TypeString},
   134  				Set:      schema.HashString,
   135  			},
   136  
   137  			"public_dns": {
   138  				Type:     schema.TypeString,
   139  				Computed: true,
   140  			},
   141  
   142  			// TODO: Deprecate me v0.10.0
   143  			"network_interface_id": {
   144  				Type:       schema.TypeString,
   145  				Computed:   true,
   146  				Deprecated: "Please use `primary_network_interface_id` instead",
   147  			},
   148  
   149  			"primary_network_interface_id": {
   150  				Type:     schema.TypeString,
   151  				Computed: true,
   152  			},
   153  
   154  			"network_interface": {
   155  				ConflictsWith: []string{"associate_public_ip_address", "subnet_id", "private_ip", "vpc_security_group_ids", "security_groups", "ipv6_addresses", "ipv6_address_count", "source_dest_check"},
   156  				Type:          schema.TypeSet,
   157  				Optional:      true,
   158  				Computed:      true,
   159  				Elem: &schema.Resource{
   160  					Schema: map[string]*schema.Schema{
   161  						"delete_on_termination": {
   162  							Type:     schema.TypeBool,
   163  							Default:  false,
   164  							Optional: true,
   165  							ForceNew: true,
   166  						},
   167  						"network_interface_id": {
   168  							Type:     schema.TypeString,
   169  							Required: true,
   170  							ForceNew: true,
   171  						},
   172  						"device_index": {
   173  							Type:     schema.TypeInt,
   174  							Required: true,
   175  							ForceNew: true,
   176  						},
   177  					},
   178  				},
   179  			},
   180  
   181  			"public_ip": {
   182  				Type:     schema.TypeString,
   183  				Computed: true,
   184  			},
   185  
   186  			"instance_state": {
   187  				Type:     schema.TypeString,
   188  				Computed: true,
   189  			},
   190  
   191  			"private_dns": {
   192  				Type:     schema.TypeString,
   193  				Computed: true,
   194  			},
   195  
   196  			"ebs_optimized": {
   197  				Type:     schema.TypeBool,
   198  				Optional: true,
   199  				ForceNew: true,
   200  			},
   201  
   202  			"disable_api_termination": {
   203  				Type:     schema.TypeBool,
   204  				Optional: true,
   205  			},
   206  
   207  			"instance_initiated_shutdown_behavior": {
   208  				Type:     schema.TypeString,
   209  				Optional: true,
   210  			},
   211  
   212  			"monitoring": {
   213  				Type:     schema.TypeBool,
   214  				Optional: true,
   215  			},
   216  
   217  			"iam_instance_profile": {
   218  				Type:     schema.TypeString,
   219  				Optional: true,
   220  			},
   221  
   222  			"ipv6_address_count": {
   223  				Type:     schema.TypeInt,
   224  				Optional: true,
   225  				ForceNew: true,
   226  				Computed: true,
   227  			},
   228  
   229  			"ipv6_addresses": {
   230  				Type:     schema.TypeList,
   231  				Optional: true,
   232  				Computed: true,
   233  				ForceNew: true,
   234  				Elem: &schema.Schema{
   235  					Type: schema.TypeString,
   236  				},
   237  			},
   238  
   239  			"tenancy": {
   240  				Type:     schema.TypeString,
   241  				Optional: true,
   242  				Computed: true,
   243  				ForceNew: true,
   244  			},
   245  
   246  			"tags": tagsSchema(),
   247  
   248  			"volume_tags": tagsSchemaComputed(),
   249  
   250  			"block_device": {
   251  				Type:     schema.TypeMap,
   252  				Optional: true,
   253  				Removed:  "Split out into three sub-types; see Changelog and Docs",
   254  			},
   255  
   256  			"ebs_block_device": {
   257  				Type:     schema.TypeSet,
   258  				Optional: true,
   259  				Computed: true,
   260  				Elem: &schema.Resource{
   261  					Schema: map[string]*schema.Schema{
   262  						"delete_on_termination": {
   263  							Type:     schema.TypeBool,
   264  							Optional: true,
   265  							Default:  true,
   266  							ForceNew: true,
   267  						},
   268  
   269  						"device_name": {
   270  							Type:     schema.TypeString,
   271  							Required: true,
   272  							ForceNew: true,
   273  						},
   274  
   275  						"encrypted": {
   276  							Type:     schema.TypeBool,
   277  							Optional: true,
   278  							Computed: true,
   279  							ForceNew: true,
   280  						},
   281  
   282  						"iops": {
   283  							Type:     schema.TypeInt,
   284  							Optional: true,
   285  							Computed: true,
   286  							ForceNew: true,
   287  						},
   288  
   289  						"snapshot_id": {
   290  							Type:     schema.TypeString,
   291  							Optional: true,
   292  							Computed: true,
   293  							ForceNew: true,
   294  						},
   295  
   296  						"volume_size": {
   297  							Type:     schema.TypeInt,
   298  							Optional: true,
   299  							Computed: true,
   300  							ForceNew: true,
   301  						},
   302  
   303  						"volume_type": {
   304  							Type:     schema.TypeString,
   305  							Optional: true,
   306  							Computed: true,
   307  							ForceNew: true,
   308  						},
   309  					},
   310  				},
   311  				Set: func(v interface{}) int {
   312  					var buf bytes.Buffer
   313  					m := v.(map[string]interface{})
   314  					buf.WriteString(fmt.Sprintf("%s-", m["device_name"].(string)))
   315  					buf.WriteString(fmt.Sprintf("%s-", m["snapshot_id"].(string)))
   316  					return hashcode.String(buf.String())
   317  				},
   318  			},
   319  
   320  			"ephemeral_block_device": {
   321  				Type:     schema.TypeSet,
   322  				Optional: true,
   323  				Computed: true,
   324  				ForceNew: true,
   325  				Elem: &schema.Resource{
   326  					Schema: map[string]*schema.Schema{
   327  						"device_name": {
   328  							Type:     schema.TypeString,
   329  							Required: true,
   330  						},
   331  
   332  						"virtual_name": {
   333  							Type:     schema.TypeString,
   334  							Optional: true,
   335  						},
   336  
   337  						"no_device": {
   338  							Type:     schema.TypeBool,
   339  							Optional: true,
   340  						},
   341  					},
   342  				},
   343  				Set: func(v interface{}) int {
   344  					var buf bytes.Buffer
   345  					m := v.(map[string]interface{})
   346  					buf.WriteString(fmt.Sprintf("%s-", m["device_name"].(string)))
   347  					buf.WriteString(fmt.Sprintf("%s-", m["virtual_name"].(string)))
   348  					if v, ok := m["no_device"].(bool); ok && v {
   349  						buf.WriteString(fmt.Sprintf("%t-", v))
   350  					}
   351  					return hashcode.String(buf.String())
   352  				},
   353  			},
   354  
   355  			"root_block_device": {
   356  				Type:     schema.TypeList,
   357  				Optional: true,
   358  				Computed: true,
   359  				MaxItems: 1,
   360  				Elem: &schema.Resource{
   361  					// "You can only modify the volume size, volume type, and Delete on
   362  					// Termination flag on the block device mapping entry for the root
   363  					// device volume." - bit.ly/ec2bdmap
   364  					Schema: map[string]*schema.Schema{
   365  						"delete_on_termination": {
   366  							Type:     schema.TypeBool,
   367  							Optional: true,
   368  							Default:  true,
   369  							ForceNew: true,
   370  						},
   371  
   372  						"iops": {
   373  							Type:     schema.TypeInt,
   374  							Optional: true,
   375  							Computed: true,
   376  							ForceNew: true,
   377  						},
   378  
   379  						"volume_size": {
   380  							Type:     schema.TypeInt,
   381  							Optional: true,
   382  							Computed: true,
   383  							ForceNew: true,
   384  						},
   385  
   386  						"volume_type": {
   387  							Type:     schema.TypeString,
   388  							Optional: true,
   389  							Computed: true,
   390  							ForceNew: true,
   391  						},
   392  					},
   393  				},
   394  			},
   395  		},
   396  	}
   397  }
   398  
   399  func resourceAwsInstanceCreate(d *schema.ResourceData, meta interface{}) error {
   400  	conn := meta.(*AWSClient).ec2conn
   401  
   402  	instanceOpts, err := buildAwsInstanceOpts(d, meta)
   403  	if err != nil {
   404  		return err
   405  	}
   406  
   407  	// Build the creation struct
   408  	runOpts := &ec2.RunInstancesInput{
   409  		BlockDeviceMappings:   instanceOpts.BlockDeviceMappings,
   410  		DisableApiTermination: instanceOpts.DisableAPITermination,
   411  		EbsOptimized:          instanceOpts.EBSOptimized,
   412  		Monitoring:            instanceOpts.Monitoring,
   413  		IamInstanceProfile:    instanceOpts.IAMInstanceProfile,
   414  		ImageId:               instanceOpts.ImageID,
   415  		InstanceInitiatedShutdownBehavior: instanceOpts.InstanceInitiatedShutdownBehavior,
   416  		InstanceType:                      instanceOpts.InstanceType,
   417  		KeyName:                           instanceOpts.KeyName,
   418  		MaxCount:                          aws.Int64(int64(1)),
   419  		MinCount:                          aws.Int64(int64(1)),
   420  		NetworkInterfaces:                 instanceOpts.NetworkInterfaces,
   421  		Placement:                         instanceOpts.Placement,
   422  		PrivateIpAddress:                  instanceOpts.PrivateIPAddress,
   423  		SecurityGroupIds:                  instanceOpts.SecurityGroupIDs,
   424  		SecurityGroups:                    instanceOpts.SecurityGroups,
   425  		SubnetId:                          instanceOpts.SubnetID,
   426  		UserData:                          instanceOpts.UserData64,
   427  	}
   428  
   429  	ipv6Count, ipv6CountOk := d.GetOk("ipv6_address_count")
   430  	ipv6Address, ipv6AddressOk := d.GetOk("ipv6_addresses")
   431  
   432  	if ipv6AddressOk && ipv6CountOk {
   433  		return fmt.Errorf("Only 1 of `ipv6_address_count` or `ipv6_addresses` can be specified")
   434  	}
   435  
   436  	if ipv6CountOk {
   437  		runOpts.Ipv6AddressCount = aws.Int64(int64(ipv6Count.(int)))
   438  	}
   439  
   440  	if ipv6AddressOk {
   441  		ipv6Addresses := make([]*ec2.InstanceIpv6Address, len(ipv6Address.([]interface{})))
   442  		for _, address := range ipv6Address.([]interface{}) {
   443  			ipv6Address := &ec2.InstanceIpv6Address{
   444  				Ipv6Address: aws.String(address.(string)),
   445  			}
   446  
   447  			ipv6Addresses = append(ipv6Addresses, ipv6Address)
   448  		}
   449  
   450  		runOpts.Ipv6Addresses = ipv6Addresses
   451  	}
   452  
   453  	restricted := meta.(*AWSClient).IsGovCloud() || meta.(*AWSClient).IsChinaCloud()
   454  	if !restricted {
   455  		tagsSpec := make([]*ec2.TagSpecification, 0)
   456  
   457  		if v, ok := d.GetOk("tags"); ok {
   458  			tags := tagsFromMap(v.(map[string]interface{}))
   459  
   460  			spec := &ec2.TagSpecification{
   461  				ResourceType: aws.String("instance"),
   462  				Tags:         tags,
   463  			}
   464  
   465  			tagsSpec = append(tagsSpec, spec)
   466  		}
   467  
   468  		if v, ok := d.GetOk("volume_tags"); ok {
   469  			tags := tagsFromMap(v.(map[string]interface{}))
   470  
   471  			spec := &ec2.TagSpecification{
   472  				ResourceType: aws.String("volume"),
   473  				Tags:         tags,
   474  			}
   475  
   476  			tagsSpec = append(tagsSpec, spec)
   477  		}
   478  
   479  		if len(tagsSpec) > 0 {
   480  			runOpts.TagSpecifications = tagsSpec
   481  		}
   482  	}
   483  
   484  	// Create the instance
   485  	log.Printf("[DEBUG] Run configuration: %s", runOpts)
   486  
   487  	var runResp *ec2.Reservation
   488  	err = resource.Retry(15*time.Second, func() *resource.RetryError {
   489  		var err error
   490  		runResp, err = conn.RunInstances(runOpts)
   491  		// IAM instance profiles can take ~10 seconds to propagate in AWS:
   492  		// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console
   493  		if isAWSErr(err, "InvalidParameterValue", "Invalid IAM Instance Profile") {
   494  			log.Print("[DEBUG] Invalid IAM Instance Profile referenced, retrying...")
   495  			return resource.RetryableError(err)
   496  		}
   497  		// IAM roles can also take time to propagate in AWS:
   498  		if isAWSErr(err, "InvalidParameterValue", " has no associated IAM Roles") {
   499  			log.Print("[DEBUG] IAM Instance Profile appears to have no IAM roles, retrying...")
   500  			return resource.RetryableError(err)
   501  		}
   502  		return resource.NonRetryableError(err)
   503  	})
   504  	// Warn if the AWS Error involves group ids, to help identify situation
   505  	// where a user uses group ids in security_groups for the Default VPC.
   506  	//   See https://github.com/hashicorp/terraform/issues/3798
   507  	if isAWSErr(err, "InvalidParameterValue", "groupId is invalid") {
   508  		return fmt.Errorf("Error launching instance, possible mismatch of Security Group IDs and Names. See AWS Instance docs here: %s.\n\n\tAWS Error: %s", "https://terraform.io/docs/providers/aws/r/instance.html", err.(awserr.Error).Message())
   509  	}
   510  	if err != nil {
   511  		return fmt.Errorf("Error launching source instance: %s", err)
   512  	}
   513  	if runResp == nil || len(runResp.Instances) == 0 {
   514  		return errors.New("Error launching source instance: no instances returned in response")
   515  	}
   516  
   517  	instance := runResp.Instances[0]
   518  	log.Printf("[INFO] Instance ID: %s", *instance.InstanceId)
   519  
   520  	// Store the resulting ID so we can look this up later
   521  	d.SetId(*instance.InstanceId)
   522  
   523  	// Wait for the instance to become running so we can get some attributes
   524  	// that aren't available until later.
   525  	log.Printf(
   526  		"[DEBUG] Waiting for instance (%s) to become running",
   527  		*instance.InstanceId)
   528  
   529  	stateConf := &resource.StateChangeConf{
   530  		Pending:    []string{"pending"},
   531  		Target:     []string{"running"},
   532  		Refresh:    InstanceStateRefreshFunc(conn, *instance.InstanceId, "terminated"),
   533  		Timeout:    d.Timeout(schema.TimeoutCreate),
   534  		Delay:      10 * time.Second,
   535  		MinTimeout: 3 * time.Second,
   536  	}
   537  
   538  	instanceRaw, err := stateConf.WaitForState()
   539  	if err != nil {
   540  		return fmt.Errorf(
   541  			"Error waiting for instance (%s) to become ready: %s",
   542  			*instance.InstanceId, err)
   543  	}
   544  
   545  	instance = instanceRaw.(*ec2.Instance)
   546  
   547  	// Initialize the connection info
   548  	if instance.PublicIpAddress != nil {
   549  		d.SetConnInfo(map[string]string{
   550  			"type": "ssh",
   551  			"host": *instance.PublicIpAddress,
   552  		})
   553  	} else if instance.PrivateIpAddress != nil {
   554  		d.SetConnInfo(map[string]string{
   555  			"type": "ssh",
   556  			"host": *instance.PrivateIpAddress,
   557  		})
   558  	}
   559  
   560  	// Update if we need to
   561  	return resourceAwsInstanceUpdate(d, meta)
   562  }
   563  
   564  func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error {
   565  	conn := meta.(*AWSClient).ec2conn
   566  
   567  	resp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{
   568  		InstanceIds: []*string{aws.String(d.Id())},
   569  	})
   570  	if err != nil {
   571  		// If the instance was not found, return nil so that we can show
   572  		// that the instance is gone.
   573  		if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" {
   574  			d.SetId("")
   575  			return nil
   576  		}
   577  
   578  		// Some other error, report it
   579  		return err
   580  	}
   581  
   582  	// If nothing was found, then return no state
   583  	if len(resp.Reservations) == 0 {
   584  		d.SetId("")
   585  		return nil
   586  	}
   587  
   588  	instance := resp.Reservations[0].Instances[0]
   589  
   590  	if instance.State != nil {
   591  		// If the instance is terminated, then it is gone
   592  		if *instance.State.Name == "terminated" {
   593  			d.SetId("")
   594  			return nil
   595  		}
   596  
   597  		d.Set("instance_state", instance.State.Name)
   598  	}
   599  
   600  	if instance.Placement != nil {
   601  		d.Set("availability_zone", instance.Placement.AvailabilityZone)
   602  	}
   603  	if instance.Placement.Tenancy != nil {
   604  		d.Set("tenancy", instance.Placement.Tenancy)
   605  	}
   606  
   607  	d.Set("ami", instance.ImageId)
   608  	d.Set("instance_type", instance.InstanceType)
   609  	d.Set("key_name", instance.KeyName)
   610  	d.Set("public_dns", instance.PublicDnsName)
   611  	d.Set("public_ip", instance.PublicIpAddress)
   612  	d.Set("private_dns", instance.PrivateDnsName)
   613  	d.Set("private_ip", instance.PrivateIpAddress)
   614  	d.Set("iam_instance_profile", iamInstanceProfileArnToName(instance.IamInstanceProfile))
   615  
   616  	// Set configured Network Interface Device Index Slice
   617  	// We only want to read, and populate state for the configured network_interface attachments. Otherwise, other
   618  	// resources have the potential to attach network interfaces to the instance, and cause a perpetual create/destroy
   619  	// diff. We should only read on changes configured for this specific resource because of this.
   620  	var configuredDeviceIndexes []int
   621  	if v, ok := d.GetOk("network_interface"); ok {
   622  		vL := v.(*schema.Set).List()
   623  		for _, vi := range vL {
   624  			mVi := vi.(map[string]interface{})
   625  			configuredDeviceIndexes = append(configuredDeviceIndexes, mVi["device_index"].(int))
   626  		}
   627  	}
   628  
   629  	var ipv6Addresses []string
   630  	if len(instance.NetworkInterfaces) > 0 {
   631  		var primaryNetworkInterface ec2.InstanceNetworkInterface
   632  		var networkInterfaces []map[string]interface{}
   633  		for _, iNi := range instance.NetworkInterfaces {
   634  			ni := make(map[string]interface{})
   635  			if *iNi.Attachment.DeviceIndex == 0 {
   636  				primaryNetworkInterface = *iNi
   637  			}
   638  			// If the attached network device is inside our configuration, refresh state with values found.
   639  			// Otherwise, assume the network device was attached via an outside resource.
   640  			for _, index := range configuredDeviceIndexes {
   641  				if index == int(*iNi.Attachment.DeviceIndex) {
   642  					ni["device_index"] = *iNi.Attachment.DeviceIndex
   643  					ni["network_interface_id"] = *iNi.NetworkInterfaceId
   644  					ni["delete_on_termination"] = *iNi.Attachment.DeleteOnTermination
   645  				}
   646  			}
   647  			// Don't add empty network interfaces to schema
   648  			if len(ni) == 0 {
   649  				continue
   650  			}
   651  			networkInterfaces = append(networkInterfaces, ni)
   652  		}
   653  		if err := d.Set("network_interface", networkInterfaces); err != nil {
   654  			return fmt.Errorf("Error setting network_interfaces: %v", err)
   655  		}
   656  
   657  		// Set primary network interface details
   658  		// If an instance is shutting down, network interfaces are detached, and attributes may be nil,
   659  		// need to protect against nil pointer dereferences
   660  		if primaryNetworkInterface.SubnetId != nil {
   661  			d.Set("subnet_id", primaryNetworkInterface.SubnetId)
   662  		}
   663  		if primaryNetworkInterface.NetworkInterfaceId != nil {
   664  			d.Set("network_interface_id", primaryNetworkInterface.NetworkInterfaceId) // TODO: Deprecate me v0.10.0
   665  			d.Set("primary_network_interface_id", primaryNetworkInterface.NetworkInterfaceId)
   666  		}
   667  		if primaryNetworkInterface.Ipv6Addresses != nil {
   668  			d.Set("ipv6_address_count", len(primaryNetworkInterface.Ipv6Addresses))
   669  		}
   670  		if primaryNetworkInterface.SourceDestCheck != nil {
   671  			d.Set("source_dest_check", primaryNetworkInterface.SourceDestCheck)
   672  		}
   673  
   674  		d.Set("associate_public_ip_address", primaryNetworkInterface.Association != nil)
   675  
   676  		for _, address := range primaryNetworkInterface.Ipv6Addresses {
   677  			ipv6Addresses = append(ipv6Addresses, *address.Ipv6Address)
   678  		}
   679  
   680  	} else {
   681  		d.Set("subnet_id", instance.SubnetId)
   682  		d.Set("network_interface_id", "") // TODO: Deprecate me v0.10.0
   683  		d.Set("primary_network_interface_id", "")
   684  	}
   685  
   686  	if err := d.Set("ipv6_addresses", ipv6Addresses); err != nil {
   687  		log.Printf("[WARN] Error setting ipv6_addresses for AWS Instance (%s): %s", d.Id(), err)
   688  	}
   689  
   690  	d.Set("ebs_optimized", instance.EbsOptimized)
   691  	if instance.SubnetId != nil && *instance.SubnetId != "" {
   692  		d.Set("source_dest_check", instance.SourceDestCheck)
   693  	}
   694  
   695  	if instance.Monitoring != nil && instance.Monitoring.State != nil {
   696  		monitoringState := *instance.Monitoring.State
   697  		d.Set("monitoring", monitoringState == "enabled" || monitoringState == "pending")
   698  	}
   699  
   700  	d.Set("tags", tagsToMap(instance.Tags))
   701  
   702  	if err := readVolumeTags(conn, d); err != nil {
   703  		return err
   704  	}
   705  
   706  	if err := readSecurityGroups(d, instance); err != nil {
   707  		return err
   708  	}
   709  
   710  	if err := readBlockDevices(d, instance, conn); err != nil {
   711  		return err
   712  	}
   713  	if _, ok := d.GetOk("ephemeral_block_device"); !ok {
   714  		d.Set("ephemeral_block_device", []interface{}{})
   715  	}
   716  
   717  	// Instance attributes
   718  	{
   719  		attr, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
   720  			Attribute:  aws.String("disableApiTermination"),
   721  			InstanceId: aws.String(d.Id()),
   722  		})
   723  		if err != nil {
   724  			return err
   725  		}
   726  		d.Set("disable_api_termination", attr.DisableApiTermination.Value)
   727  	}
   728  	{
   729  		attr, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
   730  			Attribute:  aws.String(ec2.InstanceAttributeNameUserData),
   731  			InstanceId: aws.String(d.Id()),
   732  		})
   733  		if err != nil {
   734  			return err
   735  		}
   736  		if attr.UserData.Value != nil {
   737  			d.Set("user_data", userDataHashSum(*attr.UserData.Value))
   738  		}
   739  	}
   740  
   741  	return nil
   742  }
   743  
   744  func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
   745  	conn := meta.(*AWSClient).ec2conn
   746  
   747  	d.Partial(true)
   748  
   749  	restricted := meta.(*AWSClient).IsGovCloud() || meta.(*AWSClient).IsChinaCloud()
   750  
   751  	if d.HasChange("tags") {
   752  		if !d.IsNewResource() || restricted {
   753  			if err := setTags(conn, d); err != nil {
   754  				return err
   755  			} else {
   756  				d.SetPartial("tags")
   757  			}
   758  		}
   759  	}
   760  	if d.HasChange("volume_tags") {
   761  		if !d.IsNewResource() || !restricted {
   762  			if err := setVolumeTags(conn, d); err != nil {
   763  				return err
   764  			} else {
   765  				d.SetPartial("volume_tags")
   766  			}
   767  		}
   768  	}
   769  
   770  	if d.HasChange("iam_instance_profile") && !d.IsNewResource() {
   771  		request := &ec2.DescribeIamInstanceProfileAssociationsInput{
   772  			Filters: []*ec2.Filter{
   773  				{
   774  					Name:   aws.String("instance-id"),
   775  					Values: []*string{aws.String(d.Id())},
   776  				},
   777  			},
   778  		}
   779  
   780  		resp, err := conn.DescribeIamInstanceProfileAssociations(request)
   781  		if err != nil {
   782  			return err
   783  		}
   784  
   785  		// An Iam Instance Profile has been provided and is pending a change
   786  		// This means it is an association or a replacement to an association
   787  		if _, ok := d.GetOk("iam_instance_profile"); ok {
   788  			// Does not have an Iam Instance Profile associated with it, need to associate
   789  			if len(resp.IamInstanceProfileAssociations) == 0 {
   790  				_, err := conn.AssociateIamInstanceProfile(&ec2.AssociateIamInstanceProfileInput{
   791  					InstanceId: aws.String(d.Id()),
   792  					IamInstanceProfile: &ec2.IamInstanceProfileSpecification{
   793  						Name: aws.String(d.Get("iam_instance_profile").(string)),
   794  					},
   795  				})
   796  				if err != nil {
   797  					return err
   798  				}
   799  
   800  			} else {
   801  				// Has an Iam Instance Profile associated with it, need to replace the association
   802  				associationId := resp.IamInstanceProfileAssociations[0].AssociationId
   803  
   804  				_, err := conn.ReplaceIamInstanceProfileAssociation(&ec2.ReplaceIamInstanceProfileAssociationInput{
   805  					AssociationId: associationId,
   806  					IamInstanceProfile: &ec2.IamInstanceProfileSpecification{
   807  						Name: aws.String(d.Get("iam_instance_profile").(string)),
   808  					},
   809  				})
   810  				if err != nil {
   811  					return err
   812  				}
   813  			}
   814  			// An Iam Instance Profile has _not_ been provided but is pending a change. This means there is a pending removal
   815  		} else {
   816  			if len(resp.IamInstanceProfileAssociations) > 0 {
   817  				// Has an Iam Instance Profile associated with it, need to remove the association
   818  				associationId := resp.IamInstanceProfileAssociations[0].AssociationId
   819  
   820  				_, err := conn.DisassociateIamInstanceProfile(&ec2.DisassociateIamInstanceProfileInput{
   821  					AssociationId: associationId,
   822  				})
   823  				if err != nil {
   824  					return err
   825  				}
   826  			}
   827  		}
   828  	}
   829  
   830  	// SourceDestCheck can only be modified on an instance without manually specified network interfaces.
   831  	// SourceDestCheck, in that case, is configured at the network interface level
   832  	if _, ok := d.GetOk("network_interface"); !ok {
   833  		if d.HasChange("source_dest_check") || d.IsNewResource() {
   834  			// SourceDestCheck can only be set on VPC instances	// AWS will return an error of InvalidParameterCombination if we attempt
   835  			// to modify the source_dest_check of an instance in EC2 Classic
   836  			log.Printf("[INFO] Modifying `source_dest_check` on Instance %s", d.Id())
   837  			_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   838  				InstanceId: aws.String(d.Id()),
   839  				SourceDestCheck: &ec2.AttributeBooleanValue{
   840  					Value: aws.Bool(d.Get("source_dest_check").(bool)),
   841  				},
   842  			})
   843  			if err != nil {
   844  				if ec2err, ok := err.(awserr.Error); ok {
   845  					// Tolerate InvalidParameterCombination error in Classic, otherwise
   846  					// return the error
   847  					if "InvalidParameterCombination" != ec2err.Code() {
   848  						return err
   849  					}
   850  					log.Printf("[WARN] Attempted to modify SourceDestCheck on non VPC instance: %s", ec2err.Message())
   851  				}
   852  			}
   853  		}
   854  	}
   855  
   856  	if d.HasChange("vpc_security_group_ids") {
   857  		var groups []*string
   858  		if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 {
   859  			for _, v := range v.List() {
   860  				groups = append(groups, aws.String(v.(string)))
   861  			}
   862  		}
   863  		// If a user has multiple network interface attachments on the target EC2 instance, simply modifying the
   864  		// instance attributes via a `ModifyInstanceAttributes()` request would fail with the following error message:
   865  		// "There are multiple interfaces attached to instance 'i-XX'. Please specify an interface ID for the operation instead."
   866  		// Thus, we need to actually modify the primary network interface for the new security groups, as the primary
   867  		// network interface is where we modify/create security group assignments during Create.
   868  		log.Printf("[INFO] Modifying `vpc_security_group_ids` on Instance %q", d.Id())
   869  		instances, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{
   870  			InstanceIds: []*string{aws.String(d.Id())},
   871  		})
   872  		if err != nil {
   873  			return err
   874  		}
   875  		instance := instances.Reservations[0].Instances[0]
   876  		var primaryInterface ec2.InstanceNetworkInterface
   877  		for _, ni := range instance.NetworkInterfaces {
   878  			if *ni.Attachment.DeviceIndex == 0 {
   879  				primaryInterface = *ni
   880  			}
   881  		}
   882  
   883  		if primaryInterface.NetworkInterfaceId == nil {
   884  			log.Print("[Error] Attempted to set vpc_security_group_ids on an instance without a primary network interface")
   885  			return fmt.Errorf(
   886  				"Failed to update vpc_security_group_ids on %q, which does not contain a primary network interface",
   887  				d.Id())
   888  		}
   889  
   890  		if _, err := conn.ModifyNetworkInterfaceAttribute(&ec2.ModifyNetworkInterfaceAttributeInput{
   891  			NetworkInterfaceId: primaryInterface.NetworkInterfaceId,
   892  			Groups:             groups,
   893  		}); err != nil {
   894  			return err
   895  		}
   896  	}
   897  
   898  	if d.HasChange("instance_type") && !d.IsNewResource() {
   899  		log.Printf("[INFO] Stopping Instance %q for instance_type change", d.Id())
   900  		_, err := conn.StopInstances(&ec2.StopInstancesInput{
   901  			InstanceIds: []*string{aws.String(d.Id())},
   902  		})
   903  
   904  		stateConf := &resource.StateChangeConf{
   905  			Pending:    []string{"pending", "running", "shutting-down", "stopped", "stopping"},
   906  			Target:     []string{"stopped"},
   907  			Refresh:    InstanceStateRefreshFunc(conn, d.Id(), ""),
   908  			Timeout:    d.Timeout(schema.TimeoutUpdate),
   909  			Delay:      10 * time.Second,
   910  			MinTimeout: 3 * time.Second,
   911  		}
   912  
   913  		_, err = stateConf.WaitForState()
   914  		if err != nil {
   915  			return fmt.Errorf(
   916  				"Error waiting for instance (%s) to stop: %s", d.Id(), err)
   917  		}
   918  
   919  		log.Printf("[INFO] Modifying instance type %s", d.Id())
   920  		_, err = conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   921  			InstanceId: aws.String(d.Id()),
   922  			InstanceType: &ec2.AttributeValue{
   923  				Value: aws.String(d.Get("instance_type").(string)),
   924  			},
   925  		})
   926  		if err != nil {
   927  			return err
   928  		}
   929  
   930  		log.Printf("[INFO] Starting Instance %q after instance_type change", d.Id())
   931  		_, err = conn.StartInstances(&ec2.StartInstancesInput{
   932  			InstanceIds: []*string{aws.String(d.Id())},
   933  		})
   934  
   935  		stateConf = &resource.StateChangeConf{
   936  			Pending:    []string{"pending", "stopped"},
   937  			Target:     []string{"running"},
   938  			Refresh:    InstanceStateRefreshFunc(conn, d.Id(), "terminated"),
   939  			Timeout:    d.Timeout(schema.TimeoutUpdate),
   940  			Delay:      10 * time.Second,
   941  			MinTimeout: 3 * time.Second,
   942  		}
   943  
   944  		_, err = stateConf.WaitForState()
   945  		if err != nil {
   946  			return fmt.Errorf(
   947  				"Error waiting for instance (%s) to become ready: %s",
   948  				d.Id(), err)
   949  		}
   950  	}
   951  
   952  	if d.HasChange("disable_api_termination") {
   953  		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   954  			InstanceId: aws.String(d.Id()),
   955  			DisableApiTermination: &ec2.AttributeBooleanValue{
   956  				Value: aws.Bool(d.Get("disable_api_termination").(bool)),
   957  			},
   958  		})
   959  		if err != nil {
   960  			return err
   961  		}
   962  	}
   963  
   964  	if d.HasChange("instance_initiated_shutdown_behavior") {
   965  		log.Printf("[INFO] Modifying instance %s", d.Id())
   966  		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   967  			InstanceId: aws.String(d.Id()),
   968  			InstanceInitiatedShutdownBehavior: &ec2.AttributeValue{
   969  				Value: aws.String(d.Get("instance_initiated_shutdown_behavior").(string)),
   970  			},
   971  		})
   972  		if err != nil {
   973  			return err
   974  		}
   975  	}
   976  
   977  	if d.HasChange("monitoring") {
   978  		var mErr error
   979  		if d.Get("monitoring").(bool) {
   980  			log.Printf("[DEBUG] Enabling monitoring for Instance (%s)", d.Id())
   981  			_, mErr = conn.MonitorInstances(&ec2.MonitorInstancesInput{
   982  				InstanceIds: []*string{aws.String(d.Id())},
   983  			})
   984  		} else {
   985  			log.Printf("[DEBUG] Disabling monitoring for Instance (%s)", d.Id())
   986  			_, mErr = conn.UnmonitorInstances(&ec2.UnmonitorInstancesInput{
   987  				InstanceIds: []*string{aws.String(d.Id())},
   988  			})
   989  		}
   990  		if mErr != nil {
   991  			return fmt.Errorf("[WARN] Error updating Instance monitoring: %s", mErr)
   992  		}
   993  	}
   994  
   995  	// TODO(mitchellh): wait for the attributes we modified to
   996  	// persist the change...
   997  
   998  	d.Partial(false)
   999  
  1000  	return resourceAwsInstanceRead(d, meta)
  1001  }
  1002  
  1003  func resourceAwsInstanceDelete(d *schema.ResourceData, meta interface{}) error {
  1004  	conn := meta.(*AWSClient).ec2conn
  1005  
  1006  	if err := awsTerminateInstance(conn, d.Id(), d); err != nil {
  1007  		return err
  1008  	}
  1009  
  1010  	d.SetId("")
  1011  	return nil
  1012  }
  1013  
  1014  // InstanceStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
  1015  // an EC2 instance.
  1016  func InstanceStateRefreshFunc(conn *ec2.EC2, instanceID, failState string) resource.StateRefreshFunc {
  1017  	return func() (interface{}, string, error) {
  1018  		resp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{
  1019  			InstanceIds: []*string{aws.String(instanceID)},
  1020  		})
  1021  		if err != nil {
  1022  			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" {
  1023  				// Set this to nil as if we didn't find anything.
  1024  				resp = nil
  1025  			} else {
  1026  				log.Printf("Error on InstanceStateRefresh: %s", err)
  1027  				return nil, "", err
  1028  			}
  1029  		}
  1030  
  1031  		if resp == nil || len(resp.Reservations) == 0 || len(resp.Reservations[0].Instances) == 0 {
  1032  			// Sometimes AWS just has consistency issues and doesn't see
  1033  			// our instance yet. Return an empty state.
  1034  			return nil, "", nil
  1035  		}
  1036  
  1037  		i := resp.Reservations[0].Instances[0]
  1038  		state := *i.State.Name
  1039  
  1040  		if state == failState {
  1041  			return i, state, fmt.Errorf("Failed to reach target state. Reason: %s",
  1042  				stringifyStateReason(i.StateReason))
  1043  
  1044  		}
  1045  
  1046  		return i, state, nil
  1047  	}
  1048  }
  1049  
  1050  func stringifyStateReason(sr *ec2.StateReason) string {
  1051  	if sr.Message != nil {
  1052  		return *sr.Message
  1053  	}
  1054  	if sr.Code != nil {
  1055  		return *sr.Code
  1056  	}
  1057  
  1058  	return sr.String()
  1059  }
  1060  
  1061  func readBlockDevices(d *schema.ResourceData, instance *ec2.Instance, conn *ec2.EC2) error {
  1062  	ibds, err := readBlockDevicesFromInstance(instance, conn)
  1063  	if err != nil {
  1064  		return err
  1065  	}
  1066  
  1067  	if err := d.Set("ebs_block_device", ibds["ebs"]); err != nil {
  1068  		return err
  1069  	}
  1070  
  1071  	// This handles the import case which needs to be defaulted to empty
  1072  	if _, ok := d.GetOk("root_block_device"); !ok {
  1073  		if err := d.Set("root_block_device", []interface{}{}); err != nil {
  1074  			return err
  1075  		}
  1076  	}
  1077  
  1078  	if ibds["root"] != nil {
  1079  		roots := []interface{}{ibds["root"]}
  1080  		if err := d.Set("root_block_device", roots); err != nil {
  1081  			return err
  1082  		}
  1083  	}
  1084  
  1085  	return nil
  1086  }
  1087  
  1088  func readBlockDevicesFromInstance(instance *ec2.Instance, conn *ec2.EC2) (map[string]interface{}, error) {
  1089  	blockDevices := make(map[string]interface{})
  1090  	blockDevices["ebs"] = make([]map[string]interface{}, 0)
  1091  	blockDevices["root"] = nil
  1092  
  1093  	instanceBlockDevices := make(map[string]*ec2.InstanceBlockDeviceMapping)
  1094  	for _, bd := range instance.BlockDeviceMappings {
  1095  		if bd.Ebs != nil {
  1096  			instanceBlockDevices[*bd.Ebs.VolumeId] = bd
  1097  		}
  1098  	}
  1099  
  1100  	if len(instanceBlockDevices) == 0 {
  1101  		return nil, nil
  1102  	}
  1103  
  1104  	volIDs := make([]*string, 0, len(instanceBlockDevices))
  1105  	for volID := range instanceBlockDevices {
  1106  		volIDs = append(volIDs, aws.String(volID))
  1107  	}
  1108  
  1109  	// Need to call DescribeVolumes to get volume_size and volume_type for each
  1110  	// EBS block device
  1111  	volResp, err := conn.DescribeVolumes(&ec2.DescribeVolumesInput{
  1112  		VolumeIds: volIDs,
  1113  	})
  1114  	if err != nil {
  1115  		return nil, err
  1116  	}
  1117  
  1118  	for _, vol := range volResp.Volumes {
  1119  		instanceBd := instanceBlockDevices[*vol.VolumeId]
  1120  		bd := make(map[string]interface{})
  1121  
  1122  		if instanceBd.Ebs != nil && instanceBd.Ebs.DeleteOnTermination != nil {
  1123  			bd["delete_on_termination"] = *instanceBd.Ebs.DeleteOnTermination
  1124  		}
  1125  		if vol.Size != nil {
  1126  			bd["volume_size"] = *vol.Size
  1127  		}
  1128  		if vol.VolumeType != nil {
  1129  			bd["volume_type"] = *vol.VolumeType
  1130  		}
  1131  		if vol.Iops != nil {
  1132  			bd["iops"] = *vol.Iops
  1133  		}
  1134  
  1135  		if blockDeviceIsRoot(instanceBd, instance) {
  1136  			blockDevices["root"] = bd
  1137  		} else {
  1138  			if instanceBd.DeviceName != nil {
  1139  				bd["device_name"] = *instanceBd.DeviceName
  1140  			}
  1141  			if vol.Encrypted != nil {
  1142  				bd["encrypted"] = *vol.Encrypted
  1143  			}
  1144  			if vol.SnapshotId != nil {
  1145  				bd["snapshot_id"] = *vol.SnapshotId
  1146  			}
  1147  
  1148  			blockDevices["ebs"] = append(blockDevices["ebs"].([]map[string]interface{}), bd)
  1149  		}
  1150  	}
  1151  
  1152  	return blockDevices, nil
  1153  }
  1154  
  1155  func blockDeviceIsRoot(bd *ec2.InstanceBlockDeviceMapping, instance *ec2.Instance) bool {
  1156  	return bd.DeviceName != nil &&
  1157  		instance.RootDeviceName != nil &&
  1158  		*bd.DeviceName == *instance.RootDeviceName
  1159  }
  1160  
  1161  func fetchRootDeviceName(ami string, conn *ec2.EC2) (*string, error) {
  1162  	if ami == "" {
  1163  		return nil, errors.New("Cannot fetch root device name for blank AMI ID.")
  1164  	}
  1165  
  1166  	log.Printf("[DEBUG] Describing AMI %q to get root block device name", ami)
  1167  	res, err := conn.DescribeImages(&ec2.DescribeImagesInput{
  1168  		ImageIds: []*string{aws.String(ami)},
  1169  	})
  1170  	if err != nil {
  1171  		return nil, err
  1172  	}
  1173  
  1174  	// For a bad image, we just return nil so we don't block a refresh
  1175  	if len(res.Images) == 0 {
  1176  		return nil, nil
  1177  	}
  1178  
  1179  	image := res.Images[0]
  1180  	rootDeviceName := image.RootDeviceName
  1181  
  1182  	// Instance store backed AMIs do not provide a root device name.
  1183  	if *image.RootDeviceType == ec2.DeviceTypeInstanceStore {
  1184  		return nil, nil
  1185  	}
  1186  
  1187  	// Some AMIs have a RootDeviceName like "/dev/sda1" that does not appear as a
  1188  	// DeviceName in the BlockDeviceMapping list (which will instead have
  1189  	// something like "/dev/sda")
  1190  	//
  1191  	// While this seems like it breaks an invariant of AMIs, it ends up working
  1192  	// on the AWS side, and AMIs like this are common enough that we need to
  1193  	// special case it so Terraform does the right thing.
  1194  	//
  1195  	// Our heuristic is: if the RootDeviceName does not appear in the
  1196  	// BlockDeviceMapping, assume that the DeviceName of the first
  1197  	// BlockDeviceMapping entry serves as the root device.
  1198  	rootDeviceNameInMapping := false
  1199  	for _, bdm := range image.BlockDeviceMappings {
  1200  		if bdm.DeviceName == image.RootDeviceName {
  1201  			rootDeviceNameInMapping = true
  1202  		}
  1203  	}
  1204  
  1205  	if !rootDeviceNameInMapping && len(image.BlockDeviceMappings) > 0 {
  1206  		rootDeviceName = image.BlockDeviceMappings[0].DeviceName
  1207  	}
  1208  
  1209  	if rootDeviceName == nil {
  1210  		return nil, fmt.Errorf("[WARN] Error finding Root Device Name for AMI (%s)", ami)
  1211  	}
  1212  
  1213  	return rootDeviceName, nil
  1214  }
  1215  
  1216  func buildNetworkInterfaceOpts(d *schema.ResourceData, groups []*string, nInterfaces interface{}) []*ec2.InstanceNetworkInterfaceSpecification {
  1217  	networkInterfaces := []*ec2.InstanceNetworkInterfaceSpecification{}
  1218  	// Get necessary items
  1219  	associatePublicIPAddress := d.Get("associate_public_ip_address").(bool)
  1220  	subnet, hasSubnet := d.GetOk("subnet_id")
  1221  
  1222  	if hasSubnet && associatePublicIPAddress {
  1223  		// If we have a non-default VPC / Subnet specified, we can flag
  1224  		// AssociatePublicIpAddress to get a Public IP assigned. By default these are not provided.
  1225  		// You cannot specify both SubnetId and the NetworkInterface.0.* parameters though, otherwise
  1226  		// you get: Network interfaces and an instance-level subnet ID may not be specified on the same request
  1227  		// You also need to attach Security Groups to the NetworkInterface instead of the instance,
  1228  		// to avoid: Network interfaces and an instance-level security groups may not be specified on
  1229  		// the same request
  1230  		ni := &ec2.InstanceNetworkInterfaceSpecification{
  1231  			AssociatePublicIpAddress: aws.Bool(associatePublicIPAddress),
  1232  			DeviceIndex:              aws.Int64(int64(0)),
  1233  			SubnetId:                 aws.String(subnet.(string)),
  1234  			Groups:                   groups,
  1235  		}
  1236  
  1237  		if v, ok := d.GetOk("private_ip"); ok {
  1238  			ni.PrivateIpAddress = aws.String(v.(string))
  1239  		}
  1240  
  1241  		if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 {
  1242  			for _, v := range v.List() {
  1243  				ni.Groups = append(ni.Groups, aws.String(v.(string)))
  1244  			}
  1245  		}
  1246  
  1247  		networkInterfaces = append(networkInterfaces, ni)
  1248  	} else {
  1249  		// If we have manually specified network interfaces, build and attach those here.
  1250  		vL := nInterfaces.(*schema.Set).List()
  1251  		for _, v := range vL {
  1252  			ini := v.(map[string]interface{})
  1253  			ni := &ec2.InstanceNetworkInterfaceSpecification{
  1254  				DeviceIndex:         aws.Int64(int64(ini["device_index"].(int))),
  1255  				NetworkInterfaceId:  aws.String(ini["network_interface_id"].(string)),
  1256  				DeleteOnTermination: aws.Bool(ini["delete_on_termination"].(bool)),
  1257  			}
  1258  			networkInterfaces = append(networkInterfaces, ni)
  1259  		}
  1260  	}
  1261  
  1262  	return networkInterfaces
  1263  }
  1264  
  1265  func readBlockDeviceMappingsFromConfig(
  1266  	d *schema.ResourceData, conn *ec2.EC2) ([]*ec2.BlockDeviceMapping, error) {
  1267  	blockDevices := make([]*ec2.BlockDeviceMapping, 0)
  1268  
  1269  	if v, ok := d.GetOk("ebs_block_device"); ok {
  1270  		vL := v.(*schema.Set).List()
  1271  		for _, v := range vL {
  1272  			bd := v.(map[string]interface{})
  1273  			ebs := &ec2.EbsBlockDevice{
  1274  				DeleteOnTermination: aws.Bool(bd["delete_on_termination"].(bool)),
  1275  			}
  1276  
  1277  			if v, ok := bd["snapshot_id"].(string); ok && v != "" {
  1278  				ebs.SnapshotId = aws.String(v)
  1279  			}
  1280  
  1281  			if v, ok := bd["encrypted"].(bool); ok && v {
  1282  				ebs.Encrypted = aws.Bool(v)
  1283  			}
  1284  
  1285  			if v, ok := bd["volume_size"].(int); ok && v != 0 {
  1286  				ebs.VolumeSize = aws.Int64(int64(v))
  1287  			}
  1288  
  1289  			if v, ok := bd["volume_type"].(string); ok && v != "" {
  1290  				ebs.VolumeType = aws.String(v)
  1291  				if "io1" == strings.ToLower(v) {
  1292  					// Condition: This parameter is required for requests to create io1
  1293  					// volumes; it is not used in requests to create gp2, st1, sc1, or
  1294  					// standard volumes.
  1295  					// See: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_EbsBlockDevice.html
  1296  					if v, ok := bd["iops"].(int); ok && v > 0 {
  1297  						ebs.Iops = aws.Int64(int64(v))
  1298  					}
  1299  				}
  1300  			}
  1301  
  1302  			blockDevices = append(blockDevices, &ec2.BlockDeviceMapping{
  1303  				DeviceName: aws.String(bd["device_name"].(string)),
  1304  				Ebs:        ebs,
  1305  			})
  1306  		}
  1307  	}
  1308  
  1309  	if v, ok := d.GetOk("ephemeral_block_device"); ok {
  1310  		vL := v.(*schema.Set).List()
  1311  		for _, v := range vL {
  1312  			bd := v.(map[string]interface{})
  1313  			bdm := &ec2.BlockDeviceMapping{
  1314  				DeviceName:  aws.String(bd["device_name"].(string)),
  1315  				VirtualName: aws.String(bd["virtual_name"].(string)),
  1316  			}
  1317  			if v, ok := bd["no_device"].(bool); ok && v {
  1318  				bdm.NoDevice = aws.String("")
  1319  				// When NoDevice is true, just ignore VirtualName since it's not needed
  1320  				bdm.VirtualName = nil
  1321  			}
  1322  
  1323  			if bdm.NoDevice == nil && aws.StringValue(bdm.VirtualName) == "" {
  1324  				return nil, errors.New("virtual_name cannot be empty when no_device is false or undefined.")
  1325  			}
  1326  
  1327  			blockDevices = append(blockDevices, bdm)
  1328  		}
  1329  	}
  1330  
  1331  	if v, ok := d.GetOk("root_block_device"); ok {
  1332  		vL := v.([]interface{})
  1333  		if len(vL) > 1 {
  1334  			return nil, errors.New("Cannot specify more than one root_block_device.")
  1335  		}
  1336  		for _, v := range vL {
  1337  			bd := v.(map[string]interface{})
  1338  			ebs := &ec2.EbsBlockDevice{
  1339  				DeleteOnTermination: aws.Bool(bd["delete_on_termination"].(bool)),
  1340  			}
  1341  
  1342  			if v, ok := bd["volume_size"].(int); ok && v != 0 {
  1343  				ebs.VolumeSize = aws.Int64(int64(v))
  1344  			}
  1345  
  1346  			if v, ok := bd["volume_type"].(string); ok && v != "" {
  1347  				ebs.VolumeType = aws.String(v)
  1348  			}
  1349  
  1350  			if v, ok := bd["iops"].(int); ok && v > 0 && *ebs.VolumeType == "io1" {
  1351  				// Only set the iops attribute if the volume type is io1. Setting otherwise
  1352  				// can trigger a refresh/plan loop based on the computed value that is given
  1353  				// from AWS, and prevent us from specifying 0 as a valid iops.
  1354  				//   See https://github.com/hashicorp/terraform/pull/4146
  1355  				//   See https://github.com/hashicorp/terraform/issues/7765
  1356  				ebs.Iops = aws.Int64(int64(v))
  1357  			} else if v, ok := bd["iops"].(int); ok && v > 0 && *ebs.VolumeType != "io1" {
  1358  				// Message user about incompatibility
  1359  				log.Print("[WARN] IOPs is only valid for storate type io1 for EBS Volumes")
  1360  			}
  1361  
  1362  			if dn, err := fetchRootDeviceName(d.Get("ami").(string), conn); err == nil {
  1363  				if dn == nil {
  1364  					return nil, fmt.Errorf(
  1365  						"Expected 1 AMI for ID: %s, got none",
  1366  						d.Get("ami").(string))
  1367  				}
  1368  
  1369  				blockDevices = append(blockDevices, &ec2.BlockDeviceMapping{
  1370  					DeviceName: dn,
  1371  					Ebs:        ebs,
  1372  				})
  1373  			} else {
  1374  				return nil, err
  1375  			}
  1376  		}
  1377  	}
  1378  
  1379  	return blockDevices, nil
  1380  }
  1381  
  1382  func readVolumeTags(conn *ec2.EC2, d *schema.ResourceData) error {
  1383  	volumeIds, err := getAwsInstanceVolumeIds(conn, d)
  1384  	if err != nil {
  1385  		return err
  1386  	}
  1387  
  1388  	tagsResp, err := conn.DescribeTags(&ec2.DescribeTagsInput{
  1389  		Filters: []*ec2.Filter{
  1390  			{
  1391  				Name:   aws.String("resource-id"),
  1392  				Values: volumeIds,
  1393  			},
  1394  		},
  1395  	})
  1396  	if err != nil {
  1397  		return err
  1398  	}
  1399  
  1400  	var tags []*ec2.Tag
  1401  
  1402  	for _, t := range tagsResp.Tags {
  1403  		tag := &ec2.Tag{
  1404  			Key:   t.Key,
  1405  			Value: t.Value,
  1406  		}
  1407  		tags = append(tags, tag)
  1408  	}
  1409  
  1410  	d.Set("volume_tags", tagsToMap(tags))
  1411  
  1412  	return nil
  1413  }
  1414  
  1415  // Determine whether we're referring to security groups with
  1416  // IDs or names. We use a heuristic to figure this out. By default,
  1417  // we use IDs if we're in a VPC. However, if we previously had an
  1418  // all-name list of security groups, we use names. Or, if we had any
  1419  // IDs, we use IDs.
  1420  func readSecurityGroups(d *schema.ResourceData, instance *ec2.Instance) error {
  1421  	useID := instance.SubnetId != nil && *instance.SubnetId != ""
  1422  	if v := d.Get("security_groups"); v != nil {
  1423  		match := useID
  1424  		sgs := v.(*schema.Set).List()
  1425  		if len(sgs) > 0 {
  1426  			match = false
  1427  			for _, v := range v.(*schema.Set).List() {
  1428  				if strings.HasPrefix(v.(string), "sg-") {
  1429  					match = true
  1430  					break
  1431  				}
  1432  			}
  1433  		}
  1434  
  1435  		useID = match
  1436  	}
  1437  
  1438  	// Build up the security groups
  1439  	sgs := make([]string, 0, len(instance.SecurityGroups))
  1440  	if useID {
  1441  		for _, sg := range instance.SecurityGroups {
  1442  			sgs = append(sgs, *sg.GroupId)
  1443  		}
  1444  		log.Printf("[DEBUG] Setting Security Group IDs: %#v", sgs)
  1445  		if err := d.Set("vpc_security_group_ids", sgs); err != nil {
  1446  			return err
  1447  		}
  1448  		if err := d.Set("security_groups", []string{}); err != nil {
  1449  			return err
  1450  		}
  1451  	} else {
  1452  		for _, sg := range instance.SecurityGroups {
  1453  			sgs = append(sgs, *sg.GroupName)
  1454  		}
  1455  		log.Printf("[DEBUG] Setting Security Group Names: %#v", sgs)
  1456  		if err := d.Set("security_groups", sgs); err != nil {
  1457  			return err
  1458  		}
  1459  		if err := d.Set("vpc_security_group_ids", []string{}); err != nil {
  1460  			return err
  1461  		}
  1462  	}
  1463  	return nil
  1464  }
  1465  
  1466  type awsInstanceOpts struct {
  1467  	BlockDeviceMappings               []*ec2.BlockDeviceMapping
  1468  	DisableAPITermination             *bool
  1469  	EBSOptimized                      *bool
  1470  	Monitoring                        *ec2.RunInstancesMonitoringEnabled
  1471  	IAMInstanceProfile                *ec2.IamInstanceProfileSpecification
  1472  	ImageID                           *string
  1473  	InstanceInitiatedShutdownBehavior *string
  1474  	InstanceType                      *string
  1475  	KeyName                           *string
  1476  	NetworkInterfaces                 []*ec2.InstanceNetworkInterfaceSpecification
  1477  	Placement                         *ec2.Placement
  1478  	PrivateIPAddress                  *string
  1479  	SecurityGroupIDs                  []*string
  1480  	SecurityGroups                    []*string
  1481  	SpotPlacement                     *ec2.SpotPlacement
  1482  	SubnetID                          *string
  1483  	UserData64                        *string
  1484  }
  1485  
  1486  func buildAwsInstanceOpts(
  1487  	d *schema.ResourceData, meta interface{}) (*awsInstanceOpts, error) {
  1488  	conn := meta.(*AWSClient).ec2conn
  1489  
  1490  	opts := &awsInstanceOpts{
  1491  		DisableAPITermination: aws.Bool(d.Get("disable_api_termination").(bool)),
  1492  		EBSOptimized:          aws.Bool(d.Get("ebs_optimized").(bool)),
  1493  		ImageID:               aws.String(d.Get("ami").(string)),
  1494  		InstanceType:          aws.String(d.Get("instance_type").(string)),
  1495  	}
  1496  
  1497  	if v := d.Get("instance_initiated_shutdown_behavior").(string); v != "" {
  1498  		opts.InstanceInitiatedShutdownBehavior = aws.String(v)
  1499  	}
  1500  
  1501  	opts.Monitoring = &ec2.RunInstancesMonitoringEnabled{
  1502  		Enabled: aws.Bool(d.Get("monitoring").(bool)),
  1503  	}
  1504  
  1505  	opts.IAMInstanceProfile = &ec2.IamInstanceProfileSpecification{
  1506  		Name: aws.String(d.Get("iam_instance_profile").(string)),
  1507  	}
  1508  
  1509  	user_data := d.Get("user_data").(string)
  1510  
  1511  	opts.UserData64 = aws.String(base64Encode([]byte(user_data)))
  1512  
  1513  	// check for non-default Subnet, and cast it to a String
  1514  	subnet, hasSubnet := d.GetOk("subnet_id")
  1515  	subnetID := subnet.(string)
  1516  
  1517  	// Placement is used for aws_instance; SpotPlacement is used for
  1518  	// aws_spot_instance_request. They represent the same data. :-|
  1519  	opts.Placement = &ec2.Placement{
  1520  		AvailabilityZone: aws.String(d.Get("availability_zone").(string)),
  1521  		GroupName:        aws.String(d.Get("placement_group").(string)),
  1522  	}
  1523  
  1524  	opts.SpotPlacement = &ec2.SpotPlacement{
  1525  		AvailabilityZone: aws.String(d.Get("availability_zone").(string)),
  1526  		GroupName:        aws.String(d.Get("placement_group").(string)),
  1527  	}
  1528  
  1529  	if v := d.Get("tenancy").(string); v != "" {
  1530  		opts.Placement.Tenancy = aws.String(v)
  1531  	}
  1532  
  1533  	associatePublicIPAddress := d.Get("associate_public_ip_address").(bool)
  1534  
  1535  	var groups []*string
  1536  	if v := d.Get("security_groups"); v != nil {
  1537  		// Security group names.
  1538  		// For a nondefault VPC, you must use security group IDs instead.
  1539  		// See http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html
  1540  		sgs := v.(*schema.Set).List()
  1541  		if len(sgs) > 0 && hasSubnet {
  1542  			log.Print("[WARN] Deprecated. Attempting to use 'security_groups' within a VPC instance. Use 'vpc_security_group_ids' instead.")
  1543  		}
  1544  		for _, v := range sgs {
  1545  			str := v.(string)
  1546  			groups = append(groups, aws.String(str))
  1547  		}
  1548  	}
  1549  
  1550  	networkInterfaces, interfacesOk := d.GetOk("network_interface")
  1551  
  1552  	// If setting subnet and public address, OR manual network interfaces, populate those now.
  1553  	if hasSubnet && associatePublicIPAddress || interfacesOk {
  1554  		// Otherwise we're attaching (a) network interface(s)
  1555  		opts.NetworkInterfaces = buildNetworkInterfaceOpts(d, groups, networkInterfaces)
  1556  	} else {
  1557  		// If simply specifying a subnetID, privateIP, Security Groups, or VPC Security Groups, build these now
  1558  		if subnetID != "" {
  1559  			opts.SubnetID = aws.String(subnetID)
  1560  		}
  1561  
  1562  		if v, ok := d.GetOk("private_ip"); ok {
  1563  			opts.PrivateIPAddress = aws.String(v.(string))
  1564  		}
  1565  		if opts.SubnetID != nil &&
  1566  			*opts.SubnetID != "" {
  1567  			opts.SecurityGroupIDs = groups
  1568  		} else {
  1569  			opts.SecurityGroups = groups
  1570  		}
  1571  
  1572  		if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 {
  1573  			for _, v := range v.List() {
  1574  				opts.SecurityGroupIDs = append(opts.SecurityGroupIDs, aws.String(v.(string)))
  1575  			}
  1576  		}
  1577  	}
  1578  
  1579  	if v, ok := d.GetOk("key_name"); ok {
  1580  		opts.KeyName = aws.String(v.(string))
  1581  	}
  1582  
  1583  	blockDevices, err := readBlockDeviceMappingsFromConfig(d, conn)
  1584  	if err != nil {
  1585  		return nil, err
  1586  	}
  1587  	if len(blockDevices) > 0 {
  1588  		opts.BlockDeviceMappings = blockDevices
  1589  	}
  1590  	return opts, nil
  1591  }
  1592  
  1593  func awsTerminateInstance(conn *ec2.EC2, id string, d *schema.ResourceData) error {
  1594  	log.Printf("[INFO] Terminating instance: %s", id)
  1595  	req := &ec2.TerminateInstancesInput{
  1596  		InstanceIds: []*string{aws.String(id)},
  1597  	}
  1598  	if _, err := conn.TerminateInstances(req); err != nil {
  1599  		return fmt.Errorf("Error terminating instance: %s", err)
  1600  	}
  1601  
  1602  	log.Printf("[DEBUG] Waiting for instance (%s) to become terminated", id)
  1603  
  1604  	stateConf := &resource.StateChangeConf{
  1605  		Pending:    []string{"pending", "running", "shutting-down", "stopped", "stopping"},
  1606  		Target:     []string{"terminated"},
  1607  		Refresh:    InstanceStateRefreshFunc(conn, id, ""),
  1608  		Timeout:    d.Timeout(schema.TimeoutDelete),
  1609  		Delay:      10 * time.Second,
  1610  		MinTimeout: 3 * time.Second,
  1611  	}
  1612  
  1613  	_, err := stateConf.WaitForState()
  1614  	if err != nil {
  1615  		return fmt.Errorf(
  1616  			"Error waiting for instance (%s) to terminate: %s", id, err)
  1617  	}
  1618  
  1619  	return nil
  1620  }
  1621  
  1622  func iamInstanceProfileArnToName(ip *ec2.IamInstanceProfile) string {
  1623  	if ip == nil || ip.Arn == nil {
  1624  		return ""
  1625  	}
  1626  	parts := strings.Split(*ip.Arn, "/")
  1627  	return parts[len(parts)-1]
  1628  }
  1629  
  1630  func userDataHashSum(user_data string) string {
  1631  	// Check whether the user_data is not Base64 encoded.
  1632  	// Always calculate hash of base64 decoded value since we
  1633  	// check against double-encoding when setting it
  1634  	v, base64DecodeError := base64.StdEncoding.DecodeString(user_data)
  1635  	if base64DecodeError != nil {
  1636  		v = []byte(user_data)
  1637  	}
  1638  
  1639  	hash := sha1.Sum(v)
  1640  	return hex.EncodeToString(hash[:])
  1641  }
  1642  
  1643  func getAwsInstanceVolumeIds(conn *ec2.EC2, d *schema.ResourceData) ([]*string, error) {
  1644  	volumeIds := make([]*string, 0)
  1645  
  1646  	opts := &ec2.DescribeVolumesInput{
  1647  		Filters: []*ec2.Filter{
  1648  			{
  1649  				Name:   aws.String("attachment.instance-id"),
  1650  				Values: []*string{aws.String(d.Id())},
  1651  			},
  1652  		},
  1653  	}
  1654  
  1655  	resp, err := conn.DescribeVolumes(opts)
  1656  	if err != nil {
  1657  		return nil, err
  1658  	}
  1659  
  1660  	for _, v := range resp.Volumes {
  1661  		volumeIds = append(volumeIds, v.VolumeId)
  1662  	}
  1663  
  1664  	return volumeIds, nil
  1665  }