-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
resource_aws_instance.go
2692 lines (2404 loc) · 86.7 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"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/aws-sdk-go-base/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode"
"github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags"
tfec2 "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/ec2"
"github.com/terraform-providers/terraform-provider-aws/aws/internal/service/ec2/waiter"
"github.com/terraform-providers/terraform-provider-aws/aws/internal/tfresource"
)
func resourceAwsInstance() *schema.Resource {
//lintignore:R011
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(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"ami": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"arn": {
Type: schema.TypeString,
Computed: 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,
},
"cpu_core_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"cpu_threads_per_core": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"credit_specification": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if old == "1" && new == "0" {
return true
}
return false
},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cpu_credits": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
// Only work with existing instances
if d.Id() == "" {
return false
}
// Only work with missing configurations
if new != "" {
return false
}
// Only work when already set in Terraform state
if old == "" {
return false
}
return true
},
},
},
},
},
"disable_api_termination": {
Type: schema.TypeBool,
Optional: true,
},
"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,
DiffSuppressFunc: iopsDiffSuppressFunc,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"tags": tagsSchemaConflictsWith([]string{"volume_tags"}),
"throughput": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
DiffSuppressFunc: throughputDiffSuppressFunc,
},
"volume_id": {
Type: schema.TypeString,
Computed: true,
},
"volume_size": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"volume_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice(ec2.VolumeType_Values(), false),
},
},
},
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())
},
},
"ebs_optimized": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"enclave_options": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
},
},
},
},
"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,
},
"no_device": {
Type: schema.TypeBool,
Optional: true,
},
"virtual_name": {
Type: schema.TypeString,
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())
},
},
"get_password_data": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"hibernation": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"host_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"iam_instance_profile": {
Type: schema.TypeString,
Optional: true,
},
"instance_initiated_shutdown_behavior": {
Type: schema.TypeString,
Optional: true,
},
"instance_state": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Required: 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,
ValidateFunc: validation.IsIPv6Address,
},
},
"key_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"metadata_options": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"http_endpoint": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{ec2.InstanceMetadataEndpointStateEnabled, ec2.InstanceMetadataEndpointStateDisabled}, false),
},
"http_put_response_hop_limit": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(1, 64),
},
"http_tokens": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{ec2.HttpTokensStateOptional, ec2.HttpTokensStateRequired}, false),
},
},
},
},
"monitoring": {
Type: schema.TypeBool,
Optional: true,
},
"network_interface": {
ConflictsWith: []string{"associate_public_ip_address", "subnet_id", "private_ip", "secondary_private_ips", "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,
},
"device_index": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"network_interface_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
},
},
"outpost_arn": {
Type: schema.TypeString,
Computed: true,
},
"password_data": {
Type: schema.TypeString,
Computed: true,
},
"placement_group": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"primary_network_interface_id": {
Type: schema.TypeString,
Computed: true,
},
"private_dns": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.Any(
validation.StringIsEmpty,
validation.IsIPv4Address,
),
},
"public_dns": {
Type: schema.TypeString,
Computed: true,
},
"public_ip": {
Type: schema.TypeString,
Computed: true,
},
"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."
// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html
Schema: map[string]*schema.Schema{
"delete_on_termination": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"device_name": {
Type: schema.TypeString,
Computed: true,
},
"encrypted": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
},
"iops": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
DiffSuppressFunc: iopsDiffSuppressFunc,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"tags": tagsSchemaConflictsWith([]string{"volume_tags"}),
"throughput": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
DiffSuppressFunc: throughputDiffSuppressFunc,
},
"volume_id": {
Type: schema.TypeString,
Computed: true,
},
"volume_size": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"volume_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice(ec2.VolumeType_Values(), false),
},
},
},
},
"secondary_private_ips": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.IsIPv4Address,
},
},
"security_groups": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"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
},
},
"subnet_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"tags": tagsSchema(),
"tenancy": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
ec2.TenancyDedicated,
ec2.TenancyDefault,
ec2.TenancyHost,
}, false),
},
"user_data": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"user_data_base64"},
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
// Sometimes the EC2 API responds with the equivalent, empty SHA1 sum
// echo -n "" | shasum
if (old == "da39a3ee5e6b4b0d3255bfef95601890afd80709" && new == "") ||
(old == "" && new == "da39a3ee5e6b4b0d3255bfef95601890afd80709") {
return true
}
return false
},
StateFunc: func(v interface{}) string {
switch v := v.(type) {
case string:
return userDataHashSum(v)
default:
return ""
}
},
ValidateFunc: validation.StringLenBetween(0, 16384),
},
"user_data_base64": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"user_data"},
ValidateFunc: func(v interface{}, name string) (warns []string, errs []error) {
s := v.(string)
if !isBase64Encoded([]byte(s)) {
errs = append(errs, fmt.Errorf(
"%s: must be base64-encoded", name,
))
}
return
},
},
"volume_tags": tagsSchema(),
"vpc_security_group_ids": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
},
}
}
func iopsDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
// Suppress diff if volume_type is not io1, io2, or gp3 and iops is unset or configured as 0
i := strings.LastIndexByte(k, '.')
vt := k[:i+1] + "volume_type"
v := d.Get(vt).(string)
return (strings.ToLower(v) != ec2.VolumeTypeIo1 && strings.ToLower(v) != ec2.VolumeTypeIo2 && strings.ToLower(v) != ec2.VolumeTypeGp3) && new == "0"
}
func throughputDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
// Suppress diff if volume_type is not gp3 and throughput is unset or configured as 0
i := strings.LastIndexByte(k, '.')
vt := k[:i+1] + "volume_type"
v := d.Get(vt).(string)
return strings.ToLower(v) != ec2.VolumeTypeGp3 && new == "0"
}
func resourceAwsInstanceCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
instanceOpts, err := buildAwsInstanceOpts(d, meta)
if err != nil {
return err
}
tagSpecifications := ec2TagSpecificationsFromMap(d.Get("tags").(map[string]interface{}), ec2.ResourceTypeInstance)
tagSpecifications = append(tagSpecifications, ec2TagSpecificationsFromMap(d.Get("volume_tags").(map[string]interface{}), ec2.ResourceTypeVolume)...)
// 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,
CreditSpecification: instanceOpts.CreditSpecification,
CpuOptions: instanceOpts.CpuOptions,
HibernationOptions: instanceOpts.HibernationOptions,
MetadataOptions: instanceOpts.MetadataOptions,
EnclaveOptions: instanceOpts.EnclaveOptions,
TagSpecifications: tagSpecifications,
}
_, 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")
}
// 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)
}
if err != nil {
return resource.NonRetryableError(err)
}
return nil
})
if isResourceTimeoutError(err) {
runResp, err = conn.RunInstances(runOpts)
}
// 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: %w", "https://terraform.io/docs/providers/aws/r/instance.html", err)
}
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", aws.StringValue(instance.InstanceId))
// Store the resulting ID so we can look this up later
d.SetId(aws.StringValue(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",
aws.StringValue(instance.InstanceId))
stateConf := &resource.StateChangeConf{
Pending: []string{ec2.InstanceStateNamePending},
Target: []string{ec2.InstanceStateNameRunning},
Refresh: InstanceStateRefreshFunc(conn, aws.StringValue(instance.InstanceId), []string{ec2.InstanceStateNameTerminated, ec2.InstanceStateNameShuttingDown}),
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",
aws.StringValue(instance.InstanceId), err)
}
instance = instanceRaw.(*ec2.Instance)
// Initialize the connection info
if instance.PublicIpAddress != nil {
d.SetConnInfo(map[string]string{
"type": "ssh",
"host": aws.StringValue(instance.PublicIpAddress),
})
} else if instance.PrivateIpAddress != nil {
d.SetConnInfo(map[string]string{
"type": "ssh",
"host": aws.StringValue(instance.PrivateIpAddress),
})
}
// tags in root_block_device and ebs_block_device
blockDeviceTagsToCreate := map[string]map[string]interface{}{}
if v, ok := d.GetOk("root_block_device"); ok {
vL := v.([]interface{})
for _, v := range vL {
bd := v.(map[string]interface{})
if blockDeviceTags, ok := bd["tags"].(map[string]interface{}); ok && len(blockDeviceTags) > 0 {
if rootVolumeId := getRootVolumeId(instance); rootVolumeId != "" {
blockDeviceTagsToCreate[rootVolumeId] = blockDeviceTags
}
}
}
}
if v, ok := d.GetOk("ebs_block_device"); ok {
vL := v.(*schema.Set).List()
for _, v := range vL {
bd := v.(map[string]interface{})
if blockDeviceTags, ok := bd["tags"].(map[string]interface{}); ok && len(blockDeviceTags) > 0 {
devName := bd["device_name"].(string)
if volumeId := getVolumeIdByDeviceName(instance, devName); volumeId != "" {
blockDeviceTagsToCreate[volumeId] = blockDeviceTags
}
}
}
}
for vol, blockDeviceTags := range blockDeviceTagsToCreate {
if err := keyvaluetags.Ec2CreateTags(conn, vol, blockDeviceTags); err != nil {
log.Printf("[ERR] Error creating tags for EBS volume %s: %s", vol, err)
}
}
// Update if we need to
return resourceAwsInstanceUpdate(d, meta)
}
func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig
instance, err := resourceAwsInstanceFindByID(conn, d.Id())
if err != nil {
// If the instance was not found, return nil so that we can show
// that the instance is gone.
if isAWSErr(err, "InvalidInstanceID.NotFound", "") {
d.SetId("")
return nil
}
// Some other error, report it
return err
}
// If nothing was found, then return no state
if instance == nil {
d.SetId("")
return nil
}
if instance.State != nil {
// If the instance is terminated, then it is gone
if aws.StringValue(instance.State.Name) == ec2.InstanceStateNameTerminated {
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.GroupName != nil {
d.Set("placement_group", instance.Placement.GroupName)
}
if instance.Placement.Tenancy != nil {
d.Set("tenancy", instance.Placement.Tenancy)
}
if instance.Placement.HostId != nil {
d.Set("host_id", instance.Placement.HostId)
}
if instance.CpuOptions != nil {
d.Set("cpu_core_count", instance.CpuOptions.CoreCount)
d.Set("cpu_threads_per_core", instance.CpuOptions.ThreadsPerCore)
}
if instance.HibernationOptions != nil {
d.Set("hibernation", instance.HibernationOptions.Configured)
}
if err := d.Set("metadata_options", flattenEc2InstanceMetadataOptions(instance.MetadataOptions)); err != nil {
return fmt.Errorf("error setting metadata_options: %s", err)
}
if err := d.Set("enclave_options", flattenEc2EnclaveOptions(instance.EnclaveOptions)); err != nil {
return fmt.Errorf("error setting enclave_options: %s", err)
}
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("outpost_arn", instance.OutpostArn)
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 secondaryPrivateIPs []string
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 aws.Int64Value(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(aws.Int64Value(iNi.Attachment.DeviceIndex)) {
ni["device_index"] = aws.Int64Value(iNi.Attachment.DeviceIndex)
ni["network_interface_id"] = aws.StringValue(iNi.NetworkInterfaceId)
ni["delete_on_termination"] = aws.BoolValue(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("primary_network_interface_id", primaryNetworkInterface.NetworkInterfaceId)
}
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.PrivateIpAddresses {
if !aws.BoolValue(address.Primary) {
secondaryPrivateIPs = append(secondaryPrivateIPs, aws.StringValue(address.PrivateIpAddress))
}
}
for _, address := range primaryNetworkInterface.Ipv6Addresses {
ipv6Addresses = append(ipv6Addresses, aws.StringValue(address.Ipv6Address))
}
} else {
d.Set("associate_public_ip_address", instance.PublicIpAddress != nil)
d.Set("ipv6_address_count", 0)
d.Set("primary_network_interface_id", "")
d.Set("subnet_id", instance.SubnetId)
}
if err := d.Set("secondary_private_ips", secondaryPrivateIPs); err != nil {
return fmt.Errorf("Error setting private_ips for AWS Instance (%s): %w", d.Id(), err)
}
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 aws.StringValue(instance.SubnetId) != "" {
d.Set("source_dest_check", instance.SourceDestCheck)
}
if instance.Monitoring != nil && instance.Monitoring.State != nil {
monitoringState := aws.StringValue(instance.Monitoring.State)
d.Set("monitoring", monitoringState == ec2.MonitoringStateEnabled || monitoringState == ec2.MonitoringStatePending)
}
if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(instance.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil {
return fmt.Errorf("error setting tags: %s", err)
}
if _, ok := d.GetOk("volume_tags"); ok && !blockDeviceTagsDefined(d) {
volumeTags, err := readVolumeTags(conn, d.Id())
if err != nil {
return err
}
if err := d.Set("volume_tags", keyvaluetags.Ec2KeyValueTags(volumeTags).IgnoreAws().Map()); err != nil {
return fmt.Errorf("error setting volume_tags: %s", err)
}
}
if err := readSecurityGroups(d, instance, conn); 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{}{})
}
// ARN
arn := arn.ARN{
Partition: meta.(*AWSClient).partition,
Region: meta.(*AWSClient).region,
Service: "ec2",
AccountID: meta.(*AWSClient).accountid,
Resource: fmt.Sprintf("instance/%s", d.Id()),
}
d.Set("arn", arn.String())
// 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 != nil && attr.UserData.Value != nil {
// Since user_data and user_data_base64 conflict with each other,
// we'll only set one or the other here to avoid a perma-diff.
// Since user_data_base64 was added later, we'll prefer to set
// user_data.
_, b64 := d.GetOk("user_data_base64")
if b64 {
d.Set("user_data_base64", attr.UserData.Value)
} else {
d.Set("user_data", userDataHashSum(aws.StringValue(attr.UserData.Value)))
}
}
}
// AWS Standard will return InstanceCreditSpecification.NotSupported errors for EC2 Instance IDs outside T2 and T3 instance types
// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/8055
if strings.HasPrefix(aws.StringValue(instance.InstanceType), "t2") || strings.HasPrefix(aws.StringValue(instance.InstanceType), "t3") {
creditSpecifications, err := getCreditSpecifications(conn, d.Id())
// Ignore UnsupportedOperation errors for AWS China and GovCloud (US)
// Reference: https://github.com/hashicorp/terraform-provider-aws/pull/4362
if err != nil && !isAWSErr(err, "UnsupportedOperation", "") {
return fmt.Errorf("error getting EC2 Instance (%s) Credit Specifications: %s", d.Id(), err)
}
if err := d.Set("credit_specification", creditSpecifications); err != nil {
return fmt.Errorf("error setting credit_specification: %s", err)
}
}
if d.Get("get_password_data").(bool) {
passwordData, err := getAwsEc2InstancePasswordData(aws.StringValue(instance.InstanceId), conn)
if err != nil {
return err