-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathbuilder_acc_test.go
More file actions
2133 lines (1872 loc) · 56.7 KB
/
builder_acc_test.go
File metadata and controls
2133 lines (1872 loc) · 56.7 KB
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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
/*
deregister the test image with
aws ec2 deregister-image --image-id $(aws ec2 describe-images --output text --filters "Name=name,Values=packer-test-packer-test-dereg" --query 'Images[*].{ID:ImageId}')
*/
//nolint:unparam
package ebs
import (
_ "embed"
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/packer-plugin-amazon/builder/common"
awscommon "github.com/hashicorp/packer-plugin-amazon/builder/common"
amazon_acc "github.com/hashicorp/packer-plugin-amazon/builder/ebs/acceptance"
"github.com/hashicorp/packer-plugin-sdk/acctest"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
)
func TestAccBuilder_EbsBasic(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: fmt.Sprintf("packer-plugin-amazon-ebs-basic-acc-test %d", time.Now().Unix()),
}
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_basic_test",
Template: fmt.Sprintf(testBuilderAccBasic, ami.Name),
Teardown: func() error {
return ami.CleanUpAmi()
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
return nil
},
}
acctest.TestPlugin(t, testCase)
}
func TestAccBuilder_EbsRegionCopy(t *testing.T) {
amiName := fmt.Sprintf("packer-test-builder-region-copy-acc-test-%d", time.Now().Unix())
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_region_copy_test",
Template: fmt.Sprintf(testBuilderAccRegionCopy, amiName),
Teardown: func() error {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: amiName,
}
_ = ami.CleanUpAmi()
ami = amazon_acc.AMIHelper{
Region: "ca-west-1",
Name: amiName,
}
_ = ami.CleanUpAmi()
return nil
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
return checkRegionCopy(amiName, []string{"us-east-1", "ca-west-1"})
},
}
acctest.TestPlugin(t, testCase)
}
func TestAccBuilder_EbsRegionsCopyWithDeprecation(t *testing.T) {
amiName := fmt.Sprintf("packer-test-builder-region-copy-deprecate-acc-test-%d", time.Now().Unix())
amis := []amazon_acc.AMIHelper{
{
Region: "us-east-1",
Name: amiName,
},
{
Region: "us-west-1",
Name: amiName,
},
}
deprecationTime := time.Now().UTC().AddDate(0, 0, 1)
deprecationTimeStr := deprecationTime.Format(time.RFC3339)
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_region_copy_with_deprecation_test",
Template: fmt.Sprintf(testBuilderAccRegionCopyDeprecated, deprecationTimeStr, amiName),
Teardown: func() error {
err := amis[0].CleanUpAmi()
if err != nil {
t.Logf("ami %s cleanup failed: %s", amis[0].Name, err)
}
err = amis[1].CleanUpAmi()
if err != nil {
t.Logf("ami %s cleanup failed: %s", amis[1].Name, err)
}
return nil
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
var errors error
err := checkRegionCopy(
amiName,
[]string{"us-east-1", "us-west-1"})
if err != nil {
errors = multierror.Append(errors, err)
}
for _, ami := range amis {
err := checkDeprecationEnabled(ami, deprecationTime)
if err != nil {
errors = multierror.Append(errors,
fmt.Errorf(
"AMI region %s: %s",
ami.Region,
err))
}
}
return errors
},
}
acctest.TestPlugin(t, testCase)
}
func checkRegionCopy(amiName string, regions []string) error {
regionSet := make(map[string]struct{})
for _, r := range regions {
regionSet[r] = struct{}{}
ami := amazon_acc.AMIHelper{
Region: r,
Name: amiName,
}
images, err := ami.GetAmi()
if err != nil || len(images) != 1 {
continue
}
delete(regionSet, r)
}
if len(regionSet) > 0 {
return fmt.Errorf("didn't copy to: %#v", regionSet)
}
return nil
}
func TestAccBuilder_EbsForceDeregister(t *testing.T) {
amiName := fmt.Sprintf("dereg %d", time.Now().Unix())
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_force_deregister_part1_test",
Template: buildForceDeregisterConfig("false", amiName),
Teardown: func() error {
// skip
return nil
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
return nil
},
}
acctest.TestPlugin(t, testCase)
testCase = &acctest.PluginTestCase{
Name: "amazon-ebs_force_deregister_part2_test",
Template: buildForceDeregisterConfig("true", amiName),
Teardown: func() error {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: amiName,
}
return ami.CleanUpAmi()
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
return nil
},
}
acctest.TestPlugin(t, testCase)
}
func TestAccBuilder_EbsForceDeleteSnapshot(t *testing.T) {
amiName := fmt.Sprintf("packer-test-dereg %d", time.Now().Unix())
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_force_delete_snapshot_part1_test",
Template: buildForceDeleteSnapshotConfig("false", amiName),
Teardown: func() error {
// skip
return nil
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
return nil
},
}
acctest.TestPlugin(t, testCase)
// Get image data by AMI name
ec2conn, _ := testEC2Conn("us-east-1")
describeInput := &ec2.DescribeImagesInput{Filters: []*ec2.Filter{
{
Name: aws.String("name"),
Values: []*string{aws.String(amiName)},
},
}}
_ = ec2conn.WaitUntilImageExists(describeInput)
imageResp, _ := ec2conn.DescribeImages(describeInput)
image := imageResp.Images[0]
// Get snapshot ids for image
snapshotIds := []*string{}
for _, device := range image.BlockDeviceMappings {
if device.Ebs != nil && device.Ebs.SnapshotId != nil {
snapshotIds = append(snapshotIds, device.Ebs.SnapshotId)
}
}
testCase = &acctest.PluginTestCase{
Name: "amazon-ebs_force_delete_snapshot_part2_test",
Template: buildForceDeleteSnapshotConfig("true", amiName),
Teardown: func() error {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: amiName,
}
return ami.CleanUpAmi()
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
return checkSnapshotsDeleted(snapshotIds)
},
}
acctest.TestPlugin(t, testCase)
}
func checkSnapshotsDeleted(snapshotIds []*string) error {
// Verify the snapshots are gone
ec2conn, _ := testEC2Conn("us-east-1")
snapshotResp, _ := ec2conn.DescribeSnapshots(
&ec2.DescribeSnapshotsInput{SnapshotIds: snapshotIds},
)
if len(snapshotResp.Snapshots) > 0 {
return fmt.Errorf("Snapshots weren't successfully deleted by `force_delete_snapshot`")
}
return nil
}
func TestAccBuilder_EbsAmiSharing(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: fmt.Sprintf("packer-sharing-acc-test %d", time.Now().Unix()),
}
missing_v := []string{}
env_vars := []string{"TESTACC_AWS_ACCOUNT_ID", "TESTACC_AWS_ORG_ARN", "TESTACC_AWS_OU_ARN"}
for _, var_name := range env_vars {
v := os.Getenv(var_name)
if v == "" {
missing_v = append(missing_v, var_name)
}
}
if len(missing_v) > 0 {
t.Skipf("%s must be set for AMI sharing test, skipping", strings.Join(missing_v, ","))
}
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_ami_sharing_test",
Template: buildSharingConfig(os.Getenv("TESTACC_AWS_ACCOUNT_ID"), os.Getenv("TESTACC_AWS_ORG_ARN"), os.Getenv("TESTACC_AWS_OU_ARN"), ami.Name),
Teardown: func() error {
return ami.CleanUpAmi()
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
return checkAMISharing(ami, 4, os.Getenv("TESTACC_AWS_ACCOUNT_ID"), "all")
},
}
acctest.TestPlugin(t, testCase)
}
func checkAMISharing(ami amazon_acc.AMIHelper, count int, uid, group string) error {
images, err := ami.GetAmi()
if err != nil || len(images) == 0 {
return fmt.Errorf("failed to find ami %s at region %s", ami.Name, ami.Region)
}
ec2conn, _ := testEC2Conn("us-east-1")
imageResp, err := ec2conn.DescribeImageAttribute(&ec2.DescribeImageAttributeInput{
Attribute: aws.String("launchPermission"),
ImageId: images[0].ImageId,
})
if err != nil {
return fmt.Errorf("Error retrieving Image Attributes for AMI %s in AMI Sharing Test: %s", ami.Name, err)
}
// Launch Permissions are in addition to the userid that created it, so if
// you add 3 additional ami_users, you expect 2 Launch Permissions here
if len(imageResp.LaunchPermissions) != count {
return fmt.Errorf("Error in Image Attributes, expected (%d) Launch Permissions, got (%d)", count, len(imageResp.LaunchPermissions))
}
userFound := false
for _, lp := range imageResp.LaunchPermissions {
if lp.UserId != nil && uid == *lp.UserId {
userFound = true
}
}
if !userFound {
return fmt.Errorf("Error in Image Attributes, expected User ID (%s) to have Launch Permissions, but was not found", uid)
}
groupFound := false
for _, lp := range imageResp.LaunchPermissions {
if lp.Group != nil && group == *lp.Group {
groupFound = true
}
}
if !groupFound {
return fmt.Errorf("Error in Image Attributes, expected Group ID (%s) to have Launch Permissions, but was not found", group)
}
return nil
}
func TestAccBuilder_EbsEncryptedBoot(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: fmt.Sprintf("packer-enc-acc-test %d", time.Now().Unix()),
}
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_encrypted_boot_test",
Template: fmt.Sprintf(testBuilderAccEncrypted, ami.Name),
Teardown: func() error {
return ami.CleanUpAmi()
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
return checkBootEncrypted(ami)
},
}
acctest.TestPlugin(t, testCase)
}
func TestAccBuilder_EbsEncryptedBootWithDeprecation(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: fmt.Sprintf("packer-enc-acc-test %d", time.Now().Unix()),
}
deprecationTime := time.Now().UTC().AddDate(0, 0, 1)
deprecationTimeStr := deprecationTime.Format(time.RFC3339)
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_encrypted_boot_with_deprecation_test",
Template: fmt.Sprintf(testBuilderAccEncryptedDeprecated, deprecationTimeStr, ami.Name),
Teardown: func() error {
return ami.CleanUpAmi()
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
deprecationCheck := checkDeprecationEnabled(ami, deprecationTime)
if deprecationCheck != nil {
return deprecationCheck
}
return checkBootEncrypted(ami)
},
}
acctest.TestPlugin(t, testCase)
}
func TestAccBuilder_EbsCopyRegionEncryptedBootWithDeprecation(t *testing.T) {
amiName := fmt.Sprintf(
"packer-test-builder-region-copy-encrypt-deprecate-acc-test-%d",
time.Now().Unix())
amis := []amazon_acc.AMIHelper{
{
Region: "us-east-1",
Name: amiName,
},
{
Region: "us-west-1",
Name: amiName,
},
}
deprecationTime := time.Now().UTC().AddDate(0, 0, 1)
deprecationTimeStr := deprecationTime.Format(time.RFC3339)
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_region_copy_encrypted_boot_with_deprecation_test",
Template: fmt.Sprintf(testBuilderAccRegionCopyEncryptedAndDeprecated, deprecationTimeStr, amiName),
Teardown: func() error {
err := amis[0].CleanUpAmi()
if err != nil {
t.Logf("ami %s cleanup failed: %s", amis[0].Name, err)
}
err = amis[1].CleanUpAmi()
if err != nil {
t.Logf("ami %s cleanup failed: %s", amis[1].Name, err)
}
return nil
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
var result error
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
err := checkRegionCopy(
amiName,
[]string{"us-east-1", "us-west-1"})
if err != nil {
result = multierror.Append(result, err)
}
for _, ami := range amis {
err := checkDeprecationEnabled(ami, deprecationTime)
if err != nil {
result = multierror.Append(result, fmt.Errorf(
"Deprectiation failed, AMI region %s: %s",
ami.Region,
err))
}
err = checkBootEncrypted(ami)
if err != nil {
result = multierror.Append(result, fmt.Errorf(
"Encryption check failed, AMI region %s: %s",
ami.Region,
err))
}
}
return result
},
}
acctest.TestPlugin(t, testCase)
}
func checkBootEncrypted(ami amazon_acc.AMIHelper) error {
images, err := ami.GetAmi()
if err != nil || len(images) == 0 {
return fmt.Errorf("failed to find ami %s at region %s", ami.Name, ami.Region)
}
// describe the image, get block devices with a snapshot
ec2conn, _ := testEC2Conn(ami.Region)
imageResp, err := ec2conn.DescribeImages(&ec2.DescribeImagesInput{
ImageIds: []*string{images[0].ImageId},
})
if err != nil {
return fmt.Errorf("Error retrieving Image Attributes for AMI (%s) in AMI Encrypted Boot Test: %s", ami.Name, err)
}
image := imageResp.Images[0] // Only requested a single AMI ID
rootDeviceName := image.RootDeviceName
for _, bd := range image.BlockDeviceMappings {
if *bd.DeviceName == *rootDeviceName {
if *bd.Ebs.Encrypted != true {
return fmt.Errorf("volume not encrypted: %s", *bd.Ebs.SnapshotId)
}
}
}
return nil
}
func TestAccBuilder_EbsSessionManagerInterface(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: fmt.Sprintf("packer-ssm-acc-test %d", time.Now().Unix()),
}
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_sessionmanager_interface_test",
Template: fmt.Sprintf(testBuilderAccSessionManagerInterface, ami.Name),
Teardown: func() error {
return ami.CleanUpAmi()
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
logs, err := os.ReadFile(logfile)
if err != nil {
return fmt.Errorf("couldn't read logs from logfile %s: %s", logfile, err)
}
if strings.Contains(string(logs), "Uploading SSH public key") {
return fmt.Errorf("SSH key was uploaded, but shouldn't have been")
}
if strings.Contains(string(logs), "Bad exit status") {
return fmt.Errorf("SSM session did not terminate gracefully and exited with a non-zero exit code")
}
return nil
},
}
acctest.TestPlugin(t, testCase)
}
func TestAccBuilder_EbsSSMRebootProvisioner(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: fmt.Sprintf("packer-ssm-reboot-acc-test %d", time.Now().Unix()),
}
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_sessionmanager_interface_test_with_reboot",
Template: fmt.Sprintf(testBuilderAccSSMWithReboot, ami.Name),
Teardown: func() error {
return ami.CleanUpAmi()
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
logs, err := os.ReadFile(logfile)
if err != nil {
return fmt.Errorf("couldn't read logs from logfile %s: %s", logfile, err)
}
if strings.Contains(string(logs), "Uploading SSH public key") {
return fmt.Errorf("SSH key was uploaded, but shouldn't have been")
}
return nil
},
}
acctest.TestPlugin(t, testCase)
}
func TestAccBuilder_EbsEnableDeprecation(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: fmt.Sprintf("packer-deprecation-acc-test %d", time.Now().Unix()),
}
deprecationTime := time.Now().UTC().AddDate(0, 0, 1)
deprecationTimeStr := deprecationTime.Format(time.RFC3339)
testCase := &acctest.PluginTestCase{
Name: "amazon-ebs_enable_deprecation_test",
Template: buildEnableDeprecationConfig(deprecationTimeStr, ami.Name),
Teardown: func() error {
return ami.CleanUpAmi()
},
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
}
return checkDeprecationEnabled(ami, deprecationTime)
},
}
acctest.TestPlugin(t, testCase)
}
func checkDeprecationEnabled(ami amazon_acc.AMIHelper, deprecationTime time.Time) error {
images, err := ami.GetAmi()
if err != nil || len(images) == 0 {
return fmt.Errorf("Failed to find ami %s at region %s", ami.Name, ami.Region)
}
ec2conn, err := testEC2Conn(ami.Region)
if err != nil {
return fmt.Errorf("Failed to connect to AWS on region %q: %s", ami.Region, err)
}
imageResp, err := ec2conn.DescribeImages(&ec2.DescribeImagesInput{
ImageIds: []*string{images[0].ImageId},
})
if err != nil {
return fmt.Errorf("Error Describe Image for AMI (%s): %s", ami.Name, err)
}
expectTime := deprecationTime.Round(time.Minute)
expectTimeStr := expectTime.Format(time.RFC3339)
image := imageResp.Images[0]
if image.DeprecationTime == nil {
return fmt.Errorf("Failed to Enable Deprecation for AMI (%s), expected Deprecation Time (%s), got empty", ami.Name, expectTimeStr)
}
actualTimeStr := aws.StringValue(image.DeprecationTime)
actualTime, _ := time.Parse(time.RFC3339, actualTimeStr)
if !actualTime.Equal(expectTime) {
return fmt.Errorf("Wrong Deprecation Time, expected (%s), got (%s)", expectTimeStr, actualTimeStr)
}
return nil
}
//go:embed test-fixtures/interpolated_run_tags.pkr.hcl
var testHCLInterpolatedRunTagsSource string
func TestAccBuilder_EbsRunTags(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-west-2",
Name: fmt.Sprintf("packer-amazon-run-tags-test %d", time.Now().Unix()),
}
testcase := &acctest.PluginTestCase{
Name: "amazon-ebs_hcl2_run_tags_test",
Teardown: func() error {
return ami.CleanUpAmi()
},
Template: fmt.Sprintf(testHCLInterpolatedRunTagsSource, ami.Name),
Check: func(buildcommand *exec.Cmd, logfile string) error {
if buildcommand.ProcessState != nil {
if buildcommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("bad exit code. logfile: %s", logfile)
}
}
return nil
},
}
acctest.TestPlugin(t, testcase)
}
//go:embed test-fixtures/interpolated_run_tags.json
var testJSONInterpolatedRunTagsSource string
func TestAccBuilder_EbsRunTagsJSON(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-west-2",
Name: fmt.Sprintf("packer-amazon-run-tags-test %d", time.Now().Unix()),
}
testcase := &acctest.PluginTestCase{
Name: "amazon-ebs_json_run_tags_test",
Teardown: func() error {
return ami.CleanUpAmi()
},
Template: testJSONInterpolatedRunTagsSource,
Check: func(buildcommand *exec.Cmd, logfile string) error {
if buildcommand.ProcessState != nil {
if buildcommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("bad exit code. logfile: %s", logfile)
}
}
return nil
},
}
acctest.TestPlugin(t, testcase)
}
//go:embed test-fixtures/ssh-keys/rsa_ssh_keypair.pkr.hcl
var testSSHKeyPairRSA string
func TestAccBuilder_EbsKeyPair_rsa(t *testing.T) {
testcase := &acctest.PluginTestCase{
Name: "amazon-ebs_rsa",
Template: testSSHKeyPairRSA,
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
logs, err := os.Open(logfile)
if err != nil {
return fmt.Errorf("Unable find %s", logfile)
}
defer logs.Close()
logsBytes, err := ioutil.ReadAll(logs)
if err != nil {
return fmt.Errorf("Unable to read %s", logfile)
}
logsString := string(logsBytes)
expectedKeyType := "rsa"
re := regexp.MustCompile(fmt.Sprintf(`(?:amazon-ebs.basic-example:\s+)+(ssh-%s)`, expectedKeyType))
matched := re.FindStringSubmatch(logsString)
if len(matched) != 2 {
return fmt.Errorf("unable to capture key information from %q", logfile)
}
return nil
},
}
acctest.TestPlugin(t, testcase)
}
//go:embed test-fixtures/ssh-keys/ed25519_ssh_keypair.pkr.hcl
var testSSHKeyPairED25519 string
func TestAccBuilder_EbsKeyPair_ed25519(t *testing.T) {
testcase := &acctest.PluginTestCase{
Name: "amazon-ebs_ed25519",
Template: testSSHKeyPairED25519,
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
logs, err := os.Open(logfile)
if err != nil {
return fmt.Errorf("Unable find %s", logfile)
}
defer logs.Close()
logsBytes, err := ioutil.ReadAll(logs)
if err != nil {
return fmt.Errorf("Unable to read %s", logfile)
}
logsString := string(logsBytes)
expectedKeyType := "ed25519"
re := regexp.MustCompile(fmt.Sprintf(`(?:amazon-ebs.basic-example:\s+)+(ssh-%s)`, expectedKeyType))
matched := re.FindStringSubmatch(logsString)
if len(matched) != 2 {
return fmt.Errorf("unable to capture key information from %q", logfile)
}
return nil
},
}
acctest.TestPlugin(t, testcase)
}
//go:embed test-fixtures/ssh-keys/rsa_sha2_only_server.pkr.hcl
var testRSASHA2OnlyServer string
func TestAccBuilder_EbsKeyPair_rsaSHA2OnlyServer(t *testing.T) {
testcase := &acctest.PluginTestCase{
Name: "amazon-ebs_rsa_sha2_srv_test",
Template: testRSASHA2OnlyServer,
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
logs, err := os.Open(logfile)
if err != nil {
return fmt.Errorf("Unable find %s", logfile)
}
defer logs.Close()
logsBytes, err := ioutil.ReadAll(logs)
if err != nil {
return fmt.Errorf("Unable to read %s", logfile)
}
logsString := string(logsBytes)
re := regexp.MustCompile(`amazon-ebs.basic-example:\s+Successful login`)
matched := re.FindString(logsString)
if matched == "" {
return fmt.Errorf("unable to success string from %q", logfile)
}
return nil
},
}
acctest.TestPlugin(t, testcase)
}
func TestAccBuilder_PrivateKeyFile(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: fmt.Sprintf("packer-pkey-file-acc-test-%d", time.Now().Unix()),
}
sshFile, err := amazon_acc.GenerateSSHPrivateKeyFile()
if err != nil {
t.Fatalf("failed to generate SSH key file: %s", err)
}
defer os.Remove(sshFile)
testcase := &acctest.PluginTestCase{
Name: "amazon-ebs_test_private_key_file",
Template: buildPrivateKeyFileConfig(ami.Name, sshFile),
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
return nil
},
}
acctest.TestPlugin(t, testcase)
}
func TestAccBuilder_PrivateKeyFileWithReboot(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: fmt.Sprintf("packer-pkey-file-reboot-acc-test-%d", time.Now().Unix()),
}
sshFile, err := amazon_acc.GenerateSSHPrivateKeyFile()
if err != nil {
t.Fatalf("failed to generate SSH key file: %s", err)
}
defer os.Remove(sshFile)
testcase := &acctest.PluginTestCase{
Name: "amazon-ebs_test_private_key_file_reboot",
Template: buildPrivateKeyFileRebootConfig(ami.Name, sshFile),
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
logs, err := os.ReadFile(logfile)
if err != nil {
return fmt.Errorf("couldn't read logs from logfile %s: %s", logfile, err)
}
if !strings.Contains(string(logs), "Uploading SSH public key") {
return fmt.Errorf("SSH key was not uploaded, but should have been")
}
return nil
},
}
acctest.TestPlugin(t, testcase)
}
//go:embed test-fixtures/unlimited-credits/burstable_instances.pkr.hcl
var testBurstableInstanceTypes string
func TestAccBuilder_EnableUnlimitedCredits(t *testing.T) {
testcase := &acctest.PluginTestCase{
Name: "amazon-ebs_unlimited_credits_test",
Template: testBurstableInstanceTypes,
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
return nil
},
}
acctest.TestPlugin(t, testcase)
}
//go:embed test-fixtures/unlimited-credits/burstable_spot_instances.pkr.hcl
var testBurstableSpotInstanceTypes string
func TestAccBuilder_EnableUnlimitedCredits_withSpotInstances(t *testing.T) {
testcase := &acctest.PluginTestCase{
Name: "amazon-ebs_unlimited_credits_spot_instance_test",
Template: testBurstableSpotInstanceTypes,
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
return nil
},
}
acctest.TestPlugin(t, testcase)
}
func testEC2Conn(region string) (*ec2.EC2, error) {
access := &common.AccessConfig{RawRegion: region}
session, err := access.Session()
if err != nil {
return nil, err
}
return ec2.New(session), nil
}
func TestAccBuilder_EbsBasicWithIMDSv2(t *testing.T) {
ami := amazon_acc.AMIHelper{
Region: "us-east-1",
Name: fmt.Sprintf("packer-ebs-imds-acc-test-%d", time.Now().Unix()),
}
testcase := &acctest.PluginTestCase{
Name: "amazon-ebs-with-imdsv2",
Template: fmt.Sprintf(testIMDSv2Support, ami.Name),
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState.ExitCode() != 0 {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
amis, err := ami.GetAmi()
if err != nil {
return fmt.Errorf("failed to get AMI: %s", err)
}
if len(amis) != 1 {
return fmt.Errorf("got too many AMIs, expected 1, got %d", len(amis))
}
ami := amis[0]
imds := ami.ImdsSupport
if imds == nil {
return fmt.Errorf("expected AMI's IMDSSupport to be set, but is null")
}
if *imds != "v2.0" {
return fmt.Errorf("expected AMI's IMDSSupport to be v2.0, got %q", *imds)
}
return nil
},
}
acctest.TestPlugin(t, testcase)
}
func TestAccBuilder_EbsCopyRegionKeepTagsInAllAMI(t *testing.T) {
tests := []struct {
name string
amiName string
template string
}{
{
name: "amazon-ebs_region_copy_keep_tags",
amiName: fmt.Sprintf(
"packer-test-builder-region-copy-keep-tags-%d",
time.Now().Unix()),
template: testAMIRunTagsCopyKeepTags,
},
{
name: "amazon-ebs_region_copy_keep_run_tags",
amiName: fmt.Sprintf(
"packer-test-builder-region-copy-keep-run-tags-%d",
time.Now().Unix()),
template: testAMIRunTagsCopyKeepRunTags,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
amis := []amazon_acc.AMIHelper{
{
Region: "us-east-1",
Name: tt.amiName,
},
{
Region: "us-west-1",
Name: tt.amiName,
},