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