github.com/keshavdv/terraform@v0.7.0-rc2.0.20160711232630-d69256dcb425/builtin/providers/aws/resource_aws_instance.go (about)

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