forked from hashicorp/terraform-provider-aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathacctest.go
2851 lines (2324 loc) · 89 KB
/
acctest.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package acctest
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"os"
"os/exec"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/YakDriver/regexache"
accounttypes "github.com/aws/aws-sdk-go-v2/service/account/types"
"github.com/aws/aws-sdk-go-v2/service/acmpca"
acmpcatypes "github.com/aws/aws-sdk-go-v2/service/acmpca/types"
"github.com/aws/aws-sdk-go-v2/service/cloudsearch"
"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
"github.com/aws/aws-sdk-go-v2/service/costexplorer"
"github.com/aws/aws-sdk-go-v2/service/directoryservice"
dstypes "github.com/aws/aws-sdk-go-v2/service/directoryservice/types"
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/aws/aws-sdk-go-v2/service/iam"
iamtypes "github.com/aws/aws-sdk-go-v2/service/iam/types"
"github.com/aws/aws-sdk-go-v2/service/inspector2"
inspector2types "github.com/aws/aws-sdk-go-v2/service/inspector2/types"
organizationstypes "github.com/aws/aws-sdk-go-v2/service/organizations/types"
"github.com/aws/aws-sdk-go-v2/service/outposts"
"github.com/aws/aws-sdk-go-v2/service/pinpoint"
"github.com/aws/aws-sdk-go-v2/service/ssoadmin"
ssoadmintypes "github.com/aws/aws-sdk-go-v2/service/ssoadmin/types"
"github.com/aws/aws-sdk-go-v2/service/wafv2"
wafv2types "github.com/aws/aws-sdk-go-v2/service/wafv2/types"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/endpoints"
tfawserr_sdkv1 "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr"
tfawserr_sdkv2 "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr"
"github.com/hashicorp/terraform-plugin-go/tfprotov5"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/id"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure"
terraformsdk "github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"github.com/hashicorp/terraform-provider-aws/internal/acctest/jsoncmp"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/envvar"
"github.com/hashicorp/terraform-provider-aws/internal/errs"
"github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag"
tfsync "github.com/hashicorp/terraform-provider-aws/internal/experimental/sync"
"github.com/hashicorp/terraform-provider-aws/internal/provider"
tfaccount "github.com/hashicorp/terraform-provider-aws/internal/service/account"
tfacmpca "github.com/hashicorp/terraform-provider-aws/internal/service/acmpca"
tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2"
tfiam "github.com/hashicorp/terraform-provider-aws/internal/service/iam"
tforganizations "github.com/hashicorp/terraform-provider-aws/internal/service/organizations"
tfsts "github.com/hashicorp/terraform-provider-aws/internal/service/sts"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/names"
"github.com/jmespath/go-jmespath"
"github.com/mitchellh/mapstructure"
)
const (
// Provider name for single configuration testing
ProviderName = "aws"
// Provider name for alternate configuration testing
ProviderNameAlternate = "awsalternate"
// Provider name for alternate account and alternate region configuration testing
ProviderNameAlternateAccountAlternateRegion = "awsalternateaccountalternateregion"
// Provider name for alternate account and same region configuration testing
ProviderNameAlternateAccountSameRegion = "awsalternateaccountsameregion"
// Provider name for same account and alternate region configuration testing
ProviderNameSameAccountAlternateRegion = "awssameaccountalternateregion"
// Provider name for third configuration testing
ProviderNameThird = "awsthird"
ResourcePrefix = "tf-acc-test"
CertificateIssueTimeout = 5 * time.Minute
)
const RFC3339RegexPattern = `^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?([Zz]|([+-]([01][0-9]|2[0-3]):[0-5][0-9]))$`
const regionRegexp = `[a-z]{2}(-[a-z]+)+-\d`
const accountIDRegexp = `(aws|aws-managed|\d{12})`
// Skip implements a wrapper for (*testing.T).Skip() to prevent unused linting reports
//
// Reference: https://github.com/dominikh/go-tools/issues/633#issuecomment-606560616
func Skip(t *testing.T, message string) {
t.Helper()
t.Skip(message)
}
// ProtoV5ProviderFactories is a static map containing only the main provider instance
//
// Use other ProviderFactories functions, such as FactoriesAlternate,
// for tests requiring special provider configurations.
var (
ProtoV5ProviderFactories map[string]func() (tfprotov5.ProviderServer, error) = protoV5ProviderFactoriesInit(context.Background(), ProviderName)
)
// Provider is the "main" provider instance
//
// This Provider can be used in testing code for API calls without requiring
// the use of saving and referencing specific ProviderFactories instances.
//
// PreCheck(t) must be called before using this provider instance.
var (
Provider *schema.Provider = errs.Must(provider.New(context.Background()))
)
type ProviderFunc func() *schema.Provider
// testAccProviderConfigure ensures Provider is only configured once
//
// The PreCheck(t) function is invoked for every test and this prevents
// extraneous reconfiguration to the same values each time. However, this does
// not prevent reconfiguration that may happen should the address of
// Provider be errantly reused in ProviderFactories.
var testAccProviderConfigure sync.Once
func protoV5ProviderFactoriesInit(ctx context.Context, providerNames ...string) map[string]func() (tfprotov5.ProviderServer, error) {
factories := make(map[string]func() (tfprotov5.ProviderServer, error), len(providerNames))
for _, name := range providerNames {
factories[name] = func() (tfprotov5.ProviderServer, error) {
providerServerFactory, _, err := provider.ProtoV5ProviderServerFactory(ctx)
if err != nil {
return nil, err
}
return providerServerFactory(), nil
}
}
return factories
}
func protoV5ProviderFactoriesNamedInit(ctx context.Context, t *testing.T, providers map[string]*schema.Provider, providerNames ...string) map[string]func() (tfprotov5.ProviderServer, error) {
t.Helper()
factories := make(map[string]func() (tfprotov5.ProviderServer, error), len(providerNames))
for _, name := range providerNames {
providerServerFactory, p, err := provider.ProtoV5ProviderServerFactory(ctx)
if err != nil {
t.Fatal(err)
}
factories[name] = func() (tfprotov5.ProviderServer, error) { //nolint:unparam
return providerServerFactory(), nil
}
providers[name] = p
}
return factories
}
func protoV5ProviderFactoriesPlusProvidersInit(ctx context.Context, t *testing.T, providers *[]*schema.Provider, providerNames ...string) map[string]func() (tfprotov5.ProviderServer, error) {
t.Helper()
factories := make(map[string]func() (tfprotov5.ProviderServer, error), len(providerNames))
for _, name := range providerNames {
providerServerFactory, p, err := provider.ProtoV5ProviderServerFactory(ctx)
if err != nil {
t.Fatal(err)
}
factories[name] = func() (tfprotov5.ProviderServer, error) { //nolint:unparam
return providerServerFactory(), nil
}
if providers != nil {
*providers = append(*providers, p)
}
}
return factories
}
// ProtoV5FactoriesPlusProvidersAlternate creates ProtoV5ProviderFactories for cross-account and cross-region configurations
// and also returns Providers suitable for use with AWS APIs.
//
// For cross-region testing: Typically paired with PreCheckMultipleRegion and ConfigAlternateRegionProvider.
//
// For cross-account testing: Typically paired with PreCheckAlternateAccount and ConfigAlternateAccountProvider.
func ProtoV5FactoriesPlusProvidersAlternate(ctx context.Context, t *testing.T, providers *[]*schema.Provider) map[string]func() (tfprotov5.ProviderServer, error) {
t.Helper()
return protoV5ProviderFactoriesPlusProvidersInit(ctx, t, providers, ProviderName, ProviderNameAlternate)
}
func ProtoV5FactoriesNamedAlternate(ctx context.Context, t *testing.T, providers map[string]*schema.Provider) map[string]func() (tfprotov5.ProviderServer, error) {
t.Helper()
return ProtoV5FactoriesNamed(ctx, t, providers, ProviderName, ProviderNameAlternate)
}
func ProtoV5FactoriesNamed(ctx context.Context, t *testing.T, providers map[string]*schema.Provider, providerNames ...string) map[string]func() (tfprotov5.ProviderServer, error) {
t.Helper()
return protoV5ProviderFactoriesNamedInit(ctx, t, providers, providerNames...)
}
func ProtoV5FactoriesAlternate(ctx context.Context, t *testing.T) map[string]func() (tfprotov5.ProviderServer, error) {
t.Helper()
return protoV5ProviderFactoriesInit(ctx, ProviderName, ProviderNameAlternate)
}
// ProtoV5FactoriesAlternateAccountAndAlternateRegion creates ProtoV5ProviderFactories for cross-account and cross-region configurations
//
// Usage typically paired with PreCheckMultipleRegion, PreCheckAlternateAccount,
// and ConfigAlternateAccountAndAlternateRegionProvider.
func ProtoV5FactoriesAlternateAccountAndAlternateRegion(ctx context.Context, t *testing.T) map[string]func() (tfprotov5.ProviderServer, error) {
t.Helper()
return protoV5ProviderFactoriesInit(
ctx,
ProviderName,
ProviderNameAlternateAccountAlternateRegion,
ProviderNameAlternateAccountSameRegion,
ProviderNameSameAccountAlternateRegion,
)
}
// ProtoV5FactoriesMultipleRegions creates ProtoV5ProviderFactories for the specified number of region configurations
//
// Usage typically paired with PreCheckMultipleRegion and ConfigMultipleRegionProvider.
func ProtoV5FactoriesMultipleRegions(ctx context.Context, t *testing.T, n int) map[string]func() (tfprotov5.ProviderServer, error) {
t.Helper()
switch n {
case 2:
return protoV5ProviderFactoriesInit(ctx, ProviderName, ProviderNameAlternate)
case 3:
return protoV5ProviderFactoriesInit(ctx, ProviderName, ProviderNameAlternate, ProviderNameThird)
default:
t.Fatalf("invalid number of Region configurations: %d", n)
}
return nil
}
// PreCheck verifies and sets required provider testing configuration
//
// This PreCheck function should be present in every acceptance test. It allows
// test configurations to omit a provider configuration with region and ensures
// testing functions that attempt to call AWS APIs are previously configured.
//
// These verifications and configuration are preferred at this level to prevent
// provider developers from experiencing less clear errors for every test.
func PreCheck(ctx context.Context, t *testing.T) {
t.Helper()
// Since we are outside the scope of the Terraform configuration we must
// call Configure() to properly initialize the provider configuration.
testAccProviderConfigure.Do(func() {
envvar.FailIfAllEmpty(t, []string{envvar.Profile, envvar.AccessKeyId, envvar.ContainerCredentialsFullURI}, "credentials for running acceptance testing")
if os.Getenv(envvar.AccessKeyId) != "" {
envvar.FailIfEmpty(t, envvar.SecretAccessKey, "static credentials value when using "+envvar.AccessKeyId)
}
// Setting the AWS_DEFAULT_REGION environment variable here allows all tests to omit
// a provider configuration with a region. This defaults to us-west-2 for provider
// developer simplicity and has been in the codebase for a very long time.
//
// This handling must be preserved until either:
// * AWS_DEFAULT_REGION is required and checked above (should mention us-west-2 default)
// * Region is automatically handled via shared AWS configuration file and still verified
region := Region()
os.Setenv(envvar.DefaultRegion, region)
diags := Provider.Configure(ctx, terraformsdk.NewResourceConfigRaw(nil))
if err := sdkdiag.DiagnosticsError(diags); err != nil {
t.Fatalf("configuring provider: %s", err)
}
})
}
// ProviderAccountID returns the account ID of an AWS provider
func ProviderAccountID(provider *schema.Provider) string {
if provider == nil {
log.Print("[DEBUG] Unable to read account ID from test provider: empty provider")
return ""
}
if provider.Meta() == nil {
log.Print("[DEBUG] Unable to read account ID from test provider: unconfigured provider")
return ""
}
client, ok := provider.Meta().(*conns.AWSClient)
if !ok {
log.Print("[DEBUG] Unable to read account ID from test provider: non-AWS or unconfigured AWS provider")
return ""
}
return client.AccountID
}
// CheckDestroyNoop is a TestCheckFunc to be used as a TestCase's CheckDestroy when no such check can be made.
func CheckDestroyNoop(*terraform.State) error {
return nil
}
// CheckSleep returns a TestCheckFunc that pauses the current goroutine for at least the duration d.
func CheckSleep(t *testing.T, d time.Duration) resource.TestCheckFunc {
t.Helper()
return func(*terraform.State) error {
time.Sleep(d)
return nil
}
}
// CheckResourceAttrAccountID ensures the Terraform state exactly matches the account ID
func CheckResourceAttrAccountID(resourceName, attributeName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
return resource.TestCheckResourceAttr(resourceName, attributeName, AccountID())(s)
}
}
// CheckResourceAttrRegionalARN ensures the Terraform state exactly matches a formatted ARN with region
func CheckResourceAttrRegionalARN(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc {
return func(s *terraform.State) error {
attributeValue := arn.ARN{
AccountID: AccountID(),
Partition: Partition(),
Region: Region(),
Resource: arnResource,
Service: arnService,
}.String()
return resource.TestCheckResourceAttr(resourceName, attributeName, attributeValue)(s)
}
}
// CheckResourceAttrRegionalARNNoAccount ensures the Terraform state exactly matches a formatted ARN with region but without account ID
func CheckResourceAttrRegionalARNNoAccount(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc {
return func(s *terraform.State) error {
attributeValue := arn.ARN{
Partition: Partition(),
Region: Region(),
Resource: arnResource,
Service: arnService,
}.String()
return resource.TestCheckResourceAttr(resourceName, attributeName, attributeValue)(s)
}
}
// CheckResourceAttrRegionalARNAccountID ensures the Terraform state exactly matches a formatted ARN with region and specific account ID
func CheckResourceAttrRegionalARNAccountID(resourceName, attributeName, arnService, accountID, arnResource string) resource.TestCheckFunc {
return func(s *terraform.State) error {
attributeValue := arn.ARN{
AccountID: accountID,
Partition: Partition(),
Region: Region(),
Resource: arnResource,
Service: arnService,
}.String()
return resource.TestCheckResourceAttr(resourceName, attributeName, attributeValue)(s)
}
}
// CheckResourceAttrRegionalHostnameService ensures the Terraform state exactly matches a service DNS hostname with region and partition DNS suffix
//
// For example: ec2.us-west-2.amazonaws.com
func CheckResourceAttrRegionalHostnameService(resourceName, attributeName, serviceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
hostname := fmt.Sprintf("%s.%s.%s", serviceName, Region(), PartitionDNSSuffix())
return resource.TestCheckResourceAttr(resourceName, attributeName, hostname)(s)
}
}
// CheckResourceAttrNameFromPrefix verifies that the state attribute value matches name generated from given prefix
func CheckResourceAttrNameFromPrefix(resourceName string, attributeName string, prefix string) resource.TestCheckFunc {
return CheckResourceAttrNameWithSuffixFromPrefix(resourceName, attributeName, prefix, "")
}
// Regexp for "<start-of-string>terraform-<26 lowercase hex digits><additional suffix><end-of-string>".
func resourceUniqueIDPrefixPlusAdditionalSuffixRegexp(prefix, suffix string) *regexp.Regexp {
return regexache.MustCompile(fmt.Sprintf("^%s[[:xdigit:]]{%d}%s$", prefix, id.UniqueIDSuffixLength, suffix))
}
// CheckResourceAttrNameWithSuffixFromPrefix verifies that the state attribute value matches name with suffix generated from given prefix
func CheckResourceAttrNameWithSuffixFromPrefix(resourceName string, attributeName string, prefix string, suffix string) resource.TestCheckFunc {
return func(s *terraform.State) error {
attributeMatch := resourceUniqueIDPrefixPlusAdditionalSuffixRegexp(prefix, suffix)
return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s)
}
}
// CheckResourceAttrNameGenerated verifies that the state attribute value matches name automatically generated without prefix
func CheckResourceAttrNameGenerated(resourceName string, attributeName string) resource.TestCheckFunc {
return CheckResourceAttrNameWithSuffixGenerated(resourceName, attributeName, "")
}
// CheckResourceAttrNameGeneratedWithPrefix verifies that the state attribute value matches name automatically generated with prefix
func CheckResourceAttrNameGeneratedWithPrefix(resourceName string, attributeName string, prefix string) resource.TestCheckFunc {
return func(s *terraform.State) error {
return resource.TestMatchResourceAttr(resourceName, attributeName, resourceUniqueIDPrefixPlusAdditionalSuffixRegexp(prefix, ""))(s)
}
}
// CheckResourceAttrNameWithSuffixGenerated verifies that the state attribute value matches name with suffix automatically generated without prefix
func CheckResourceAttrNameWithSuffixGenerated(resourceName string, attributeName string, suffix string) resource.TestCheckFunc {
return func(s *terraform.State) error {
return resource.TestMatchResourceAttr(resourceName, attributeName, resourceUniqueIDPrefixPlusAdditionalSuffixRegexp(id.UniqueIdPrefix, suffix))(s)
}
}
// MatchResourceAttrAccountID ensures the Terraform state regexp matches an account ID
func MatchResourceAttrAccountID(resourceName, attributeName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
return resource.TestMatchResourceAttr(resourceName, attributeName, regexache.MustCompile(`^\d{12}$`))(s)
}
}
// MatchResourceAttrRegionalARN ensures the Terraform state regexp matches a formatted ARN with region
func MatchResourceAttrRegionalARN(resourceName, attributeName, arnService string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc {
return func(s *terraform.State) error {
arnRegexp := arn.ARN{
AccountID: AccountID(),
Partition: Partition(),
Region: Region(),
Resource: arnResourceRegexp.String(),
Service: arnService,
}.String()
attributeMatch, err := regexp.Compile(arnRegexp)
if err != nil {
return fmt.Errorf("unable to compile ARN regexp (%s): %w", arnRegexp, err)
}
return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s)
}
}
// MatchResourceAttrRegionalARNRegion ensures the Terraform state regexp matches a formatted ARN with the specified region
func MatchResourceAttrRegionalARNRegion(resourceName, attributeName, arnService, region string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc {
return func(s *terraform.State) error {
arnRegexp := arn.ARN{
AccountID: AccountID(),
Partition: Partition(),
Region: region,
Resource: arnResourceRegexp.String(),
Service: arnService,
}.String()
attributeMatch, err := regexp.Compile(arnRegexp)
if err != nil {
return fmt.Errorf("unable to compile ARN regexp (%s): %w", arnRegexp, err)
}
return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s)
}
}
// MatchResourceAttrRegionalARNNoAccount ensures the Terraform state regexp matches a formatted ARN with region but without account ID
func MatchResourceAttrRegionalARNNoAccount(resourceName, attributeName, arnService string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc {
return func(s *terraform.State) error {
arnRegexp := arn.ARN{
Partition: Partition(),
Region: Region(),
Resource: arnResourceRegexp.String(),
Service: arnService,
}.String()
attributeMatch, err := regexp.Compile(arnRegexp)
if err != nil {
return fmt.Errorf("unable to compile ARN regexp (%s): %s", arnRegexp, err)
}
return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s)
}
}
// MatchResourceAttrRegionalARNAccountID ensures the Terraform state regexp matches a formatted ARN with region and specific account ID
func MatchResourceAttrRegionalARNAccountID(resourceName, attributeName, arnService, accountID string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc {
return func(s *terraform.State) error {
arnRegexp := arn.ARN{
AccountID: accountID,
Partition: Partition(),
Region: Region(),
Resource: arnResourceRegexp.String(),
Service: arnService,
}.String()
attributeMatch, err := regexp.Compile(arnRegexp)
if err != nil {
return fmt.Errorf("unable to compile ARN regexp (%s): %w", arnRegexp, err)
}
return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s)
}
}
// MatchResourceAttrRegionalHostname ensures the Terraform state regexp matches a formatted DNS hostname with region and partition DNS suffix
func MatchResourceAttrRegionalHostname(resourceName, attributeName, serviceName string, hostnamePrefixRegexp *regexp.Regexp) resource.TestCheckFunc {
return func(s *terraform.State) error {
hostnameRegexpPattern := fmt.Sprintf("%s\\.%s\\.%s\\.%s$", hostnamePrefixRegexp.String(), serviceName, Region(), PartitionDNSSuffix())
hostnameRegexp, err := regexp.Compile(hostnameRegexpPattern)
if err != nil {
return fmt.Errorf("unable to compile hostname regexp (%s): %w", hostnameRegexp, err)
}
return resource.TestMatchResourceAttr(resourceName, attributeName, hostnameRegexp)(s)
}
}
// MatchResourceAttrGlobalHostname ensures the Terraform state regexp matches a formatted DNS hostname with partition DNS suffix and without region
func MatchResourceAttrGlobalHostname(resourceName, attributeName, serviceName string, hostnamePrefixRegexp *regexp.Regexp) resource.TestCheckFunc {
return func(s *terraform.State) error {
hostnameRegexpPattern := fmt.Sprintf("%s\\.%s\\.%s$", hostnamePrefixRegexp.String(), serviceName, PartitionDNSSuffix())
hostnameRegexp, err := regexp.Compile(hostnameRegexpPattern)
if err != nil {
return fmt.Errorf("unable to compile hostname regexp (%s): %w", hostnameRegexp, err)
}
return resource.TestMatchResourceAttr(resourceName, attributeName, hostnameRegexp)(s)
}
}
// CheckResourceAttrGlobalARN ensures the Terraform state exactly matches a formatted ARN without region
func CheckResourceAttrGlobalARN(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc {
return func(s *terraform.State) error {
attributeValue := arn.ARN{
AccountID: AccountID(),
Partition: Partition(),
Resource: arnResource,
Service: arnService,
}.String()
return resource.TestCheckResourceAttr(resourceName, attributeName, attributeValue)(s)
}
}
// CheckResourceAttrGlobalARNNoAccount ensures the Terraform state exactly matches a formatted ARN without region or account ID
func CheckResourceAttrGlobalARNNoAccount(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc {
return func(s *terraform.State) error {
attributeValue := arn.ARN{
Partition: Partition(),
Resource: arnResource,
Service: arnService,
}.String()
return resource.TestCheckResourceAttr(resourceName, attributeName, attributeValue)(s)
}
}
// CheckResourceAttrGlobalARNAccountID ensures the Terraform state exactly matches a formatted ARN without region and with specific account ID
func CheckResourceAttrGlobalARNAccountID(resourceName, attributeName, accountID, arnService, arnResource string) resource.TestCheckFunc {
return func(s *terraform.State) error {
attributeValue := arn.ARN{
AccountID: accountID,
Partition: Partition(),
Resource: arnResource,
Service: arnService,
}.String()
return resource.TestCheckResourceAttr(resourceName, attributeName, attributeValue)(s)
}
}
// MatchResourceAttrGlobalARN ensures the Terraform state regexp matches a formatted ARN without region
func MatchResourceAttrGlobalARN(resourceName, attributeName, arnService string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc {
return func(s *terraform.State) error {
arnRegexp := arn.ARN{
AccountID: AccountID(),
Partition: Partition(),
Resource: arnResourceRegexp.String(),
Service: arnService,
}.String()
attributeMatch, err := regexp.Compile(arnRegexp)
if err != nil {
return fmt.Errorf("unable to compile ARN regexp (%s): %w", arnRegexp, err)
}
return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s)
}
}
// CheckResourceAttrRegionalARNIgnoreRegionAndAccount ensures the Terraform state exactly matches a formatted ARN with region without specifying the region or account
func CheckResourceAttrRegionalARNIgnoreRegionAndAccount(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc {
return func(s *terraform.State) error {
arnRegexp := arn.ARN{
AccountID: accountIDRegexp,
Partition: Partition(),
Region: regionRegexp,
Resource: arnResource,
Service: arnService,
}.String()
attributeMatch, err := regexp.Compile(arnRegexp)
if err != nil {
return fmt.Errorf("unable to compile ARN regexp (%s): %w", arnRegexp, err)
}
return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s)
}
}
// MatchResourceAttrGlobalARNNoAccount ensures the Terraform state regexp matches a formatted ARN without region or account ID
func MatchResourceAttrGlobalARNNoAccount(resourceName, attributeName, arnService string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc {
return func(s *terraform.State) error {
arnRegexp := arn.ARN{
Partition: Partition(),
Resource: arnResourceRegexp.String(),
Service: arnService,
}.String()
attributeMatch, err := regexp.Compile(arnRegexp)
if err != nil {
return fmt.Errorf("unable to compile ARN regexp (%s): %s", arnRegexp, err)
}
return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s)
}
}
// CheckResourceAttrRFC3339 ensures the Terraform state matches a RFC3339 value
// This TestCheckFunc will likely be moved to the Terraform Plugin SDK in the future.
func CheckResourceAttrRFC3339(resourceName, attributeName string) resource.TestCheckFunc {
return resource.TestMatchResourceAttr(resourceName, attributeName, regexache.MustCompile(RFC3339RegexPattern))
}
// CheckResourceAttrEquivalentJSON is a TestCheckFunc that compares a JSON value with an expected value.
// Both JSON values are normalized before being compared.
func CheckResourceAttrEquivalentJSON(n, key, expectedJSON string) resource.TestCheckFunc {
return resource.TestCheckResourceAttrWith(n, key, func(value string) error {
vNormal, err := structure.NormalizeJsonString(value)
if err != nil {
return fmt.Errorf("%s: Error normalizing JSON in %q: %w", n, key, err)
}
expectedNormal, err := structure.NormalizeJsonString(expectedJSON)
if err != nil {
return fmt.Errorf("normalizing expected JSON: %w", err)
}
if vNormal != expectedNormal {
return fmt.Errorf("%s: Attribute %q expected\n%s\ngot\n%s", n, key, expectedJSON, value)
}
return nil
})
}
func CheckResourceAttrJSONNoDiff(n, key, expectedJSON string) resource.TestCheckFunc {
return resource.TestCheckResourceAttrWith(n, key, func(value string) error {
if diff := jsoncmp.Diff(expectedJSON, value); diff != "" {
return fmt.Errorf("unexpected diff (+wanted, -got): %s", diff)
}
return nil
})
}
func CheckResourceAttrJMES(name, key, jmesPath, value string) resource.TestCheckFunc {
return func(s *terraform.State) error {
is, err := PrimaryInstanceState(s, name)
if err != nil {
return err
}
attr, ok := is.Attributes[key]
if !ok {
return fmt.Errorf("%s: Attribute %q not set", name, key)
}
var jsonData any
err = json.Unmarshal([]byte(attr), &jsonData)
if err != nil {
return fmt.Errorf("%s: Expected attribute %q to be JSON: %w", name, key, err)
}
result, err := jmespath.Search(jmesPath, jsonData)
if err != nil {
return fmt.Errorf("invalid JMESPath %q: %w", jmesPath, err)
}
var v string
switch x := result.(type) {
case string:
v = x
case float64:
v = strconv.FormatFloat(x, 'f', -1, 64)
case bool:
v = fmt.Sprint(x)
default:
return fmt.Errorf(`%[1]s: Attribute %[2]q, JMESPath %[3]q got "%#[4]v" (%[4]T)`, name, key, jmesPath, result)
}
if v != value {
return fmt.Errorf("%s: Attribute %q, JMESPath %q expected %#v, got %#v", name, key, jmesPath, value, v)
}
return nil
}
}
func CheckResourceAttrJMESPair(nameFirst, keyFirst, jmesPath, nameSecond, keySecond string) resource.TestCheckFunc {
return func(s *terraform.State) error {
first, err := PrimaryInstanceState(s, nameFirst)
if err != nil {
return err
}
second, err := PrimaryInstanceState(s, nameSecond)
if err != nil {
return err
}
vFirst, okFirst := first.Attributes[keyFirst]
if !okFirst {
return fmt.Errorf("%s: Attribute %q not set", nameFirst, keyFirst)
}
var jsonData any
err = json.Unmarshal([]byte(vFirst), &jsonData)
if err != nil {
return fmt.Errorf("%s: Expected attribute %q to be JSON: %w", nameFirst, keyFirst, err)
}
result, err := jmespath.Search(jmesPath, jsonData)
if err != nil {
return fmt.Errorf("invalid JMESPath %q: %w", jmesPath, err)
}
var value string
switch x := result.(type) {
case string:
value = x
case float64:
value = strconv.FormatFloat(x, 'f', -1, 64)
case bool:
value = fmt.Sprint(x)
default:
return fmt.Errorf(`%[1]s: Attribute %[2]q, JMESPath %[3]q got "%#[4]v" (%[4]T)`, nameFirst, keyFirst, jmesPath, result)
}
vSecond, okSecond := second.Attributes[keySecond]
if !okSecond {
return fmt.Errorf("%s: Attribute %q, JMESPath %q is %q, but %q is not set in %s", nameFirst, keyFirst, jmesPath, value, keySecond, nameSecond)
}
if value != vSecond {
return fmt.Errorf("%s: Attribute %q, JMESPath %q, expected %q, got %q", nameFirst, keyFirst, jmesPath, vSecond, value)
}
return nil
}
}
func CheckResourceAttrJMESNotExists(name, key, jmesPath string) resource.TestCheckFunc {
return func(s *terraform.State) error {
is, err := PrimaryInstanceState(s, name)
if err != nil {
return err
}
attr, ok := is.Attributes[key]
if !ok {
return fmt.Errorf("%s: Attribute %q not set", name, key)
}
var jsonData any
err = json.Unmarshal([]byte(attr), &jsonData)
if err != nil {
return fmt.Errorf("%s: Expected attribute %q to be JSON: %w", name, key, err)
}
result, err := jmespath.Search(jmesPath, jsonData)
if err != nil {
return fmt.Errorf("invalid JMESPath %q: %w", jmesPath, err)
}
var v string
switch x := result.(type) {
case nil:
return nil
case string:
v = x
case float64:
v = strconv.FormatFloat(x, 'f', -1, 64)
case bool:
v = fmt.Sprint(x)
default:
return fmt.Errorf(`%[1]s: Attribute %[2]q, JMESPath %[3]q got "%#[4]v" (%[4]T), expected no attribute`, name, key, jmesPath, result)
}
return fmt.Errorf("%s: Attribute %q, JMESPath %q expected no attribute, got %#v", name, key, jmesPath, v)
}
}
// CheckResourceAttrContains ensures the Terraform state value contains the specified substr.
func CheckResourceAttrContains(name, key, substr string) resource.TestCheckFunc {
return resource.TestCheckResourceAttrWith(name, key, func(value string) error {
if strings.Contains(value, substr) {
return nil
}
return fmt.Errorf("%s: Attribute '%s' expected contains %#v, got %#v", name, key, substr, value)
})
}
// CheckResourceAttrHasPrefix ensures the Terraform state value has the specified prefix.
func CheckResourceAttrHasPrefix(name, key, prefix string) resource.TestCheckFunc {
return resource.TestCheckResourceAttrWith(name, key, func(value string) error {
if strings.HasPrefix(value, prefix) {
return nil
}
return fmt.Errorf("%s: Attribute '%s' expected prefix %#v, got %#v", name, key, prefix, value)
})
}
// CheckResourceAttrHasSuffix ensures the Terraform state value has the specified suffix.
func CheckResourceAttrHasSuffix(name, key, suffix string) resource.TestCheckFunc {
return resource.TestCheckResourceAttrWith(name, key, func(value string) error {
if strings.HasSuffix(value, suffix) {
return nil
}
return fmt.Errorf("%s: Attribute '%s' expected suffix %#v, got %#v", name, key, suffix, value)
})
}
// Copied and inlined from the SDK testing code
func PrimaryInstanceState(s *terraform.State, name string) (*terraform.InstanceState, error) {
rs, ok := s.RootModule().Resources[name]
if !ok {
return nil, fmt.Errorf("not found: %s", name)
}
is := rs.Primary
if is == nil {
return nil, fmt.Errorf("no primary instance: %s", name)
}
return is, nil
}
// AccountID returns the account ID of Provider
// Must be used within a resource.TestCheckFunc
func AccountID() string {
return ProviderAccountID(Provider)
}
func Region() string {
return envvar.GetWithDefault(envvar.DefaultRegion, names.USWest2RegionID)
}
func AlternateRegion() string {
return envvar.GetWithDefault(envvar.AlternateRegion, names.USEast1RegionID)
}
func ThirdRegion() string {
return envvar.GetWithDefault(envvar.ThirdRegion, names.USEast2RegionID)
}
func Partition() string {
return names.PartitionForRegion(Region())
}
func PartitionRegions() []string {
return RegionsInPartition(Partition())
}
func PartitionDNSSuffix() string {
return names.DNSSuffixForPartition(Partition())
}
func PartitionReverseDNSPrefix() string {
return names.ReverseDNS(PartitionDNSSuffix())
}
func alternateRegionPartition() string {
return names.PartitionForRegion(AlternateRegion())
}
func thirdRegionPartition() string {
return names.PartitionForRegion(ThirdRegion())
}
func PreCheckAlternateAccount(t *testing.T) {
t.Helper()
envvar.SkipIfAllEmpty(t, []string{envvar.AlternateProfile, envvar.AlternateAccessKeyId}, "credentials for running acceptance testing in alternate AWS account")
if os.Getenv(envvar.AlternateAccessKeyId) != "" {
envvar.SkipIfEmpty(t, envvar.AlternateSecretAccessKey, "static credentials value when using "+envvar.AlternateAccessKeyId)
}
}
func PreCheckThirdAccount(t *testing.T) {
t.Helper()
envvar.SkipIfAllEmpty(t, []string{envvar.ThirdProfile, envvar.ThirdAccessKeyId}, "credentials for running acceptance testing in third AWS account")
if os.Getenv(envvar.ThirdAccessKeyId) != "" {
envvar.SkipIfEmpty(t, envvar.ThirdSecretAccessKey, "static credentials value when using "+envvar.ThirdAccessKeyId)
}
}
func PreCheckPartitionHasService(t *testing.T, serviceID string) {
t.Helper()
if partition, ok := endpoints.PartitionForRegion(endpoints.DefaultPartitions(), Region()); ok {
if _, ok := partition.Services()[serviceID]; !ok {
t.Skipf("skipping tests; partition %s does not support %s service", partition.ID(), serviceID)
}
}
}
func PreCheckMultipleRegion(t *testing.T, regions int) {
t.Helper()
if len(PartitionRegions()) <= 1 {
t.Skipf("Skipping multiple region test as 1 or fewer regions detected in partion (%s)", Partition())
}
if Region() == AlternateRegion() {
t.Fatalf("%s and %s must be set to different values for acceptance tests", envvar.DefaultRegion, envvar.AlternateRegion)
}
if Partition() != alternateRegionPartition() {
t.Fatalf("%s partition (%s) does not match %s partition (%s)", envvar.AlternateRegion, alternateRegionPartition(), envvar.DefaultRegion, Partition())
}
if regions >= 3 {
if thirdRegionPartition() == names.USGovCloudPartitionID || Partition() == names.USGovCloudPartitionID {
t.Skipf("wanted %d regions, partition (%s) only has 2 regions", regions, Partition())
}
if Region() == ThirdRegion() {
t.Fatalf("%s and %s must be set to different values for acceptance tests", envvar.DefaultRegion, envvar.ThirdRegion)
}
if AlternateRegion() == ThirdRegion() {
t.Fatalf("%s and %s must be set to different values for acceptance tests", envvar.AlternateRegion, envvar.ThirdRegion)
}
if Partition() != thirdRegionPartition() {
t.Fatalf("%s partition (%s) does not match %s partition (%s)", envvar.ThirdRegion, thirdRegionPartition(), envvar.DefaultRegion, Partition())
}
}
if partition, ok := endpoints.PartitionForRegion(endpoints.DefaultPartitions(), Region()); ok {
if len(partition.Regions()) < regions {
t.Skipf("skipping tests; partition includes %d regions, %d expected", len(partition.Regions()), regions)
}
}
}
// PreCheckRegion checks that the test region is one of the specified AWS Regions.
func PreCheckRegion(t *testing.T, regions ...string) {
t.Helper()
curr := Region()
var regionOK bool
for _, region := range regions {
if curr == region {
regionOK = true
break
}
}
if !regionOK {