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