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