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