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