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