github.com/fluxrad/terraform@v0.6.4-0.20150906191316-06627ccf39fa/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  	// Set our attributes
   418  	if err := resourceAwsInstanceRead(d, meta); err != nil {
   419  		return err
   420  	}
   421  
   422  	// Update if we need to
   423  	return resourceAwsInstanceUpdate(d, meta)
   424  }
   425  
   426  func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error {
   427  	conn := meta.(*AWSClient).ec2conn
   428  
   429  	resp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{
   430  		InstanceIds: []*string{aws.String(d.Id())},
   431  	})
   432  	if err != nil {
   433  		// If the instance was not found, return nil so that we can show
   434  		// that the instance is gone.
   435  		if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" {
   436  			d.SetId("")
   437  			return nil
   438  		}
   439  
   440  		// Some other error, report it
   441  		return err
   442  	}
   443  
   444  	// If nothing was found, then return no state
   445  	if len(resp.Reservations) == 0 {
   446  		d.SetId("")
   447  		return nil
   448  	}
   449  
   450  	instance := resp.Reservations[0].Instances[0]
   451  
   452  	// If the instance is terminated, then it is gone
   453  	if *instance.State.Name == "terminated" {
   454  		d.SetId("")
   455  		return nil
   456  	}
   457  
   458  	if instance.Placement != nil {
   459  		d.Set("availability_zone", instance.Placement.AvailabilityZone)
   460  	}
   461  	if instance.Placement.Tenancy != nil {
   462  		d.Set("tenancy", instance.Placement.Tenancy)
   463  	}
   464  
   465  	d.Set("ami", instance.ImageId)
   466  	d.Set("instance_type", instance.InstanceType)
   467  	d.Set("key_name", instance.KeyName)
   468  	d.Set("public_dns", instance.PublicDnsName)
   469  	d.Set("public_ip", instance.PublicIpAddress)
   470  	d.Set("private_dns", instance.PrivateDnsName)
   471  	d.Set("private_ip", instance.PrivateIpAddress)
   472  	d.Set("iam_instance_profile", iamInstanceProfileArnToName(instance.IamInstanceProfile))
   473  
   474  	if len(instance.NetworkInterfaces) > 0 {
   475  		d.Set("subnet_id", instance.NetworkInterfaces[0].SubnetId)
   476  	} else {
   477  		d.Set("subnet_id", instance.SubnetId)
   478  	}
   479  	d.Set("ebs_optimized", instance.EbsOptimized)
   480  
   481  	if instance.Monitoring != nil && instance.Monitoring.State != nil {
   482  		monitoringState := *instance.Monitoring.State
   483  		d.Set("monitoring", monitoringState == "enabled" || monitoringState == "pending")
   484  	}
   485  
   486  	d.Set("tags", tagsToMap(instance.Tags))
   487  
   488  	// Determine whether we're referring to security groups with
   489  	// IDs or names. We use a heuristic to figure this out. By default,
   490  	// we use IDs if we're in a VPC. However, if we previously had an
   491  	// all-name list of security groups, we use names. Or, if we had any
   492  	// IDs, we use IDs.
   493  	useID := instance.SubnetId != nil && *instance.SubnetId != ""
   494  	if v := d.Get("security_groups"); v != nil {
   495  		match := useID
   496  		sgs := v.(*schema.Set).List()
   497  		if len(sgs) > 0 {
   498  			match = false
   499  			for _, v := range v.(*schema.Set).List() {
   500  				if strings.HasPrefix(v.(string), "sg-") {
   501  					match = true
   502  					break
   503  				}
   504  			}
   505  		}
   506  
   507  		useID = match
   508  	}
   509  
   510  	// Build up the security groups
   511  	sgs := make([]string, 0, len(instance.SecurityGroups))
   512  	if useID {
   513  		for _, sg := range instance.SecurityGroups {
   514  			sgs = append(sgs, *sg.GroupId)
   515  		}
   516  		log.Printf("[DEBUG] Setting Security Group IDs: %#v", sgs)
   517  		if err := d.Set("vpc_security_group_ids", sgs); err != nil {
   518  			return err
   519  		}
   520  	} else {
   521  		for _, sg := range instance.SecurityGroups {
   522  			sgs = append(sgs, *sg.GroupName)
   523  		}
   524  		log.Printf("[DEBUG] Setting Security Group Names: %#v", sgs)
   525  		if err := d.Set("security_groups", sgs); err != nil {
   526  			return err
   527  		}
   528  	}
   529  
   530  	if err := readBlockDevices(d, instance, conn); err != nil {
   531  		return err
   532  	}
   533  
   534  	return nil
   535  }
   536  
   537  func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
   538  	conn := meta.(*AWSClient).ec2conn
   539  
   540  	d.Partial(true)
   541  	if err := setTags(conn, d); err != nil {
   542  		return err
   543  	} else {
   544  		d.SetPartial("tags")
   545  	}
   546  
   547  	// SourceDestCheck can only be set on VPC instances
   548  	if d.Get("subnet_id").(string) != "" {
   549  		log.Printf("[INFO] Modifying instance %s", d.Id())
   550  		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   551  			InstanceId: aws.String(d.Id()),
   552  			SourceDestCheck: &ec2.AttributeBooleanValue{
   553  				Value: aws.Bool(d.Get("source_dest_check").(bool)),
   554  			},
   555  		})
   556  		if err != nil {
   557  			return err
   558  		}
   559  	}
   560  
   561  	if d.HasChange("vpc_security_group_ids") {
   562  		var groups []*string
   563  		if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 {
   564  			for _, v := range v.List() {
   565  				groups = append(groups, aws.String(v.(string)))
   566  			}
   567  		}
   568  		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   569  			InstanceId: aws.String(d.Id()),
   570  			Groups:     groups,
   571  		})
   572  		if err != nil {
   573  			return err
   574  		}
   575  	}
   576  
   577  	if d.HasChange("disable_api_termination") {
   578  		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   579  			InstanceId: aws.String(d.Id()),
   580  			DisableApiTermination: &ec2.AttributeBooleanValue{
   581  				Value: aws.Bool(d.Get("disable_api_termination").(bool)),
   582  			},
   583  		})
   584  		if err != nil {
   585  			return err
   586  		}
   587  	}
   588  
   589  	if d.HasChange("instance_initiated_shutdown_behavior") {
   590  		log.Printf("[INFO] Modifying instance %s", d.Id())
   591  		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
   592  			InstanceId: aws.String(d.Id()),
   593  			InstanceInitiatedShutdownBehavior: &ec2.AttributeValue{
   594  				Value: aws.String(d.Get("instance_initiated_shutdown_behavior").(string)),
   595  			},
   596  		})
   597  		if err != nil {
   598  			return err
   599  		}
   600  	}
   601  
   602  	if d.HasChange("monitoring") {
   603  		var mErr error
   604  		if d.Get("monitoring").(bool) {
   605  			log.Printf("[DEBUG] Enabling monitoring for Instance (%s)", d.Id())
   606  			_, mErr = conn.MonitorInstances(&ec2.MonitorInstancesInput{
   607  				InstanceIds: []*string{aws.String(d.Id())},
   608  			})
   609  		} else {
   610  			log.Printf("[DEBUG] Disabling monitoring for Instance (%s)", d.Id())
   611  			_, mErr = conn.UnmonitorInstances(&ec2.UnmonitorInstancesInput{
   612  				InstanceIds: []*string{aws.String(d.Id())},
   613  			})
   614  		}
   615  		if mErr != nil {
   616  			return fmt.Errorf("[WARN] Error updating Instance monitoring: %s", mErr)
   617  		}
   618  	}
   619  
   620  	// TODO(mitchellh): wait for the attributes we modified to
   621  	// persist the change...
   622  
   623  	d.Partial(false)
   624  
   625  	return resourceAwsInstanceRead(d, meta)
   626  }
   627  
   628  func resourceAwsInstanceDelete(d *schema.ResourceData, meta interface{}) error {
   629  	conn := meta.(*AWSClient).ec2conn
   630  
   631  	if err := awsTerminateInstance(conn, d.Id()); err != nil {
   632  		return err
   633  	}
   634  
   635  	d.SetId("")
   636  	return nil
   637  }
   638  
   639  // InstanceStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
   640  // an EC2 instance.
   641  func InstanceStateRefreshFunc(conn *ec2.EC2, instanceID string) resource.StateRefreshFunc {
   642  	return func() (interface{}, string, error) {
   643  		resp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{
   644  			InstanceIds: []*string{aws.String(instanceID)},
   645  		})
   646  		if err != nil {
   647  			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" {
   648  				// Set this to nil as if we didn't find anything.
   649  				resp = nil
   650  			} else {
   651  				log.Printf("Error on InstanceStateRefresh: %s", err)
   652  				return nil, "", err
   653  			}
   654  		}
   655  
   656  		if resp == nil || len(resp.Reservations) == 0 || len(resp.Reservations[0].Instances) == 0 {
   657  			// Sometimes AWS just has consistency issues and doesn't see
   658  			// our instance yet. Return an empty state.
   659  			return nil, "", nil
   660  		}
   661  
   662  		i := resp.Reservations[0].Instances[0]
   663  		return i, *i.State.Name, nil
   664  	}
   665  }
   666  
   667  func readBlockDevices(d *schema.ResourceData, instance *ec2.Instance, conn *ec2.EC2) error {
   668  	ibds, err := readBlockDevicesFromInstance(instance, conn)
   669  	if err != nil {
   670  		return err
   671  	}
   672  
   673  	if err := d.Set("ebs_block_device", ibds["ebs"]); err != nil {
   674  		return err
   675  	}
   676  	if ibds["root"] != nil {
   677  		if err := d.Set("root_block_device", []interface{}{ibds["root"]}); err != nil {
   678  			return err
   679  		}
   680  	}
   681  
   682  	return nil
   683  }
   684  
   685  func readBlockDevicesFromInstance(instance *ec2.Instance, conn *ec2.EC2) (map[string]interface{}, error) {
   686  	blockDevices := make(map[string]interface{})
   687  	blockDevices["ebs"] = make([]map[string]interface{}, 0)
   688  	blockDevices["root"] = nil
   689  
   690  	instanceBlockDevices := make(map[string]*ec2.InstanceBlockDeviceMapping)
   691  	for _, bd := range instance.BlockDeviceMappings {
   692  		if bd.Ebs != nil {
   693  			instanceBlockDevices[*(bd.Ebs.VolumeId)] = bd
   694  		}
   695  	}
   696  
   697  	if len(instanceBlockDevices) == 0 {
   698  		return nil, nil
   699  	}
   700  
   701  	volIDs := make([]*string, 0, len(instanceBlockDevices))
   702  	for volID := range instanceBlockDevices {
   703  		volIDs = append(volIDs, aws.String(volID))
   704  	}
   705  
   706  	// Need to call DescribeVolumes to get volume_size and volume_type for each
   707  	// EBS block device
   708  	volResp, err := conn.DescribeVolumes(&ec2.DescribeVolumesInput{
   709  		VolumeIds: volIDs,
   710  	})
   711  	if err != nil {
   712  		return nil, err
   713  	}
   714  
   715  	for _, vol := range volResp.Volumes {
   716  		instanceBd := instanceBlockDevices[*vol.VolumeId]
   717  		bd := make(map[string]interface{})
   718  
   719  		if instanceBd.Ebs != nil && instanceBd.Ebs.DeleteOnTermination != nil {
   720  			bd["delete_on_termination"] = *instanceBd.Ebs.DeleteOnTermination
   721  		}
   722  		if vol.Size != nil {
   723  			bd["volume_size"] = *vol.Size
   724  		}
   725  		if vol.VolumeType != nil {
   726  			bd["volume_type"] = *vol.VolumeType
   727  		}
   728  		if vol.Iops != nil {
   729  			bd["iops"] = *vol.Iops
   730  		}
   731  
   732  		if blockDeviceIsRoot(instanceBd, instance) {
   733  			blockDevices["root"] = bd
   734  		} else {
   735  			if instanceBd.DeviceName != nil {
   736  				bd["device_name"] = *instanceBd.DeviceName
   737  			}
   738  			if vol.Encrypted != nil {
   739  				bd["encrypted"] = *vol.Encrypted
   740  			}
   741  			if vol.SnapshotId != nil {
   742  				bd["snapshot_id"] = *vol.SnapshotId
   743  			}
   744  
   745  			blockDevices["ebs"] = append(blockDevices["ebs"].([]map[string]interface{}), bd)
   746  		}
   747  	}
   748  
   749  	return blockDevices, nil
   750  }
   751  
   752  func blockDeviceIsRoot(bd *ec2.InstanceBlockDeviceMapping, instance *ec2.Instance) bool {
   753  	return (bd.DeviceName != nil &&
   754  		instance.RootDeviceName != nil &&
   755  		*bd.DeviceName == *instance.RootDeviceName)
   756  }
   757  
   758  func fetchRootDeviceName(ami string, conn *ec2.EC2) (*string, error) {
   759  	if ami == "" {
   760  		return nil, fmt.Errorf("Cannot fetch root device name for blank AMI ID.")
   761  	}
   762  
   763  	log.Printf("[DEBUG] Describing AMI %q to get root block device name", ami)
   764  	res, err := conn.DescribeImages(&ec2.DescribeImagesInput{
   765  		ImageIds: []*string{aws.String(ami)},
   766  	})
   767  	if err != nil {
   768  		return nil, err
   769  	}
   770  
   771  	// For a bad image, we just return nil so we don't block a refresh
   772  	if len(res.Images) == 0 {
   773  		return nil, nil
   774  	}
   775  
   776  	image := res.Images[0]
   777  	rootDeviceName := image.RootDeviceName
   778  
   779  	// Some AMIs have a RootDeviceName like "/dev/sda1" that does not appear as a
   780  	// DeviceName in the BlockDeviceMapping list (which will instead have
   781  	// something like "/dev/sda")
   782  	//
   783  	// While this seems like it breaks an invariant of AMIs, it ends up working
   784  	// on the AWS side, and AMIs like this are common enough that we need to
   785  	// special case it so Terraform does the right thing.
   786  	//
   787  	// Our heuristic is: if the RootDeviceName does not appear in the
   788  	// BlockDeviceMapping, assume that the DeviceName of the first
   789  	// BlockDeviceMapping entry serves as the root device.
   790  	rootDeviceNameInMapping := false
   791  	for _, bdm := range image.BlockDeviceMappings {
   792  		if bdm.DeviceName == image.RootDeviceName {
   793  			rootDeviceNameInMapping = true
   794  		}
   795  	}
   796  
   797  	if !rootDeviceNameInMapping && len(image.BlockDeviceMappings) > 0 {
   798  		rootDeviceName = image.BlockDeviceMappings[0].DeviceName
   799  	}
   800  
   801  	if rootDeviceName == nil {
   802  		return nil, fmt.Errorf("[WARN] Error finding Root Device Name for AMI (%s)", ami)
   803  	}
   804  
   805  	return rootDeviceName, nil
   806  }
   807  
   808  func readBlockDeviceMappingsFromConfig(
   809  	d *schema.ResourceData, conn *ec2.EC2) ([]*ec2.BlockDeviceMapping, error) {
   810  	blockDevices := make([]*ec2.BlockDeviceMapping, 0)
   811  
   812  	if v, ok := d.GetOk("ebs_block_device"); ok {
   813  		vL := v.(*schema.Set).List()
   814  		for _, v := range vL {
   815  			bd := v.(map[string]interface{})
   816  			ebs := &ec2.EbsBlockDevice{
   817  				DeleteOnTermination: aws.Bool(bd["delete_on_termination"].(bool)),
   818  			}
   819  
   820  			if v, ok := bd["snapshot_id"].(string); ok && v != "" {
   821  				ebs.SnapshotId = aws.String(v)
   822  			}
   823  
   824  			if v, ok := bd["encrypted"].(bool); ok && v {
   825  				ebs.Encrypted = aws.Bool(v)
   826  			}
   827  
   828  			if v, ok := bd["volume_size"].(int); ok && v != 0 {
   829  				ebs.VolumeSize = aws.Int64(int64(v))
   830  			}
   831  
   832  			if v, ok := bd["volume_type"].(string); ok && v != "" {
   833  				ebs.VolumeType = aws.String(v)
   834  			}
   835  
   836  			if v, ok := bd["iops"].(int); ok && v > 0 {
   837  				ebs.Iops = aws.Int64(int64(v))
   838  			}
   839  
   840  			blockDevices = append(blockDevices, &ec2.BlockDeviceMapping{
   841  				DeviceName: aws.String(bd["device_name"].(string)),
   842  				Ebs:        ebs,
   843  			})
   844  		}
   845  	}
   846  
   847  	if v, ok := d.GetOk("ephemeral_block_device"); ok {
   848  		vL := v.(*schema.Set).List()
   849  		for _, v := range vL {
   850  			bd := v.(map[string]interface{})
   851  			blockDevices = append(blockDevices, &ec2.BlockDeviceMapping{
   852  				DeviceName:  aws.String(bd["device_name"].(string)),
   853  				VirtualName: aws.String(bd["virtual_name"].(string)),
   854  			})
   855  		}
   856  	}
   857  
   858  	if v, ok := d.GetOk("root_block_device"); ok {
   859  		vL := v.(*schema.Set).List()
   860  		if len(vL) > 1 {
   861  			return nil, fmt.Errorf("Cannot specify more than one root_block_device.")
   862  		}
   863  		for _, v := range vL {
   864  			bd := v.(map[string]interface{})
   865  			ebs := &ec2.EbsBlockDevice{
   866  				DeleteOnTermination: aws.Bool(bd["delete_on_termination"].(bool)),
   867  			}
   868  
   869  			if v, ok := bd["volume_size"].(int); ok && v != 0 {
   870  				ebs.VolumeSize = aws.Int64(int64(v))
   871  			}
   872  
   873  			if v, ok := bd["volume_type"].(string); ok && v != "" {
   874  				ebs.VolumeType = aws.String(v)
   875  			}
   876  
   877  			if v, ok := bd["iops"].(int); ok && v > 0 {
   878  				ebs.Iops = aws.Int64(int64(v))
   879  			}
   880  
   881  			if dn, err := fetchRootDeviceName(d.Get("ami").(string), conn); err == nil {
   882  				if dn == nil {
   883  					return nil, fmt.Errorf(
   884  						"Expected 1 AMI for ID: %s, got none",
   885  						d.Get("ami").(string))
   886  				}
   887  
   888  				blockDevices = append(blockDevices, &ec2.BlockDeviceMapping{
   889  					DeviceName: dn,
   890  					Ebs:        ebs,
   891  				})
   892  			} else {
   893  				return nil, err
   894  			}
   895  		}
   896  	}
   897  
   898  	return blockDevices, nil
   899  }
   900  
   901  type awsInstanceOpts struct {
   902  	BlockDeviceMappings               []*ec2.BlockDeviceMapping
   903  	DisableAPITermination             *bool
   904  	EBSOptimized                      *bool
   905  	Monitoring                        *ec2.RunInstancesMonitoringEnabled
   906  	IAMInstanceProfile                *ec2.IamInstanceProfileSpecification
   907  	ImageID                           *string
   908  	InstanceInitiatedShutdownBehavior *string
   909  	InstanceType                      *string
   910  	KeyName                           *string
   911  	NetworkInterfaces                 []*ec2.InstanceNetworkInterfaceSpecification
   912  	Placement                         *ec2.Placement
   913  	PrivateIPAddress                  *string
   914  	SecurityGroupIDs                  []*string
   915  	SecurityGroups                    []*string
   916  	SpotPlacement                     *ec2.SpotPlacement
   917  	SubnetID                          *string
   918  	UserData64                        *string
   919  }
   920  
   921  func buildAwsInstanceOpts(
   922  	d *schema.ResourceData, meta interface{}) (*awsInstanceOpts, error) {
   923  	conn := meta.(*AWSClient).ec2conn
   924  
   925  	opts := &awsInstanceOpts{
   926  		DisableAPITermination: aws.Bool(d.Get("disable_api_termination").(bool)),
   927  		EBSOptimized:          aws.Bool(d.Get("ebs_optimized").(bool)),
   928  		ImageID:               aws.String(d.Get("ami").(string)),
   929  		InstanceType:          aws.String(d.Get("instance_type").(string)),
   930  	}
   931  
   932  	if v := d.Get("instance_initiated_shutdown_behavior").(string); v != "" {
   933  		opts.InstanceInitiatedShutdownBehavior = aws.String(v)
   934  	}
   935  
   936  	opts.Monitoring = &ec2.RunInstancesMonitoringEnabled{
   937  		Enabled: aws.Bool(d.Get("monitoring").(bool)),
   938  	}
   939  
   940  	opts.IAMInstanceProfile = &ec2.IamInstanceProfileSpecification{
   941  		Name: aws.String(d.Get("iam_instance_profile").(string)),
   942  	}
   943  
   944  	opts.UserData64 = aws.String(
   945  		base64.StdEncoding.EncodeToString([]byte(d.Get("user_data").(string))))
   946  
   947  	// check for non-default Subnet, and cast it to a String
   948  	subnet, hasSubnet := d.GetOk("subnet_id")
   949  	subnetID := subnet.(string)
   950  
   951  	// Placement is used for aws_instance; SpotPlacement is used for
   952  	// aws_spot_instance_request. They represent the same data. :-|
   953  	opts.Placement = &ec2.Placement{
   954  		AvailabilityZone: aws.String(d.Get("availability_zone").(string)),
   955  		GroupName:        aws.String(d.Get("placement_group").(string)),
   956  	}
   957  
   958  	opts.SpotPlacement = &ec2.SpotPlacement{
   959  		AvailabilityZone: aws.String(d.Get("availability_zone").(string)),
   960  		GroupName:        aws.String(d.Get("placement_group").(string)),
   961  	}
   962  
   963  	if v := d.Get("tenancy").(string); v != "" {
   964  		opts.Placement.Tenancy = aws.String(v)
   965  	}
   966  
   967  	associatePublicIPAddress := d.Get("associate_public_ip_address").(bool)
   968  
   969  	var groups []*string
   970  	if v := d.Get("security_groups"); v != nil {
   971  		// Security group names.
   972  		// For a nondefault VPC, you must use security group IDs instead.
   973  		// See http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html
   974  		sgs := v.(*schema.Set).List()
   975  		if len(sgs) > 0 && hasSubnet {
   976  			log.Printf("[WARN] Deprecated. Attempting to use 'security_groups' within a VPC instance. Use 'vpc_security_group_ids' instead.")
   977  		}
   978  		for _, v := range sgs {
   979  			str := v.(string)
   980  			groups = append(groups, aws.String(str))
   981  		}
   982  	}
   983  
   984  	if hasSubnet && associatePublicIPAddress {
   985  		// If we have a non-default VPC / Subnet specified, we can flag
   986  		// AssociatePublicIpAddress to get a Public IP assigned. By default these are not provided.
   987  		// You cannot specify both SubnetId and the NetworkInterface.0.* parameters though, otherwise
   988  		// you get: Network interfaces and an instance-level subnet ID may not be specified on the same request
   989  		// You also need to attach Security Groups to the NetworkInterface instead of the instance,
   990  		// to avoid: Network interfaces and an instance-level security groups may not be specified on
   991  		// the same request
   992  		ni := &ec2.InstanceNetworkInterfaceSpecification{
   993  			AssociatePublicIpAddress: aws.Bool(associatePublicIPAddress),
   994  			DeviceIndex:              aws.Int64(int64(0)),
   995  			SubnetId:                 aws.String(subnetID),
   996  			Groups:                   groups,
   997  		}
   998  
   999  		if v, ok := d.GetOk("private_ip"); ok {
  1000  			ni.PrivateIpAddress = aws.String(v.(string))
  1001  		}
  1002  
  1003  		if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 {
  1004  			for _, v := range v.List() {
  1005  				ni.Groups = append(ni.Groups, aws.String(v.(string)))
  1006  			}
  1007  		}
  1008  
  1009  		opts.NetworkInterfaces = []*ec2.InstanceNetworkInterfaceSpecification{ni}
  1010  	} else {
  1011  		if subnetID != "" {
  1012  			opts.SubnetID = aws.String(subnetID)
  1013  		}
  1014  
  1015  		if v, ok := d.GetOk("private_ip"); ok {
  1016  			opts.PrivateIPAddress = aws.String(v.(string))
  1017  		}
  1018  		if opts.SubnetID != nil &&
  1019  			*opts.SubnetID != "" {
  1020  			opts.SecurityGroupIDs = groups
  1021  		} else {
  1022  			opts.SecurityGroups = groups
  1023  		}
  1024  
  1025  		if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 {
  1026  			for _, v := range v.List() {
  1027  				opts.SecurityGroupIDs = append(opts.SecurityGroupIDs, aws.String(v.(string)))
  1028  			}
  1029  		}
  1030  	}
  1031  
  1032  	if v, ok := d.GetOk("key_name"); ok {
  1033  		opts.KeyName = aws.String(v.(string))
  1034  	}
  1035  
  1036  	blockDevices, err := readBlockDeviceMappingsFromConfig(d, conn)
  1037  	if err != nil {
  1038  		return nil, err
  1039  	}
  1040  	if len(blockDevices) > 0 {
  1041  		opts.BlockDeviceMappings = blockDevices
  1042  	}
  1043  
  1044  	return opts, nil
  1045  }
  1046  
  1047  func awsTerminateInstance(conn *ec2.EC2, id string) error {
  1048  	log.Printf("[INFO] Terminating instance: %s", id)
  1049  	req := &ec2.TerminateInstancesInput{
  1050  		InstanceIds: []*string{aws.String(id)},
  1051  	}
  1052  	if _, err := conn.TerminateInstances(req); err != nil {
  1053  		return fmt.Errorf("Error terminating instance: %s", err)
  1054  	}
  1055  
  1056  	log.Printf("[DEBUG] Waiting for instance (%s) to become terminated", id)
  1057  
  1058  	stateConf := &resource.StateChangeConf{
  1059  		Pending:    []string{"pending", "running", "shutting-down", "stopped", "stopping"},
  1060  		Target:     "terminated",
  1061  		Refresh:    InstanceStateRefreshFunc(conn, id),
  1062  		Timeout:    10 * time.Minute,
  1063  		Delay:      10 * time.Second,
  1064  		MinTimeout: 3 * time.Second,
  1065  	}
  1066  
  1067  	_, err := stateConf.WaitForState()
  1068  	if err != nil {
  1069  		return fmt.Errorf(
  1070  			"Error waiting for instance (%s) to terminate: %s", id, err)
  1071  	}
  1072  
  1073  	return nil
  1074  }
  1075  
  1076  func iamInstanceProfileArnToName(ip *ec2.IamInstanceProfile) string {
  1077  	if ip == nil || ip.Arn == nil {
  1078  		return ""
  1079  	}
  1080  	return strings.Split(*ip.Arn, "/")[1]
  1081  }