github.com/recobe182/terraform@v0.8.5-0.20170117231232-49ab22a935b7/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  	"fmt"
     9  	"log"
    10  	"strings"
    11  	"time"
    12  
    13  	"github.com/aws/aws-sdk-go/aws"
    14  	"github.com/aws/aws-sdk-go/aws/awserr"
    15  	"github.com/aws/aws-sdk-go/service/ec2"
    16  	"github.com/hashicorp/terraform/helper/hashcode"
    17  	"github.com/hashicorp/terraform/helper/resource"
    18  	"github.com/hashicorp/terraform/helper/schema"
    19  )
    20  
    21  func resourceAwsInstance() *schema.Resource {
    22  	return &schema.Resource{
    23  		Create: resourceAwsInstanceCreate,
    24  		Read:   resourceAwsInstanceRead,
    25  		Update: resourceAwsInstanceUpdate,
    26  		Delete: resourceAwsInstanceDelete,
    27  		Importer: &schema.ResourceImporter{
    28  			State: schema.ImportStatePassthrough,
    29  		},
    30  
    31  		SchemaVersion: 1,
    32  		MigrateState:  resourceAwsInstanceMigrateState,
    33  
    34  		Schema: map[string]*schema.Schema{
    35  			"ami": &schema.Schema{
    36  				Type:     schema.TypeString,
    37  				Required: true,
    38  				ForceNew: true,
    39  			},
    40  
    41  			"associate_public_ip_address": &schema.Schema{
    42  				Type:     schema.TypeBool,
    43  				ForceNew: true,
    44  				Computed: true,
    45  				Optional: true,
    46  			},
    47  
    48  			"availability_zone": &schema.Schema{
    49  				Type:     schema.TypeString,
    50  				Optional: true,
    51  				Computed: true,
    52  				ForceNew: true,
    53  			},
    54  
    55  			"placement_group": &schema.Schema{
    56  				Type:     schema.TypeString,
    57  				Optional: true,
    58  				Computed: true,
    59  				ForceNew: true,
    60  			},
    61  
    62  			"instance_type": &schema.Schema{
    63  				Type:     schema.TypeString,
    64  				Required: true,
    65  				ForceNew: true,
    66  			},
    67  
    68  			"key_name": &schema.Schema{
    69  				Type:     schema.TypeString,
    70  				Optional: true,
    71  				ForceNew: true,
    72  				Computed: true,
    73  			},
    74  
    75  			"subnet_id": &schema.Schema{
    76  				Type:     schema.TypeString,
    77  				Optional: true,
    78  				Computed: true,
    79  				ForceNew: true,
    80  			},
    81  
    82  			"private_ip": &schema.Schema{
    83  				Type:     schema.TypeString,
    84  				Optional: true,
    85  				ForceNew: true,
    86  				Computed: true,
    87  			},
    88  
    89  			"source_dest_check": &schema.Schema{
    90  				Type:     schema.TypeBool,
    91  				Optional: true,
    92  				Default:  true,
    93  			},
    94  
    95  			"user_data": &schema.Schema{
    96  				Type:     schema.TypeString,
    97  				Optional: true,
    98  				ForceNew: true,
    99  				StateFunc: func(v interface{}) string {
   100  					switch v.(type) {
   101  					case string:
   102  						return userDataHashSum(v.(string))
   103  					default:
   104  						return ""
   105  					}
   106  				},
   107  			},
   108  
   109  			"security_groups": &schema.Schema{
   110  				Type:     schema.TypeSet,
   111  				Optional: true,
   112  				Computed: true,
   113  				ForceNew: true,
   114  				Elem:     &schema.Schema{Type: schema.TypeString},
   115  				Set:      schema.HashString,
   116  			},
   117  
   118  			"vpc_security_group_ids": &schema.Schema{
   119  				Type:     schema.TypeSet,
   120  				Optional: true,
   121  				Computed: true,
   122  				Elem:     &schema.Schema{Type: schema.TypeString},
   123  				Set:      schema.HashString,
   124  			},
   125  
   126  			"public_dns": &schema.Schema{
   127  				Type:     schema.TypeString,
   128  				Computed: true,
   129  			},
   130  
   131  			"network_interface_id": &schema.Schema{
   132  				Type:     schema.TypeString,
   133  				Computed: true,
   134  			},
   135  
   136  			"public_ip": &schema.Schema{
   137  				Type:     schema.TypeString,
   138  				Computed: true,
   139  			},
   140  
   141  			"instance_state": &schema.Schema{
   142  				Type:     schema.TypeString,
   143  				Computed: true,
   144  			},
   145  
   146  			"private_dns": &schema.Schema{
   147  				Type:     schema.TypeString,
   148  				Computed: true,
   149  			},
   150  
   151  			"ebs_optimized": &schema.Schema{
   152  				Type:     schema.TypeBool,
   153  				Optional: true,
   154  				ForceNew: true,
   155  			},
   156  
   157  			"disable_api_termination": &schema.Schema{
   158  				Type:     schema.TypeBool,
   159  				Optional: true,
   160  			},
   161  
   162  			"instance_initiated_shutdown_behavior": &schema.Schema{
   163  				Type:     schema.TypeString,
   164  				Optional: true,
   165  			},
   166  
   167  			"monitoring": &schema.Schema{
   168  				Type:     schema.TypeBool,
   169  				Optional: true,
   170  			},
   171  
   172  			"iam_instance_profile": &schema.Schema{
   173  				Type:     schema.TypeString,
   174  				ForceNew: true,
   175  				Optional: true,
   176  			},
   177  
   178  			"tenancy": &schema.Schema{
   179  				Type:     schema.TypeString,
   180  				Optional: true,
   181  				Computed: true,
   182  				ForceNew: true,
   183  			},
   184  
   185  			"tags": tagsSchema(),
   186  
   187  			"block_device": &schema.Schema{
   188  				Type:     schema.TypeMap,
   189  				Optional: true,
   190  				Removed:  "Split out into three sub-types; see Changelog and Docs",
   191  			},
   192  
   193  			"ebs_block_device": &schema.Schema{
   194  				Type:     schema.TypeSet,
   195  				Optional: true,
   196  				Computed: true,
   197  				Elem: &schema.Resource{
   198  					Schema: map[string]*schema.Schema{
   199  						"delete_on_termination": &schema.Schema{
   200  							Type:     schema.TypeBool,
   201  							Optional: true,
   202  							Default:  true,
   203  							ForceNew: true,
   204  						},
   205  
   206  						"device_name": &schema.Schema{
   207  							Type:     schema.TypeString,
   208  							Required: true,
   209  							ForceNew: true,
   210  						},
   211  
   212  						"encrypted": &schema.Schema{
   213  							Type:     schema.TypeBool,
   214  							Optional: true,
   215  							Computed: true,
   216  							ForceNew: true,
   217  						},
   218  
   219  						"iops": &schema.Schema{
   220  							Type:     schema.TypeInt,
   221  							Optional: true,
   222  							Computed: true,
   223  							ForceNew: true,
   224  						},
   225  
   226  						"snapshot_id": &schema.Schema{
   227  							Type:     schema.TypeString,
   228  							Optional: true,
   229  							Computed: true,
   230  							ForceNew: true,
   231  						},
   232  
   233  						"volume_size": &schema.Schema{
   234  							Type:     schema.TypeInt,
   235  							Optional: true,
   236  							Computed: true,
   237  							ForceNew: true,
   238  						},
   239  
   240  						"volume_type": &schema.Schema{
   241  							Type:     schema.TypeString,
   242  							Optional: true,
   243  							Computed: true,
   244  							ForceNew: true,
   245  						},
   246  					},
   247  				},
   248  				Set: func(v interface{}) int {
   249  					var buf bytes.Buffer
   250  					m := v.(map[string]interface{})
   251  					buf.WriteString(fmt.Sprintf("%s-", m["device_name"].(string)))
   252  					buf.WriteString(fmt.Sprintf("%s-", m["snapshot_id"].(string)))
   253  					return hashcode.String(buf.String())
   254  				},
   255  			},
   256  
   257  			"ephemeral_block_device": &schema.Schema{
   258  				Type:     schema.TypeSet,
   259  				Optional: true,
   260  				Computed: true,
   261  				ForceNew: true,
   262  				Elem: &schema.Resource{
   263  					Schema: map[string]*schema.Schema{
   264  						"device_name": &schema.Schema{
   265  							Type:     schema.TypeString,
   266  							Required: true,
   267  						},
   268  
   269  						"virtual_name": &schema.Schema{
   270  							Type:     schema.TypeString,
   271  							Optional: true,
   272  						},
   273  
   274  						"no_device": &schema.Schema{
   275  							Type:     schema.TypeBool,
   276  							Optional: true,
   277  						},
   278  					},
   279  				},
   280  				Set: func(v interface{}) int {
   281  					var buf bytes.Buffer
   282  					m := v.(map[string]interface{})
   283  					buf.WriteString(fmt.Sprintf("%s-", m["device_name"].(string)))
   284  					buf.WriteString(fmt.Sprintf("%s-", m["virtual_name"].(string)))
   285  					if v, ok := m["no_device"].(bool); ok && v {
   286  						buf.WriteString(fmt.Sprintf("%t-", v))
   287  					}
   288  					return hashcode.String(buf.String())
   289  				},
   290  			},
   291  
   292  			"root_block_device": &schema.Schema{
   293  				// TODO: This is a set because we don't support singleton
   294  				//       sub-resources today. We'll enforce that the set only ever has
   295  				//       length zero or one below. When TF gains support for
   296  				//       sub-resources this can be converted.
   297  				Type:     schema.TypeSet,
   298  				Optional: true,
   299  				Computed: true,
   300  				Elem: &schema.Resource{
   301  					// "You can only modify the volume size, volume type, and Delete on
   302  					// Termination flag on the block device mapping entry for the root
   303  					// device volume." - bit.ly/ec2bdmap
   304  					Schema: map[string]*schema.Schema{
   305  						"delete_on_termination": &schema.Schema{
   306  							Type:     schema.TypeBool,
   307  							Optional: true,
   308  							Default:  true,
   309  							ForceNew: true,
   310  						},
   311  
   312  						"iops": &schema.Schema{
   313  							Type:     schema.TypeInt,
   314  							Optional: true,
   315  							Computed: true,
   316  							ForceNew: true,
   317  						},
   318  
   319  						"volume_size": &schema.Schema{
   320  							Type:     schema.TypeInt,
   321  							Optional: true,
   322  							Computed: true,
   323  							ForceNew: true,
   324  						},
   325  
   326  						"volume_type": &schema.Schema{
   327  							Type:     schema.TypeString,
   328  							Optional: true,
   329  							Computed: true,
   330  							ForceNew: true,
   331  						},
   332  					},
   333  				},
   334  				Set: func(v interface{}) int {
   335  					// there can be only one root device; no need to hash anything
   336  					return 0
   337  				},
   338  			},
   339  		},
   340  	}
   341  }
   342  
   343  func resourceAwsInstanceCreate(d *schema.ResourceData, meta interface{}) error {
   344  	conn := meta.(*AWSClient).ec2conn
   345  
   346  	instanceOpts, err := buildAwsInstanceOpts(d, meta)
   347  	if err != nil {
   348  		return err
   349  	}
   350  
   351  	// Build the creation struct
   352  	runOpts := &ec2.RunInstancesInput{
   353  		BlockDeviceMappings:   instanceOpts.BlockDeviceMappings,
   354  		DisableApiTermination: instanceOpts.DisableAPITermination,
   355  		EbsOptimized:          instanceOpts.EBSOptimized,
   356  		Monitoring:            instanceOpts.Monitoring,
   357  		IamInstanceProfile:    instanceOpts.IAMInstanceProfile,
   358  		ImageId:               instanceOpts.ImageID,
   359  		InstanceInitiatedShutdownBehavior: instanceOpts.InstanceInitiatedShutdownBehavior,
   360  		InstanceType:                      instanceOpts.InstanceType,
   361  		KeyName:                           instanceOpts.KeyName,
   362  		MaxCount:                          aws.Int64(int64(1)),
   363  		MinCount:                          aws.Int64(int64(1)),
   364  		NetworkInterfaces:                 instanceOpts.NetworkInterfaces,
   365  		Placement:                         instanceOpts.Placement,
   366  		PrivateIpAddress:                  instanceOpts.PrivateIPAddress,
   367  		SecurityGroupIds:                  instanceOpts.SecurityGroupIDs,
   368  		SecurityGroups:                    instanceOpts.SecurityGroups,
   369  		SubnetId:                          instanceOpts.SubnetID,
   370  		UserData:                          instanceOpts.UserData64,
   371  	}
   372  
   373  	// Create the instance
   374  	log.Printf("[DEBUG] Run configuration: %s", runOpts)
   375  
   376  	var runResp *ec2.Reservation
   377  	err = resource.Retry(15*time.Second, func() *resource.RetryError {
   378  		var err error
   379  		runResp, err = conn.RunInstances(runOpts)
   380  		// IAM instance profiles can take ~10 seconds to propagate in AWS:
   381  		// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console
   382  		if isAWSErr(err, "InvalidParameterValue", "Invalid IAM Instance Profile") {
   383  			log.Printf("[DEBUG] Invalid IAM Instance Profile referenced, retrying...")
   384  			return resource.RetryableError(err)
   385  		}
   386  		// IAM roles can also take time to propagate in AWS:
   387  		if isAWSErr(err, "InvalidParameterValue", " has no associated IAM Roles") {
   388  			log.Printf("[DEBUG] IAM Instance Profile appears to have no IAM roles, retrying...")
   389  			return resource.RetryableError(err)
   390  		}
   391  		return resource.NonRetryableError(err)
   392  	})
   393  	// Warn if the AWS Error involves group ids, to help identify situation
   394  	// where a user uses group ids in security_groups for the Default VPC.
   395  	//   See https://github.com/hashicorp/terraform/issues/3798
   396  	if isAWSErr(err, "InvalidParameterValue", "groupId is invalid") {
   397  		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())
   398  	}
   399  	if err != nil {
   400  		return fmt.Errorf("Error launching source instance: %s", err)
   401  	}
   402  	if runResp == nil || len(runResp.Instances) == 0 {
   403  		return fmt.Errorf("Error launching source instance: no instances returned in response")
   404  	}
   405  
   406  	instance := runResp.Instances[0]
   407  	log.Printf("[INFO] Instance ID: %s", *instance.InstanceId)
   408  
   409  	// Store the resulting ID so we can look this up later
   410  	d.SetId(*instance.InstanceId)
   411  
   412  	// Wait for the instance to become running so we can get some attributes
   413  	// that aren't available until later.
   414  	log.Printf(
   415  		"[DEBUG] Waiting for instance (%s) to become running",
   416  		*instance.InstanceId)
   417  
   418  	stateConf := &resource.StateChangeConf{
   419  		Pending:    []string{"pending"},
   420  		Target:     []string{"running"},
   421  		Refresh:    InstanceStateRefreshFunc(conn, *instance.InstanceId),
   422  		Timeout:    10 * time.Minute,
   423  		Delay:      10 * time.Second,
   424  		MinTimeout: 3 * time.Second,
   425  	}
   426  
   427  	instanceRaw, err := stateConf.WaitForState()
   428  	if err != nil {
   429  		return fmt.Errorf(
   430  			"Error waiting for instance (%s) to become ready: %s",
   431  			*instance.InstanceId, err)
   432  	}
   433  
   434  	instance = instanceRaw.(*ec2.Instance)
   435  
   436  	// Initialize the connection info
   437  	if instance.PublicIpAddress != nil {
   438  		d.SetConnInfo(map[string]string{
   439  			"type": "ssh",
   440  			"host": *instance.PublicIpAddress,
   441  		})
   442  	} else if instance.PrivateIpAddress != nil {
   443  		d.SetConnInfo(map[string]string{
   444  			"type": "ssh",
   445  			"host": *instance.PrivateIpAddress,
   446  		})
   447  	}
   448  
   449  	// Update if we need to
   450  	return resourceAwsInstanceUpdate(d, meta)
   451  }
   452  
   453  func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error {
   454  	conn := meta.(*AWSClient).ec2conn
   455  
   456  	resp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{
   457  		InstanceIds: []*string{aws.String(d.Id())},
   458  	})
   459  	if err != nil {
   460  		// If the instance was not found, return nil so that we can show
   461  		// that the instance is gone.
   462  		if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" {
   463  			d.SetId("")
   464  			return nil
   465  		}
   466  
   467  		// Some other error, report it
   468  		return err
   469  	}
   470  
   471  	// If nothing was found, then return no state
   472  	if len(resp.Reservations) == 0 {
   473  		d.SetId("")
   474  		return nil
   475  	}
   476  
   477  	instance := resp.Reservations[0].Instances[0]
   478  
   479  	if instance.State != nil {
   480  		// If the instance is terminated, then it is gone
   481  		if *instance.State.Name == "terminated" {
   482  			d.SetId("")
   483  			return nil
   484  		}
   485  
   486  		d.Set("instance_state", instance.State.Name)
   487  	}
   488  
   489  	if instance.Placement != nil {
   490  		d.Set("availability_zone", instance.Placement.AvailabilityZone)
   491  	}
   492  	if instance.Placement.Tenancy != nil {
   493  		d.Set("tenancy", instance.Placement.Tenancy)
   494  	}
   495  
   496  	d.Set("ami", instance.ImageId)
   497  	d.Set("instance_type", instance.InstanceType)
   498  	d.Set("key_name", instance.KeyName)
   499  	d.Set("public_dns", instance.PublicDnsName)
   500  	d.Set("public_ip", instance.PublicIpAddress)
   501  	d.Set("private_dns", instance.PrivateDnsName)
   502  	d.Set("private_ip", instance.PrivateIpAddress)
   503  	d.Set("iam_instance_profile", iamInstanceProfileArnToName(instance.IamInstanceProfile))
   504  
   505  	if len(instance.NetworkInterfaces) > 0 {
   506  		for _, ni := range instance.NetworkInterfaces {
   507  			if *ni.Attachment.DeviceIndex == 0 {
   508  				d.Set("subnet_id", ni.SubnetId)
   509  				d.Set("network_interface_id", ni.NetworkInterfaceId)
   510  				d.Set("associate_public_ip_address", ni.Association != nil)
   511  			}
   512  		}
   513  	} else {
   514  		d.Set("subnet_id", instance.SubnetId)
   515  		d.Set("network_interface_id", "")
   516  	}
   517  	d.Set("ebs_optimized", instance.EbsOptimized)
   518  	if instance.SubnetId != nil && *instance.SubnetId != "" {
   519  		d.Set("source_dest_check", instance.SourceDestCheck)
   520  	}
   521  
   522  	if instance.Monitoring != nil && instance.Monitoring.State != nil {
   523  		monitoringState := *instance.Monitoring.State
   524  		d.Set("monitoring", monitoringState == "enabled" || monitoringState == "pending")
   525  	}
   526  
   527  	d.Set("tags", tagsToMap(instance.Tags))
   528  
   529  	// Determine whether we're referring to security groups with
   530  	// IDs or names. We use a heuristic to figure this out. By default,
   531  	// we use IDs if we're in a VPC. However, if we previously had an
   532  	// all-name list of security groups, we use names. Or, if we had any
   533  	// IDs, we use IDs.
   534  	useID := instance.SubnetId != nil && *instance.SubnetId != ""
   535  	if v := d.Get("security_groups"); v != nil {
   536  		match := useID
   537  		sgs := v.(*schema.Set).List()
   538  		if len(sgs) > 0 {
   539  			match = false
   540  			for _, v := range v.(*schema.Set).List() {
   541  				if strings.HasPrefix(v.(string), "sg-") {
   542  					match = true
   543  					break
   544  				}
   545  			}
   546  		}
   547  
   548  		useID = match
   549  	}
   550  
   551  	// Build up the security groups
   552  	sgs := make([]string, 0, len(instance.SecurityGroups))
   553  	if useID {
   554  		for _, sg := range instance.SecurityGroups {
   555  			sgs = append(sgs, *sg.GroupId)
   556  		}
   557  		log.Printf("[DEBUG] Setting Security Group IDs: %#v", sgs)
   558  		if err := d.Set("vpc_security_group_ids", sgs); err != nil {
   559  			return err
   560  		}
   561  		if err := d.Set("security_groups", []string{}); err != nil {
   562  			return err
   563  		}
   564  	} else {
   565  		for _, sg := range instance.SecurityGroups {
   566  			sgs = append(sgs, *sg.GroupName)
   567  		}
   568  		log.Printf("[DEBUG] Setting Security Group Names: %#v", sgs)
   569  		if err := d.Set("security_groups", sgs); err != nil {
   570  			return err
   571  		}
   572  		if err := d.Set("vpc_security_group_ids", []string{}); err != nil {
   573  			return err
   574  		}
   575  	}
   576  
   577  	if err := readBlockDevices(d, instance, conn); err != nil {
   578  		return err
   579  	}
   580  	if _, ok := d.GetOk("ephemeral_block_device"); !ok {
   581  		d.Set("ephemeral_block_device", []interface{}{})
   582  	}
   583  
   584  	// Instance attributes
   585  	{
   586  		attr, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
   587  			Attribute:  aws.String("disableApiTermination"),
   588  			InstanceId: aws.String(d.Id()),
   589  		})
   590  		if err != nil {
   591  			return err
   592  		}
   593  		d.Set("disable_api_termination", attr.DisableApiTermination.Value)
   594  	}
   595  	{
   596  		attr, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
   597  			Attribute:  aws.String(ec2.InstanceAttributeNameUserData),
   598  			InstanceId: aws.String(d.Id()),
   599  		})
   600  		if err != nil {
   601  			return err
   602  		}
   603  		if attr.UserData.Value != nil {
   604  			d.Set("user_data", userDataHashSum(*attr.UserData.Value))
   605  		}
   606  	}
   607  
   608  	return nil
   609  }
   610  
   611  func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
   612  	conn := meta.(*AWSClient).ec2conn
   613  
   614  	d.Partial(true)
   615  	if err := setTags(conn, d); err != nil {
   616  		return err
   617  	} else {
   618  		d.SetPartial("tags")
   619  	}
   620  
   621  	if d.HasChange("source_dest_check") || d.IsNewResource() {
   622  		// SourceDestCheck can only be set on VPC instances	// AWS will return an error of InvalidParameterCombination if we attempt
   623  		// to modify the source_dest_check of an instance in EC2 Classic
   624  		log.Printf("[INFO] Modifying `source_dest_check` on Instance %s", d.Id())
   625  		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   626  			InstanceId: aws.String(d.Id()),
   627  			SourceDestCheck: &ec2.AttributeBooleanValue{
   628  				Value: aws.Bool(d.Get("source_dest_check").(bool)),
   629  			},
   630  		})
   631  		if err != nil {
   632  			if ec2err, ok := err.(awserr.Error); ok {
   633  				// Toloerate InvalidParameterCombination error in Classic, otherwise
   634  				// return the error
   635  				if "InvalidParameterCombination" != ec2err.Code() {
   636  					return err
   637  				}
   638  				log.Printf("[WARN] Attempted to modify SourceDestCheck on non VPC instance: %s", ec2err.Message())
   639  			}
   640  		}
   641  	}
   642  
   643  	if d.HasChange("vpc_security_group_ids") {
   644  		var groups []*string
   645  		if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 {
   646  			for _, v := range v.List() {
   647  				groups = append(groups, aws.String(v.(string)))
   648  			}
   649  		}
   650  		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   651  			InstanceId: aws.String(d.Id()),
   652  			Groups:     groups,
   653  		})
   654  		if err != nil {
   655  			return err
   656  		}
   657  	}
   658  
   659  	if d.HasChange("disable_api_termination") {
   660  		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   661  			InstanceId: aws.String(d.Id()),
   662  			DisableApiTermination: &ec2.AttributeBooleanValue{
   663  				Value: aws.Bool(d.Get("disable_api_termination").(bool)),
   664  			},
   665  		})
   666  		if err != nil {
   667  			return err
   668  		}
   669  	}
   670  
   671  	if d.HasChange("instance_initiated_shutdown_behavior") {
   672  		log.Printf("[INFO] Modifying instance %s", d.Id())
   673  		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   674  			InstanceId: aws.String(d.Id()),
   675  			InstanceInitiatedShutdownBehavior: &ec2.AttributeValue{
   676  				Value: aws.String(d.Get("instance_initiated_shutdown_behavior").(string)),
   677  			},
   678  		})
   679  		if err != nil {
   680  			return err
   681  		}
   682  	}
   683  
   684  	if d.HasChange("monitoring") {
   685  		var mErr error
   686  		if d.Get("monitoring").(bool) {
   687  			log.Printf("[DEBUG] Enabling monitoring for Instance (%s)", d.Id())
   688  			_, mErr = conn.MonitorInstances(&ec2.MonitorInstancesInput{
   689  				InstanceIds: []*string{aws.String(d.Id())},
   690  			})
   691  		} else {
   692  			log.Printf("[DEBUG] Disabling monitoring for Instance (%s)", d.Id())
   693  			_, mErr = conn.UnmonitorInstances(&ec2.UnmonitorInstancesInput{
   694  				InstanceIds: []*string{aws.String(d.Id())},
   695  			})
   696  		}
   697  		if mErr != nil {
   698  			return fmt.Errorf("[WARN] Error updating Instance monitoring: %s", mErr)
   699  		}
   700  	}
   701  
   702  	// TODO(mitchellh): wait for the attributes we modified to
   703  	// persist the change...
   704  
   705  	d.Partial(false)
   706  
   707  	return resourceAwsInstanceRead(d, meta)
   708  }
   709  
   710  func resourceAwsInstanceDelete(d *schema.ResourceData, meta interface{}) error {
   711  	conn := meta.(*AWSClient).ec2conn
   712  
   713  	if err := awsTerminateInstance(conn, d.Id()); err != nil {
   714  		return err
   715  	}
   716  
   717  	d.SetId("")
   718  	return nil
   719  }
   720  
   721  // InstanceStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
   722  // an EC2 instance.
   723  func InstanceStateRefreshFunc(conn *ec2.EC2, instanceID string) resource.StateRefreshFunc {
   724  	return func() (interface{}, string, error) {
   725  		resp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{
   726  			InstanceIds: []*string{aws.String(instanceID)},
   727  		})
   728  		if err != nil {
   729  			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" {
   730  				// Set this to nil as if we didn't find anything.
   731  				resp = nil
   732  			} else {
   733  				log.Printf("Error on InstanceStateRefresh: %s", err)
   734  				return nil, "", err
   735  			}
   736  		}
   737  
   738  		if resp == nil || len(resp.Reservations) == 0 || len(resp.Reservations[0].Instances) == 0 {
   739  			// Sometimes AWS just has consistency issues and doesn't see
   740  			// our instance yet. Return an empty state.
   741  			return nil, "", nil
   742  		}
   743  
   744  		i := resp.Reservations[0].Instances[0]
   745  		return i, *i.State.Name, nil
   746  	}
   747  }
   748  
   749  func readBlockDevices(d *schema.ResourceData, instance *ec2.Instance, conn *ec2.EC2) error {
   750  	ibds, err := readBlockDevicesFromInstance(instance, conn)
   751  	if err != nil {
   752  		return err
   753  	}
   754  
   755  	if err := d.Set("ebs_block_device", ibds["ebs"]); err != nil {
   756  		return err
   757  	}
   758  
   759  	// This handles the import case which needs to be defaulted to empty
   760  	if _, ok := d.GetOk("root_block_device"); !ok {
   761  		if err := d.Set("root_block_device", []interface{}{}); err != nil {
   762  			return err
   763  		}
   764  	}
   765  
   766  	if ibds["root"] != nil {
   767  		roots := []interface{}{ibds["root"]}
   768  		if err := d.Set("root_block_device", roots); err != nil {
   769  			return err
   770  		}
   771  	}
   772  
   773  	return nil
   774  }
   775  
   776  func readBlockDevicesFromInstance(instance *ec2.Instance, conn *ec2.EC2) (map[string]interface{}, error) {
   777  	blockDevices := make(map[string]interface{})
   778  	blockDevices["ebs"] = make([]map[string]interface{}, 0)
   779  	blockDevices["root"] = nil
   780  
   781  	instanceBlockDevices := make(map[string]*ec2.InstanceBlockDeviceMapping)
   782  	for _, bd := range instance.BlockDeviceMappings {
   783  		if bd.Ebs != nil {
   784  			instanceBlockDevices[*bd.Ebs.VolumeId] = bd
   785  		}
   786  	}
   787  
   788  	if len(instanceBlockDevices) == 0 {
   789  		return nil, nil
   790  	}
   791  
   792  	volIDs := make([]*string, 0, len(instanceBlockDevices))
   793  	for volID := range instanceBlockDevices {
   794  		volIDs = append(volIDs, aws.String(volID))
   795  	}
   796  
   797  	// Need to call DescribeVolumes to get volume_size and volume_type for each
   798  	// EBS block device
   799  	volResp, err := conn.DescribeVolumes(&ec2.DescribeVolumesInput{
   800  		VolumeIds: volIDs,
   801  	})
   802  	if err != nil {
   803  		return nil, err
   804  	}
   805  
   806  	for _, vol := range volResp.Volumes {
   807  		instanceBd := instanceBlockDevices[*vol.VolumeId]
   808  		bd := make(map[string]interface{})
   809  
   810  		if instanceBd.Ebs != nil && instanceBd.Ebs.DeleteOnTermination != nil {
   811  			bd["delete_on_termination"] = *instanceBd.Ebs.DeleteOnTermination
   812  		}
   813  		if vol.Size != nil {
   814  			bd["volume_size"] = *vol.Size
   815  		}
   816  		if vol.VolumeType != nil {
   817  			bd["volume_type"] = *vol.VolumeType
   818  		}
   819  		if vol.Iops != nil {
   820  			bd["iops"] = *vol.Iops
   821  		}
   822  
   823  		if blockDeviceIsRoot(instanceBd, instance) {
   824  			blockDevices["root"] = bd
   825  		} else {
   826  			if instanceBd.DeviceName != nil {
   827  				bd["device_name"] = *instanceBd.DeviceName
   828  			}
   829  			if vol.Encrypted != nil {
   830  				bd["encrypted"] = *vol.Encrypted
   831  			}
   832  			if vol.SnapshotId != nil {
   833  				bd["snapshot_id"] = *vol.SnapshotId
   834  			}
   835  
   836  			blockDevices["ebs"] = append(blockDevices["ebs"].([]map[string]interface{}), bd)
   837  		}
   838  	}
   839  
   840  	return blockDevices, nil
   841  }
   842  
   843  func blockDeviceIsRoot(bd *ec2.InstanceBlockDeviceMapping, instance *ec2.Instance) bool {
   844  	return bd.DeviceName != nil &&
   845  		instance.RootDeviceName != nil &&
   846  		*bd.DeviceName == *instance.RootDeviceName
   847  }
   848  
   849  func fetchRootDeviceName(ami string, conn *ec2.EC2) (*string, error) {
   850  	if ami == "" {
   851  		return nil, fmt.Errorf("Cannot fetch root device name for blank AMI ID.")
   852  	}
   853  
   854  	log.Printf("[DEBUG] Describing AMI %q to get root block device name", ami)
   855  	res, err := conn.DescribeImages(&ec2.DescribeImagesInput{
   856  		ImageIds: []*string{aws.String(ami)},
   857  	})
   858  	if err != nil {
   859  		return nil, err
   860  	}
   861  
   862  	// For a bad image, we just return nil so we don't block a refresh
   863  	if len(res.Images) == 0 {
   864  		return nil, nil
   865  	}
   866  
   867  	image := res.Images[0]
   868  	rootDeviceName := image.RootDeviceName
   869  
   870  	// Instance store backed AMIs do not provide a root device name.
   871  	if *image.RootDeviceType == ec2.DeviceTypeInstanceStore {
   872  		return nil, nil
   873  	}
   874  
   875  	// Some AMIs have a RootDeviceName like "/dev/sda1" that does not appear as a
   876  	// DeviceName in the BlockDeviceMapping list (which will instead have
   877  	// something like "/dev/sda")
   878  	//
   879  	// While this seems like it breaks an invariant of AMIs, it ends up working
   880  	// on the AWS side, and AMIs like this are common enough that we need to
   881  	// special case it so Terraform does the right thing.
   882  	//
   883  	// Our heuristic is: if the RootDeviceName does not appear in the
   884  	// BlockDeviceMapping, assume that the DeviceName of the first
   885  	// BlockDeviceMapping entry serves as the root device.
   886  	rootDeviceNameInMapping := false
   887  	for _, bdm := range image.BlockDeviceMappings {
   888  		if bdm.DeviceName == image.RootDeviceName {
   889  			rootDeviceNameInMapping = true
   890  		}
   891  	}
   892  
   893  	if !rootDeviceNameInMapping && len(image.BlockDeviceMappings) > 0 {
   894  		rootDeviceName = image.BlockDeviceMappings[0].DeviceName
   895  	}
   896  
   897  	if rootDeviceName == nil {
   898  		return nil, fmt.Errorf("[WARN] Error finding Root Device Name for AMI (%s)", ami)
   899  	}
   900  
   901  	return rootDeviceName, nil
   902  }
   903  
   904  func readBlockDeviceMappingsFromConfig(
   905  	d *schema.ResourceData, conn *ec2.EC2) ([]*ec2.BlockDeviceMapping, error) {
   906  	blockDevices := make([]*ec2.BlockDeviceMapping, 0)
   907  
   908  	if v, ok := d.GetOk("ebs_block_device"); ok {
   909  		vL := v.(*schema.Set).List()
   910  		for _, v := range vL {
   911  			bd := v.(map[string]interface{})
   912  			ebs := &ec2.EbsBlockDevice{
   913  				DeleteOnTermination: aws.Bool(bd["delete_on_termination"].(bool)),
   914  			}
   915  
   916  			if v, ok := bd["snapshot_id"].(string); ok && v != "" {
   917  				ebs.SnapshotId = aws.String(v)
   918  			}
   919  
   920  			if v, ok := bd["encrypted"].(bool); ok && v {
   921  				ebs.Encrypted = aws.Bool(v)
   922  			}
   923  
   924  			if v, ok := bd["volume_size"].(int); ok && v != 0 {
   925  				ebs.VolumeSize = aws.Int64(int64(v))
   926  			}
   927  
   928  			if v, ok := bd["volume_type"].(string); ok && v != "" {
   929  				ebs.VolumeType = aws.String(v)
   930  			}
   931  
   932  			if v, ok := bd["iops"].(int); ok && v > 0 {
   933  				ebs.Iops = aws.Int64(int64(v))
   934  			}
   935  
   936  			blockDevices = append(blockDevices, &ec2.BlockDeviceMapping{
   937  				DeviceName: aws.String(bd["device_name"].(string)),
   938  				Ebs:        ebs,
   939  			})
   940  		}
   941  	}
   942  
   943  	if v, ok := d.GetOk("ephemeral_block_device"); ok {
   944  		vL := v.(*schema.Set).List()
   945  		for _, v := range vL {
   946  			bd := v.(map[string]interface{})
   947  			bdm := &ec2.BlockDeviceMapping{
   948  				DeviceName:  aws.String(bd["device_name"].(string)),
   949  				VirtualName: aws.String(bd["virtual_name"].(string)),
   950  			}
   951  			if v, ok := bd["no_device"].(bool); ok && v {
   952  				bdm.NoDevice = aws.String("")
   953  				// When NoDevice is true, just ignore VirtualName since it's not needed
   954  				bdm.VirtualName = nil
   955  			}
   956  
   957  			if bdm.NoDevice == nil && aws.StringValue(bdm.VirtualName) == "" {
   958  				return nil, fmt.Errorf("virtual_name cannot be empty when no_device is false or undefined.")
   959  			}
   960  
   961  			blockDevices = append(blockDevices, bdm)
   962  		}
   963  	}
   964  
   965  	if v, ok := d.GetOk("root_block_device"); ok {
   966  		vL := v.(*schema.Set).List()
   967  		if len(vL) > 1 {
   968  			return nil, fmt.Errorf("Cannot specify more than one root_block_device.")
   969  		}
   970  		for _, v := range vL {
   971  			bd := v.(map[string]interface{})
   972  			ebs := &ec2.EbsBlockDevice{
   973  				DeleteOnTermination: aws.Bool(bd["delete_on_termination"].(bool)),
   974  			}
   975  
   976  			if v, ok := bd["volume_size"].(int); ok && v != 0 {
   977  				ebs.VolumeSize = aws.Int64(int64(v))
   978  			}
   979  
   980  			if v, ok := bd["volume_type"].(string); ok && v != "" {
   981  				ebs.VolumeType = aws.String(v)
   982  			}
   983  
   984  			if v, ok := bd["iops"].(int); ok && v > 0 && *ebs.VolumeType == "io1" {
   985  				// Only set the iops attribute if the volume type is io1. Setting otherwise
   986  				// can trigger a refresh/plan loop based on the computed value that is given
   987  				// from AWS, and prevent us from specifying 0 as a valid iops.
   988  				//   See https://github.com/hashicorp/terraform/pull/4146
   989  				//   See https://github.com/hashicorp/terraform/issues/7765
   990  				ebs.Iops = aws.Int64(int64(v))
   991  			} else if v, ok := bd["iops"].(int); ok && v > 0 && *ebs.VolumeType != "io1" {
   992  				// Message user about incompatibility
   993  				log.Printf("[WARN] IOPs is only valid for storate type io1 for EBS Volumes")
   994  			}
   995  
   996  			if dn, err := fetchRootDeviceName(d.Get("ami").(string), conn); err == nil {
   997  				if dn == nil {
   998  					return nil, fmt.Errorf(
   999  						"Expected 1 AMI for ID: %s, got none",
  1000  						d.Get("ami").(string))
  1001  				}
  1002  
  1003  				blockDevices = append(blockDevices, &ec2.BlockDeviceMapping{
  1004  					DeviceName: dn,
  1005  					Ebs:        ebs,
  1006  				})
  1007  			} else {
  1008  				return nil, err
  1009  			}
  1010  		}
  1011  	}
  1012  
  1013  	return blockDevices, nil
  1014  }
  1015  
  1016  type awsInstanceOpts struct {
  1017  	BlockDeviceMappings               []*ec2.BlockDeviceMapping
  1018  	DisableAPITermination             *bool
  1019  	EBSOptimized                      *bool
  1020  	Monitoring                        *ec2.RunInstancesMonitoringEnabled
  1021  	IAMInstanceProfile                *ec2.IamInstanceProfileSpecification
  1022  	ImageID                           *string
  1023  	InstanceInitiatedShutdownBehavior *string
  1024  	InstanceType                      *string
  1025  	KeyName                           *string
  1026  	NetworkInterfaces                 []*ec2.InstanceNetworkInterfaceSpecification
  1027  	Placement                         *ec2.Placement
  1028  	PrivateIPAddress                  *string
  1029  	SecurityGroupIDs                  []*string
  1030  	SecurityGroups                    []*string
  1031  	SpotPlacement                     *ec2.SpotPlacement
  1032  	SubnetID                          *string
  1033  	UserData64                        *string
  1034  }
  1035  
  1036  func buildAwsInstanceOpts(
  1037  	d *schema.ResourceData, meta interface{}) (*awsInstanceOpts, error) {
  1038  	conn := meta.(*AWSClient).ec2conn
  1039  
  1040  	opts := &awsInstanceOpts{
  1041  		DisableAPITermination: aws.Bool(d.Get("disable_api_termination").(bool)),
  1042  		EBSOptimized:          aws.Bool(d.Get("ebs_optimized").(bool)),
  1043  		ImageID:               aws.String(d.Get("ami").(string)),
  1044  		InstanceType:          aws.String(d.Get("instance_type").(string)),
  1045  	}
  1046  
  1047  	if v := d.Get("instance_initiated_shutdown_behavior").(string); v != "" {
  1048  		opts.InstanceInitiatedShutdownBehavior = aws.String(v)
  1049  	}
  1050  
  1051  	opts.Monitoring = &ec2.RunInstancesMonitoringEnabled{
  1052  		Enabled: aws.Bool(d.Get("monitoring").(bool)),
  1053  	}
  1054  
  1055  	opts.IAMInstanceProfile = &ec2.IamInstanceProfileSpecification{
  1056  		Name: aws.String(d.Get("iam_instance_profile").(string)),
  1057  	}
  1058  
  1059  	user_data := d.Get("user_data").(string)
  1060  
  1061  	opts.UserData64 = aws.String(base64Encode([]byte(user_data)))
  1062  
  1063  	// check for non-default Subnet, and cast it to a String
  1064  	subnet, hasSubnet := d.GetOk("subnet_id")
  1065  	subnetID := subnet.(string)
  1066  
  1067  	// Placement is used for aws_instance; SpotPlacement is used for
  1068  	// aws_spot_instance_request. They represent the same data. :-|
  1069  	opts.Placement = &ec2.Placement{
  1070  		AvailabilityZone: aws.String(d.Get("availability_zone").(string)),
  1071  		GroupName:        aws.String(d.Get("placement_group").(string)),
  1072  	}
  1073  
  1074  	opts.SpotPlacement = &ec2.SpotPlacement{
  1075  		AvailabilityZone: aws.String(d.Get("availability_zone").(string)),
  1076  		GroupName:        aws.String(d.Get("placement_group").(string)),
  1077  	}
  1078  
  1079  	if v := d.Get("tenancy").(string); v != "" {
  1080  		opts.Placement.Tenancy = aws.String(v)
  1081  	}
  1082  
  1083  	associatePublicIPAddress := d.Get("associate_public_ip_address").(bool)
  1084  
  1085  	var groups []*string
  1086  	if v := d.Get("security_groups"); v != nil {
  1087  		// Security group names.
  1088  		// For a nondefault VPC, you must use security group IDs instead.
  1089  		// See http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html
  1090  		sgs := v.(*schema.Set).List()
  1091  		if len(sgs) > 0 && hasSubnet {
  1092  			log.Printf("[WARN] Deprecated. Attempting to use 'security_groups' within a VPC instance. Use 'vpc_security_group_ids' instead.")
  1093  		}
  1094  		for _, v := range sgs {
  1095  			str := v.(string)
  1096  			groups = append(groups, aws.String(str))
  1097  		}
  1098  	}
  1099  
  1100  	if hasSubnet && associatePublicIPAddress {
  1101  		// If we have a non-default VPC / Subnet specified, we can flag
  1102  		// AssociatePublicIpAddress to get a Public IP assigned. By default these are not provided.
  1103  		// You cannot specify both SubnetId and the NetworkInterface.0.* parameters though, otherwise
  1104  		// you get: Network interfaces and an instance-level subnet ID may not be specified on the same request
  1105  		// You also need to attach Security Groups to the NetworkInterface instead of the instance,
  1106  		// to avoid: Network interfaces and an instance-level security groups may not be specified on
  1107  		// the same request
  1108  		ni := &ec2.InstanceNetworkInterfaceSpecification{
  1109  			AssociatePublicIpAddress: aws.Bool(associatePublicIPAddress),
  1110  			DeviceIndex:              aws.Int64(int64(0)),
  1111  			SubnetId:                 aws.String(subnetID),
  1112  			Groups:                   groups,
  1113  		}
  1114  
  1115  		if v, ok := d.GetOk("private_ip"); ok {
  1116  			ni.PrivateIpAddress = aws.String(v.(string))
  1117  		}
  1118  
  1119  		if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 {
  1120  			for _, v := range v.List() {
  1121  				ni.Groups = append(ni.Groups, aws.String(v.(string)))
  1122  			}
  1123  		}
  1124  
  1125  		opts.NetworkInterfaces = []*ec2.InstanceNetworkInterfaceSpecification{ni}
  1126  	} else {
  1127  		if subnetID != "" {
  1128  			opts.SubnetID = aws.String(subnetID)
  1129  		}
  1130  
  1131  		if v, ok := d.GetOk("private_ip"); ok {
  1132  			opts.PrivateIPAddress = aws.String(v.(string))
  1133  		}
  1134  		if opts.SubnetID != nil &&
  1135  			*opts.SubnetID != "" {
  1136  			opts.SecurityGroupIDs = groups
  1137  		} else {
  1138  			opts.SecurityGroups = groups
  1139  		}
  1140  
  1141  		if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 {
  1142  			for _, v := range v.List() {
  1143  				opts.SecurityGroupIDs = append(opts.SecurityGroupIDs, aws.String(v.(string)))
  1144  			}
  1145  		}
  1146  	}
  1147  
  1148  	if v, ok := d.GetOk("key_name"); ok {
  1149  		opts.KeyName = aws.String(v.(string))
  1150  	}
  1151  
  1152  	blockDevices, err := readBlockDeviceMappingsFromConfig(d, conn)
  1153  	if err != nil {
  1154  		return nil, err
  1155  	}
  1156  	if len(blockDevices) > 0 {
  1157  		opts.BlockDeviceMappings = blockDevices
  1158  	}
  1159  
  1160  	return opts, nil
  1161  }
  1162  
  1163  func awsTerminateInstance(conn *ec2.EC2, id string) error {
  1164  	log.Printf("[INFO] Terminating instance: %s", id)
  1165  	req := &ec2.TerminateInstancesInput{
  1166  		InstanceIds: []*string{aws.String(id)},
  1167  	}
  1168  	if _, err := conn.TerminateInstances(req); err != nil {
  1169  		return fmt.Errorf("Error terminating instance: %s", err)
  1170  	}
  1171  
  1172  	log.Printf("[DEBUG] Waiting for instance (%s) to become terminated", id)
  1173  
  1174  	stateConf := &resource.StateChangeConf{
  1175  		Pending:    []string{"pending", "running", "shutting-down", "stopped", "stopping"},
  1176  		Target:     []string{"terminated"},
  1177  		Refresh:    InstanceStateRefreshFunc(conn, id),
  1178  		Timeout:    10 * time.Minute,
  1179  		Delay:      10 * time.Second,
  1180  		MinTimeout: 3 * time.Second,
  1181  	}
  1182  
  1183  	_, err := stateConf.WaitForState()
  1184  	if err != nil {
  1185  		return fmt.Errorf(
  1186  			"Error waiting for instance (%s) to terminate: %s", id, err)
  1187  	}
  1188  
  1189  	return nil
  1190  }
  1191  
  1192  func iamInstanceProfileArnToName(ip *ec2.IamInstanceProfile) string {
  1193  	if ip == nil || ip.Arn == nil {
  1194  		return ""
  1195  	}
  1196  	parts := strings.Split(*ip.Arn, "/")
  1197  	return parts[len(parts)-1]
  1198  }
  1199  
  1200  func userDataHashSum(user_data string) string {
  1201  	// Check whether the user_data is not Base64 encoded.
  1202  	// Always calculate hash of base64 decoded value since we
  1203  	// check against double-encoding when setting it
  1204  	v, base64DecodeError := base64.StdEncoding.DecodeString(user_data)
  1205  	if base64DecodeError != nil {
  1206  		v = []byte(user_data)
  1207  	}
  1208  
  1209  	hash := sha1.Sum(v)
  1210  	return hex.EncodeToString(hash[:])
  1211  }