-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
resource_aws_instance.go
1691 lines (1457 loc) · 48.9 KB
/
resource_aws_instance.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package aws
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAwsInstanceCreate,
Read: resourceAwsInstanceRead,
Update: resourceAwsInstanceUpdate,
Delete: resourceAwsInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
SchemaVersion: 1,
MigrateState: resourceAwsInstanceMigrateState,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"ami": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"associate_public_ip_address": {
Type: schema.TypeBool,
ForceNew: true,
Computed: true,
Optional: true,
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"placement_group": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
},
"key_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"subnet_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"private_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"source_dest_check": {
Type: schema.TypeBool,
Optional: true,
Default: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
// Suppress diff if network_interface is set
_, ok := d.GetOk("network_interface")
return ok
},
},
"user_data": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
StateFunc: func(v interface{}) string {
switch v.(type) {
case string:
return userDataHashSum(v.(string))
default:
return ""
}
},
},
"security_groups": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"vpc_security_group_ids": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"public_dns": {
Type: schema.TypeString,
Computed: true,
},
// TODO: Deprecate me v0.10.0
"network_interface_id": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Please use `primary_network_interface_id` instead",
},
"primary_network_interface_id": {
Type: schema.TypeString,
Computed: true,
},
"network_interface": {
ConflictsWith: []string{"associate_public_ip_address", "subnet_id", "private_ip", "vpc_security_group_ids", "security_groups", "ipv6_addresses", "ipv6_address_count", "source_dest_check"},
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"delete_on_termination": {
Type: schema.TypeBool,
Default: false,
Optional: true,
ForceNew: true,
},
"network_interface_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"device_index": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
},
},
},
"public_ip": {
Type: schema.TypeString,
Computed: true,
},
"instance_state": {
Type: schema.TypeString,
Computed: true,
},
"private_dns": {
Type: schema.TypeString,
Computed: true,
},
"ebs_optimized": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"disable_api_termination": {
Type: schema.TypeBool,
Optional: true,
},
"instance_initiated_shutdown_behavior": {
Type: schema.TypeString,
Optional: true,
},
"monitoring": {
Type: schema.TypeBool,
Optional: true,
},
"iam_instance_profile": {
Type: schema.TypeString,
Optional: true,
},
"ipv6_address_count": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Computed: true,
},
"ipv6_addresses": {
Type: schema.TypeList,
Optional: true,
Computed: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"tenancy": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"tags": tagsSchema(),
"volume_tags": tagsSchemaComputed(),
"block_device": {
Type: schema.TypeMap,
Optional: true,
Removed: "Split out into three sub-types; see Changelog and Docs",
},
"ebs_block_device": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"delete_on_termination": {
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
},
"device_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"encrypted": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
},
"iops": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"volume_size": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"volume_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
},
Set: func(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["device_name"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["snapshot_id"].(string)))
return hashcode.String(buf.String())
},
},
"ephemeral_block_device": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"device_name": {
Type: schema.TypeString,
Required: true,
},
"virtual_name": {
Type: schema.TypeString,
Optional: true,
},
"no_device": {
Type: schema.TypeBool,
Optional: true,
},
},
},
Set: func(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["device_name"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["virtual_name"].(string)))
if v, ok := m["no_device"].(bool); ok && v {
buf.WriteString(fmt.Sprintf("%t-", v))
}
return hashcode.String(buf.String())
},
},
"root_block_device": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
// "You can only modify the volume size, volume type, and Delete on
// Termination flag on the block device mapping entry for the root
// device volume." - bit.ly/ec2bdmap
Schema: map[string]*schema.Schema{
"delete_on_termination": {
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
},
"iops": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"volume_size": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"volume_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
},
},
},
}
}
func resourceAwsInstanceCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
instanceOpts, err := buildAwsInstanceOpts(d, meta)
if err != nil {
return err
}
// Build the creation struct
runOpts := &ec2.RunInstancesInput{
BlockDeviceMappings: instanceOpts.BlockDeviceMappings,
DisableApiTermination: instanceOpts.DisableAPITermination,
EbsOptimized: instanceOpts.EBSOptimized,
Monitoring: instanceOpts.Monitoring,
IamInstanceProfile: instanceOpts.IAMInstanceProfile,
ImageId: instanceOpts.ImageID,
InstanceInitiatedShutdownBehavior: instanceOpts.InstanceInitiatedShutdownBehavior,
InstanceType: instanceOpts.InstanceType,
Ipv6AddressCount: instanceOpts.Ipv6AddressCount,
Ipv6Addresses: instanceOpts.Ipv6Addresses,
KeyName: instanceOpts.KeyName,
MaxCount: aws.Int64(int64(1)),
MinCount: aws.Int64(int64(1)),
NetworkInterfaces: instanceOpts.NetworkInterfaces,
Placement: instanceOpts.Placement,
PrivateIpAddress: instanceOpts.PrivateIPAddress,
SecurityGroupIds: instanceOpts.SecurityGroupIDs,
SecurityGroups: instanceOpts.SecurityGroups,
SubnetId: instanceOpts.SubnetID,
UserData: instanceOpts.UserData64,
}
_, ipv6CountOk := d.GetOk("ipv6_address_count")
_, ipv6AddressOk := d.GetOk("ipv6_addresses")
if ipv6AddressOk && ipv6CountOk {
return fmt.Errorf("Only 1 of `ipv6_address_count` or `ipv6_addresses` can be specified")
}
restricted := meta.(*AWSClient).IsGovCloud() || meta.(*AWSClient).IsChinaCloud()
if !restricted {
tagsSpec := make([]*ec2.TagSpecification, 0)
if v, ok := d.GetOk("tags"); ok {
tags := tagsFromMap(v.(map[string]interface{}))
spec := &ec2.TagSpecification{
ResourceType: aws.String("instance"),
Tags: tags,
}
tagsSpec = append(tagsSpec, spec)
}
if v, ok := d.GetOk("volume_tags"); ok {
tags := tagsFromMap(v.(map[string]interface{}))
spec := &ec2.TagSpecification{
ResourceType: aws.String("volume"),
Tags: tags,
}
tagsSpec = append(tagsSpec, spec)
}
if len(tagsSpec) > 0 {
runOpts.TagSpecifications = tagsSpec
}
}
// Create the instance
log.Printf("[DEBUG] Run configuration: %s", runOpts)
var runResp *ec2.Reservation
err = resource.Retry(30*time.Second, func() *resource.RetryError {
var err error
runResp, err = conn.RunInstances(runOpts)
// IAM instance profiles can take ~10 seconds to propagate in AWS:
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console
if isAWSErr(err, "InvalidParameterValue", "Invalid IAM Instance Profile") {
log.Print("[DEBUG] Invalid IAM Instance Profile referenced, retrying...")
return resource.RetryableError(err)
}
// IAM roles can also take time to propagate in AWS:
if isAWSErr(err, "InvalidParameterValue", " has no associated IAM Roles") {
log.Print("[DEBUG] IAM Instance Profile appears to have no IAM roles, retrying...")
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
})
// Warn if the AWS Error involves group ids, to help identify situation
// where a user uses group ids in security_groups for the Default VPC.
// See https://github.com/hashicorp/terraform/issues/3798
if isAWSErr(err, "InvalidParameterValue", "groupId is invalid") {
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())
}
if err != nil {
return fmt.Errorf("Error launching source instance: %s", err)
}
if runResp == nil || len(runResp.Instances) == 0 {
return errors.New("Error launching source instance: no instances returned in response")
}
instance := runResp.Instances[0]
log.Printf("[INFO] Instance ID: %s", *instance.InstanceId)
// Store the resulting ID so we can look this up later
d.SetId(*instance.InstanceId)
// Wait for the instance to become running so we can get some attributes
// that aren't available until later.
log.Printf(
"[DEBUG] Waiting for instance (%s) to become running",
*instance.InstanceId)
stateConf := &resource.StateChangeConf{
Pending: []string{"pending"},
Target: []string{"running"},
Refresh: InstanceStateRefreshFunc(conn, *instance.InstanceId, "terminated"),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
instanceRaw, err := stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for instance (%s) to become ready: %s",
*instance.InstanceId, err)
}
instance = instanceRaw.(*ec2.Instance)
// Initialize the connection info
if instance.PublicIpAddress != nil {
d.SetConnInfo(map[string]string{
"type": "ssh",
"host": *instance.PublicIpAddress,
})
} else if instance.PrivateIpAddress != nil {
d.SetConnInfo(map[string]string{
"type": "ssh",
"host": *instance.PrivateIpAddress,
})
}
// Update if we need to
return resourceAwsInstanceUpdate(d, meta)
}
func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
resp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(d.Id())},
})
if err != nil {
// If the instance was not found, return nil so that we can show
// that the instance is gone.
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" {
d.SetId("")
return nil
}
// Some other error, report it
return err
}
// If nothing was found, then return no state
if len(resp.Reservations) == 0 {
d.SetId("")
return nil
}
instance := resp.Reservations[0].Instances[0]
if instance.State != nil {
// If the instance is terminated, then it is gone
if *instance.State.Name == "terminated" {
d.SetId("")
return nil
}
d.Set("instance_state", instance.State.Name)
}
if instance.Placement != nil {
d.Set("availability_zone", instance.Placement.AvailabilityZone)
}
if instance.Placement.Tenancy != nil {
d.Set("tenancy", instance.Placement.Tenancy)
}
d.Set("ami", instance.ImageId)
d.Set("instance_type", instance.InstanceType)
d.Set("key_name", instance.KeyName)
d.Set("public_dns", instance.PublicDnsName)
d.Set("public_ip", instance.PublicIpAddress)
d.Set("private_dns", instance.PrivateDnsName)
d.Set("private_ip", instance.PrivateIpAddress)
d.Set("iam_instance_profile", iamInstanceProfileArnToName(instance.IamInstanceProfile))
// Set configured Network Interface Device Index Slice
// We only want to read, and populate state for the configured network_interface attachments. Otherwise, other
// resources have the potential to attach network interfaces to the instance, and cause a perpetual create/destroy
// diff. We should only read on changes configured for this specific resource because of this.
var configuredDeviceIndexes []int
if v, ok := d.GetOk("network_interface"); ok {
vL := v.(*schema.Set).List()
for _, vi := range vL {
mVi := vi.(map[string]interface{})
configuredDeviceIndexes = append(configuredDeviceIndexes, mVi["device_index"].(int))
}
}
var ipv6Addresses []string
if len(instance.NetworkInterfaces) > 0 {
var primaryNetworkInterface ec2.InstanceNetworkInterface
var networkInterfaces []map[string]interface{}
for _, iNi := range instance.NetworkInterfaces {
ni := make(map[string]interface{})
if *iNi.Attachment.DeviceIndex == 0 {
primaryNetworkInterface = *iNi
}
// If the attached network device is inside our configuration, refresh state with values found.
// Otherwise, assume the network device was attached via an outside resource.
for _, index := range configuredDeviceIndexes {
if index == int(*iNi.Attachment.DeviceIndex) {
ni["device_index"] = *iNi.Attachment.DeviceIndex
ni["network_interface_id"] = *iNi.NetworkInterfaceId
ni["delete_on_termination"] = *iNi.Attachment.DeleteOnTermination
}
}
// Don't add empty network interfaces to schema
if len(ni) == 0 {
continue
}
networkInterfaces = append(networkInterfaces, ni)
}
if err := d.Set("network_interface", networkInterfaces); err != nil {
return fmt.Errorf("Error setting network_interfaces: %v", err)
}
// Set primary network interface details
// If an instance is shutting down, network interfaces are detached, and attributes may be nil,
// need to protect against nil pointer dereferences
if primaryNetworkInterface.SubnetId != nil {
d.Set("subnet_id", primaryNetworkInterface.SubnetId)
}
if primaryNetworkInterface.NetworkInterfaceId != nil {
d.Set("network_interface_id", primaryNetworkInterface.NetworkInterfaceId) // TODO: Deprecate me v0.10.0
d.Set("primary_network_interface_id", primaryNetworkInterface.NetworkInterfaceId)
}
if primaryNetworkInterface.Ipv6Addresses != nil {
d.Set("ipv6_address_count", len(primaryNetworkInterface.Ipv6Addresses))
}
if primaryNetworkInterface.SourceDestCheck != nil {
d.Set("source_dest_check", primaryNetworkInterface.SourceDestCheck)
}
d.Set("associate_public_ip_address", primaryNetworkInterface.Association != nil)
for _, address := range primaryNetworkInterface.Ipv6Addresses {
ipv6Addresses = append(ipv6Addresses, *address.Ipv6Address)
}
} else {
d.Set("subnet_id", instance.SubnetId)
d.Set("network_interface_id", "") // TODO: Deprecate me v0.10.0
d.Set("primary_network_interface_id", "")
}
if err := d.Set("ipv6_addresses", ipv6Addresses); err != nil {
log.Printf("[WARN] Error setting ipv6_addresses for AWS Instance (%s): %s", d.Id(), err)
}
d.Set("ebs_optimized", instance.EbsOptimized)
if instance.SubnetId != nil && *instance.SubnetId != "" {
d.Set("source_dest_check", instance.SourceDestCheck)
}
if instance.Monitoring != nil && instance.Monitoring.State != nil {
monitoringState := *instance.Monitoring.State
d.Set("monitoring", monitoringState == "enabled" || monitoringState == "pending")
}
d.Set("tags", tagsToMap(instance.Tags))
if err := readVolumeTags(conn, d); err != nil {
return err
}
if err := readSecurityGroups(d, instance); err != nil {
return err
}
if err := readBlockDevices(d, instance, conn); err != nil {
return err
}
if _, ok := d.GetOk("ephemeral_block_device"); !ok {
d.Set("ephemeral_block_device", []interface{}{})
}
// Instance attributes
{
attr, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
Attribute: aws.String("disableApiTermination"),
InstanceId: aws.String(d.Id()),
})
if err != nil {
return err
}
d.Set("disable_api_termination", attr.DisableApiTermination.Value)
}
{
attr, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
Attribute: aws.String(ec2.InstanceAttributeNameUserData),
InstanceId: aws.String(d.Id()),
})
if err != nil {
return err
}
if attr.UserData.Value != nil {
d.Set("user_data", userDataHashSum(*attr.UserData.Value))
}
}
return nil
}
func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
d.Partial(true)
restricted := meta.(*AWSClient).IsGovCloud() || meta.(*AWSClient).IsChinaCloud()
if d.HasChange("tags") {
if !d.IsNewResource() || restricted {
if err := setTags(conn, d); err != nil {
return err
} else {
d.SetPartial("tags")
}
}
}
if d.HasChange("volume_tags") {
if !d.IsNewResource() || !restricted {
if err := setVolumeTags(conn, d); err != nil {
return err
} else {
d.SetPartial("volume_tags")
}
}
}
if d.HasChange("iam_instance_profile") && !d.IsNewResource() {
request := &ec2.DescribeIamInstanceProfileAssociationsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("instance-id"),
Values: []*string{aws.String(d.Id())},
},
},
}
resp, err := conn.DescribeIamInstanceProfileAssociations(request)
if err != nil {
return err
}
// An Iam Instance Profile has been provided and is pending a change
// This means it is an association or a replacement to an association
if _, ok := d.GetOk("iam_instance_profile"); ok {
// Does not have an Iam Instance Profile associated with it, need to associate
if len(resp.IamInstanceProfileAssociations) == 0 {
_, err := conn.AssociateIamInstanceProfile(&ec2.AssociateIamInstanceProfileInput{
InstanceId: aws.String(d.Id()),
IamInstanceProfile: &ec2.IamInstanceProfileSpecification{
Name: aws.String(d.Get("iam_instance_profile").(string)),
},
})
if err != nil {
return err
}
} else {
// Has an Iam Instance Profile associated with it, need to replace the association
associationId := resp.IamInstanceProfileAssociations[0].AssociationId
_, err := conn.ReplaceIamInstanceProfileAssociation(&ec2.ReplaceIamInstanceProfileAssociationInput{
AssociationId: associationId,
IamInstanceProfile: &ec2.IamInstanceProfileSpecification{
Name: aws.String(d.Get("iam_instance_profile").(string)),
},
})
if err != nil {
return err
}
}
// An Iam Instance Profile has _not_ been provided but is pending a change. This means there is a pending removal
} else {
if len(resp.IamInstanceProfileAssociations) > 0 {
// Has an Iam Instance Profile associated with it, need to remove the association
associationId := resp.IamInstanceProfileAssociations[0].AssociationId
_, err := conn.DisassociateIamInstanceProfile(&ec2.DisassociateIamInstanceProfileInput{
AssociationId: associationId,
})
if err != nil {
return err
}
}
}
}
// SourceDestCheck can only be modified on an instance without manually specified network interfaces.
// SourceDestCheck, in that case, is configured at the network interface level
if _, ok := d.GetOk("network_interface"); !ok {
// If we have a new resource and source_dest_check is still true, don't modify
sourceDestCheck := d.Get("source_dest_check").(bool)
if d.HasChange("source_dest_check") || d.IsNewResource() && !sourceDestCheck {
// SourceDestCheck can only be set on VPC instances
// AWS will return an error of InvalidParameterCombination if we attempt
// to modify the source_dest_check of an instance in EC2 Classic
log.Printf("[INFO] Modifying `source_dest_check` on Instance %s", d.Id())
_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
InstanceId: aws.String(d.Id()),
SourceDestCheck: &ec2.AttributeBooleanValue{
Value: aws.Bool(sourceDestCheck),
},
})
if err != nil {
if ec2err, ok := err.(awserr.Error); ok {
// Tolerate InvalidParameterCombination error in Classic, otherwise
// return the error
if "InvalidParameterCombination" != ec2err.Code() {
return err
}
log.Printf("[WARN] Attempted to modify SourceDestCheck on non VPC instance: %s", ec2err.Message())
}
}
}
}
if d.HasChange("vpc_security_group_ids") {
var groups []*string
if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 {
for _, v := range v.List() {
groups = append(groups, aws.String(v.(string)))
}
}
// If a user has multiple network interface attachments on the target EC2 instance, simply modifying the
// instance attributes via a `ModifyInstanceAttributes()` request would fail with the following error message:
// "There are multiple interfaces attached to instance 'i-XX'. Please specify an interface ID for the operation instead."
// Thus, we need to actually modify the primary network interface for the new security groups, as the primary
// network interface is where we modify/create security group assignments during Create.
log.Printf("[INFO] Modifying `vpc_security_group_ids` on Instance %q", d.Id())
instances, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(d.Id())},
})
if err != nil {
return err
}
instance := instances.Reservations[0].Instances[0]
var primaryInterface ec2.InstanceNetworkInterface
for _, ni := range instance.NetworkInterfaces {
if *ni.Attachment.DeviceIndex == 0 {
primaryInterface = *ni
}
}
if primaryInterface.NetworkInterfaceId == nil {
log.Print("[Error] Attempted to set vpc_security_group_ids on an instance without a primary network interface")
return fmt.Errorf(
"Failed to update vpc_security_group_ids on %q, which does not contain a primary network interface",
d.Id())
}
if _, err := conn.ModifyNetworkInterfaceAttribute(&ec2.ModifyNetworkInterfaceAttributeInput{
NetworkInterfaceId: primaryInterface.NetworkInterfaceId,
Groups: groups,
}); err != nil {
return err
}
}
if d.HasChange("instance_type") && !d.IsNewResource() {
log.Printf("[INFO] Stopping Instance %q for instance_type change", d.Id())
_, err := conn.StopInstances(&ec2.StopInstancesInput{
InstanceIds: []*string{aws.String(d.Id())},
})
stateConf := &resource.StateChangeConf{
Pending: []string{"pending", "running", "shutting-down", "stopped", "stopping"},
Target: []string{"stopped"},
Refresh: InstanceStateRefreshFunc(conn, d.Id(), ""),
Timeout: d.Timeout(schema.TimeoutUpdate),
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for instance (%s) to stop: %s", d.Id(), err)
}
log.Printf("[INFO] Modifying instance type %s", d.Id())
_, err = conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
InstanceId: aws.String(d.Id()),
InstanceType: &ec2.AttributeValue{
Value: aws.String(d.Get("instance_type").(string)),
},
})
if err != nil {
return err
}
log.Printf("[INFO] Starting Instance %q after instance_type change", d.Id())
_, err = conn.StartInstances(&ec2.StartInstancesInput{
InstanceIds: []*string{aws.String(d.Id())},
})
stateConf = &resource.StateChangeConf{
Pending: []string{"pending", "stopped"},
Target: []string{"running"},
Refresh: InstanceStateRefreshFunc(conn, d.Id(), "terminated"),
Timeout: d.Timeout(schema.TimeoutUpdate),
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for instance (%s) to become ready: %s",
d.Id(), err)
}
}
if d.HasChange("disable_api_termination") {
_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
InstanceId: aws.String(d.Id()),
DisableApiTermination: &ec2.AttributeBooleanValue{
Value: aws.Bool(d.Get("disable_api_termination").(bool)),
},
})
if err != nil {
return err
}
}
if d.HasChange("instance_initiated_shutdown_behavior") {
log.Printf("[INFO] Modifying instance %s", d.Id())
_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
InstanceId: aws.String(d.Id()),
InstanceInitiatedShutdownBehavior: &ec2.AttributeValue{
Value: aws.String(d.Get("instance_initiated_shutdown_behavior").(string)),
},
})
if err != nil {
return err
}
}
if d.HasChange("monitoring") {
var mErr error
if d.Get("monitoring").(bool) {
log.Printf("[DEBUG] Enabling monitoring for Instance (%s)", d.Id())
_, mErr = conn.MonitorInstances(&ec2.MonitorInstancesInput{
InstanceIds: []*string{aws.String(d.Id())},
})
} else {
log.Printf("[DEBUG] Disabling monitoring for Instance (%s)", d.Id())
_, mErr = conn.UnmonitorInstances(&ec2.UnmonitorInstancesInput{
InstanceIds: []*string{aws.String(d.Id())},
})
}
if mErr != nil {
return fmt.Errorf("[WARN] Error updating Instance monitoring: %s", mErr)
}
}
// TODO(mitchellh): wait for the attributes we modified to
// persist the change...
d.Partial(false)
return resourceAwsInstanceRead(d, meta)
}
func resourceAwsInstanceDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
if err := awsTerminateInstance(conn, d.Id(), d); err != nil {
return err
}
d.SetId("")