From 40ebe91a74431200fb55eb0b82d0dc9a99ba8493 Mon Sep 17 00:00:00 2001 From: markos kandylis Date: Sun, 20 Aug 2023 20:29:08 +0100 Subject: [PATCH 01/14] veriiedacces ressource --- .github/labeler-pr-triage.yml | 2 +- internal/service/ec2/errors.go | 1 + internal/service/ec2/service_package_gen.go | 8 + .../ec2/verifiedaccess_trust_provider.go | 421 ++++++++++++++++++ .../ec2/verifiedaccess_trust_provider_test.go | 319 +++++++++++++ names/names_data.csv | 4 +- ...erifiedaccess_trust_provider.html.markdown | 59 +++ 7 files changed, 811 insertions(+), 3 deletions(-) create mode 100644 internal/service/ec2/verifiedaccess_trust_provider.go create mode 100644 internal/service/ec2/verifiedaccess_trust_provider_test.go create mode 100644 website/docs/r/verifiedaccess_trust_provider.html.markdown diff --git a/.github/labeler-pr-triage.yml b/.github/labeler-pr-triage.yml index dc41f16b9d2..a8ea9662c5b 100644 --- a/.github/labeler-pr-triage.yml +++ b/.github/labeler-pr-triage.yml @@ -1045,7 +1045,7 @@ service/translate: - 'website/**/translate_*' service/verifiedaccess: - 'internal/service/ec2/**/verifiedaccess_*' - - 'website/**/verifiedaccess*' + - 'website/**/verifiedaccess_*' service/verifiedpermissions: - 'internal/service/verifiedpermissions/**/*' - 'website/**/verifiedpermissions_*' diff --git a/internal/service/ec2/errors.go b/internal/service/ec2/errors.go index 7e41bd29988..57ea8eaf512 100644 --- a/internal/service/ec2/errors.go +++ b/internal/service/ec2/errors.go @@ -92,6 +92,7 @@ const ( errCodeInvalidSubnetIdNotFound = "InvalidSubnetId.NotFound" errCodeInvalidTrafficMirrorFilterIdNotFound = "InvalidTrafficMirrorFilterId.NotFound" errCodeInvalidTrafficMirrorFilterRuleIdNotFound = "InvalidTrafficMirrorFilterRuleId.NotFound" + errCodeInvalidVerifiedAccessTrustProviderIdNotFound = "InvalidVerifiedAccessTrustProviderId.NotFound" errCodeInvalidTrafficMirrorSessionIdNotFound = "InvalidTrafficMirrorSessionId.NotFound" errCodeInvalidTrafficMirrorTargetIdNotFound = "InvalidTrafficMirrorTargetId.NotFound" errCodeInvalidTransitGatewayAttachmentIDNotFound = "InvalidTransitGatewayAttachmentID.NotFound" diff --git a/internal/service/ec2/service_package_gen.go b/internal/service/ec2/service_package_gen.go index 24b531bd700..a6f980b66c3 100644 --- a/internal/service/ec2/service_package_gen.go +++ b/internal/service/ec2/service_package_gen.go @@ -943,6 +943,14 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka IdentifierAttribute: "id", }, }, + { + Factory: ResourceVerifiedaccessTrustProvider, + TypeName: "aws_verifiedaccess_trust_provider", + Name: "Verified Access Trust Provider", + Tags: &types.ServicePackageResourceTags{ + IdentifierAttribute: "id", + }, + }, { Factory: ResourceVolumeAttachment, TypeName: "aws_volume_attachment", diff --git a/internal/service/ec2/verifiedaccess_trust_provider.go b/internal/service/ec2/verifiedaccess_trust_provider.go new file mode 100644 index 00000000000..84d578ca20a --- /dev/null +++ b/internal/service/ec2/verifiedaccess_trust_provider.go @@ -0,0 +1,421 @@ +package ec2 + +import ( + "context" + "errors" + "log" + "regexp" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2/types" + + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/create" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" + "github.com/hashicorp/terraform-provider-aws/names" +) + +// @SDKResource("aws_verifiedaccess_trust_provider", name="Verified Access Trust Provider") +// @Tags(identifierAttribute="id") +func ResourceVerifiedaccessTrustProvider() *schema.Resource { + return &schema.Resource{ + CreateWithoutTimeout: resourceVerifiedaccessTrustProviderCreate, + ReadWithoutTimeout: resourceVerifiedaccessTrustProviderRead, + UpdateWithoutTimeout: resourceVerifiedaccessTrustProviderUpdate, + DeleteWithoutTimeout: resourceVerifiedaccessTrustProviderDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Update: schema.DefaultTimeout(30 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "description": { + Type: schema.TypeString, + Optional: true, + }, + "device_options": { + Type: schema.TypeList, + ForceNew: true, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "tenant_id": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "device_trust_provider_type": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + // ValidateFunc: validation.StringInSlice(ec2.DeviceTrustProviderType_Values(), false), + }, + "dry_run": { + Type: schema.TypeBool, + ForceNew: true, + Optional: true, + }, + "oidc_options": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "authorization_endpoint": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + ValidateFunc: validation.IsURLWithHTTPS, + }, + "client_id": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + }, + "client_secret": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + }, + "issuer": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + ValidateFunc: validation.IsURLWithHTTPS, + }, + "scope": { + Type: schema.TypeString, + Optional: true, + }, + "token_endpoint": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + ValidateFunc: validation.IsURLWithHTTPS, + }, + "user_info_endpoint": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + ValidateFunc: validation.IsURLWithHTTPS, + }, + }, + }, + }, + "policy_reference_name": { + Type: schema.TypeString, + ForceNew: true, + Required: true, + ValidateFunc: validation.StringMatch(regexp.MustCompile(`[a-zA-Z_][a-zA-Z0-9_]*`), ""), + }, + names.AttrTags: tftags.TagsSchema(), + names.AttrTagsAll: tftags.TagsSchemaComputed(), + "trust_provider_type": { + Type: schema.TypeString, + ForceNew: true, + Required: true, + // ValidateFunc: validation.StringInSlice(ec2.TrustProviderType(), false), + }, + "user_trust_provider_type": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + // ValidateFunc: validation.StringInSlice(types.TrustProviderType(), false), + }, + }, + + CustomizeDiff: verify.SetTagsDiff, + } +} + +const ( + ResNameVerifiedAccessTrustProvider = "Verified Access Trust Provider" +) + +func resourceVerifiedaccessTrustProviderCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + var diags diag.Diagnostics + + conn := meta.(*conns.AWSClient).EC2Client(ctx) + + in := &ec2.CreateVerifiedAccessTrustProviderInput{ + PolicyReferenceName: aws.String(d.Get("policy_reference_name").(string)), + TrustProviderType: types.TrustProviderType(d.Get("trust_provider_type").(string)), + } + + if v, ok := d.GetOk("dry_run"); ok { + in.DryRun = aws.Bool(v.(bool)) + } + + if v, ok := d.GetOk("description"); ok { + in.Description = aws.String(v.(string)) + } + + if v, ok := d.GetOk("device_options"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + in.DeviceOptions = expandCreateVerifiedAccessTrustProviderDeviceOptions(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("device_trust_provider_type"); ok { + in.DeviceTrustProviderType = types.DeviceTrustProviderType(v.(string)) + } + + if v, ok := d.GetOk("user_trust_provider_type"); ok { + in.UserTrustProviderType = types.UserTrustProviderType(v.(string)) + } + + out, err := conn.CreateVerifiedAccessTrustProvider(ctx, in) + if err != nil { + return append(diags, create.DiagError(names.EC2, create.ErrActionCreating, ResNameVerifiedAccessTrustProvider, d.Get("name").(string), err)...) + } + + if out == nil { + return append(diags, create.DiagError(names.EC2, create.ErrActionCreating, ResNameVerifiedAccessTrustProvider, d.Get("name").(string), errors.New("empty output"))...) + } + + d.SetId(aws.ToString(out.VerifiedAccessTrustProvider.VerifiedAccessTrustProviderId)) + + return append(diags, resourceVerifiedaccessTrustProviderRead(ctx, d, meta)...) +} + +func resourceVerifiedaccessTrustProviderRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + var diags diag.Diagnostics + + conn := meta.(*conns.AWSClient).EC2Client(ctx) + + out, err := findVerifiedaccessTrustProviderByID(ctx, conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] EC2 VerifiedaccessTrustProvider (%s) not found, removing from state", d.Id()) + d.SetId("") + return diags + } + + if err != nil { + return append(diags, create.DiagError(names.EC2, create.ErrActionReading, ResNameVerifiedAccessTrustProvider, d.Id(), err)...) + } + + d.Set("description", out.Description) + + if v := out.DeviceOptions; v != nil { + if err := d.Set("device_options", flattenDeviceOptions(v)); err != nil { + return create.DiagError(names.EC2, create.ErrActionSetting, ResNameVerifiedAccessTrustProvider, d.Id(), err) + } + } + + d.Set("device_trust_provider_type", out.DeviceTrustProviderType) + + if v := out.OidcOptions; v != nil { + if err := d.Set("oidc_options", flattenOIDCOptions(v)); err != nil { + return create.DiagError(names.EC2, create.ErrActionSetting, ResNameVerifiedAccessTrustProvider, d.Id(), err) + } + } + + d.Set("policy_reference_name", out.PolicyReferenceName) + d.Set("trust_provider_type", out.TrustProviderType) + d.Set("user_trust_provider_type", out.UserTrustProviderType) + + return diags +} + +func resourceVerifiedaccessTrustProviderUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + var diags diag.Diagnostics + + conn := meta.(*conns.AWSClient).EC2Client(ctx) + + update := false + + in := &ec2.ModifyVerifiedAccessTrustProviderInput{ + VerifiedAccessTrustProviderId: aws.String(d.Id()), + } + + if d.HasChanges("description") { + if v, ok := d.GetOk("description"); ok { + in.Description = aws.String(v.(string)) + update = true + } + } + + if d.HasChanges("oidc_options") { + if v, ok := d.GetOk("oidc_options"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + in.OidcOptions = expandModifyVerifiedAccessTrustProviderOIDCOptions(v.([]interface{})[0].(map[string]interface{})) + update = true + } + } + + if !update { + return diags + } + + log.Printf("[DEBUG] Updating EC2 VerifiedaccessTrustProvider (%s): %#v", d.Id(), in) + _, err := conn.ModifyVerifiedAccessTrustProvider(ctx, in) + if err != nil { + return append(diags, create.DiagError(names.EC2, create.ErrActionUpdating, ResNameVerifiedAccessTrustProvider, d.Id(), err)...) + } + + return append(diags, resourceVerifiedaccessTrustProviderRead(ctx, d, meta)...) +} + +func resourceVerifiedaccessTrustProviderDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + var diags diag.Diagnostics + + conn := meta.(*conns.AWSClient).EC2Client(ctx) + + log.Printf("[INFO] Deleting EC2 VerifiedaccessTrustProvider %s", d.Id()) + + _, err := conn.DeleteVerifiedAccessTrustProvider(ctx, &ec2.DeleteVerifiedAccessTrustProviderInput{ + VerifiedAccessTrustProviderId: aws.String(d.Id()), + DryRun: aws.Bool(d.Get("dry_run").(bool)), + }) + + if err != nil { + return append(diags, create.DiagError(names.EC2, create.ErrActionDeleting, ResNameVerifiedAccessTrustProvider, d.Id(), err)...) + } + + return diags +} + +func findVerifiedaccessTrustProviderByID(ctx context.Context, conn *ec2.Client, id string) (*types.VerifiedAccessTrustProvider, error) { + in := &ec2.DescribeVerifiedAccessTrustProvidersInput{ + VerifiedAccessTrustProviderIds: []string{id}, + } + out, err := conn.DescribeVerifiedAccessTrustProviders(ctx, in) + if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessTrustProviderIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: in, + } + } + + if err != nil { + return nil, err + } + + if out == nil || out.VerifiedAccessTrustProviders == nil { + return nil, tfresource.NewEmptyResultError(in) + } + + return &out.VerifiedAccessTrustProviders[0], nil +} + +func flattenDeviceOptions(apiObject *types.DeviceOptions) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.TenantId; v != nil { + tfMap["tenant_id"] = aws.ToString(v) + } + + return tfMap +} + +func flattenOIDCOptions(apiObject *types.OidcOptions) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.AuthorizationEndpoint; v != nil { + tfMap["authorization_endpoint"] = aws.ToString(v) + } + if v := apiObject.ClientId; v != nil { + tfMap["client_id"] = aws.ToString(v) + } + if v := apiObject.ClientSecret; v != nil { + tfMap["client_secret"] = aws.ToString(v) + } + if v := apiObject.Issuer; v != nil { + tfMap["issuer"] = aws.ToString(v) + } + if v := apiObject.Scope; v != nil { + tfMap["scope"] = aws.ToString(v) + } + if v := apiObject.TokenEndpoint; v != nil { + tfMap["token_endpoint"] = aws.ToString(v) + } + if v := apiObject.UserInfoEndpoint; v != nil { + tfMap["user_info_endpoint"] = aws.ToString(v) + } + + return tfMap +} + +func expandCreateVerifiedAccessTrustProviderDeviceOptions(tfMap map[string]interface{}) *types.CreateVerifiedAccessTrustProviderDeviceOptions { + if tfMap == nil { + return nil + } + + apiObject := &types.CreateVerifiedAccessTrustProviderDeviceOptions{} + + if v, ok := tfMap["tenant_id"].(string); ok && v != "" { + apiObject.TenantId = aws.String(v) + } + + return apiObject +} + +func expandCreateVerifiedAccessTrustProviderOIDCOptions(tfMap map[string]interface{}) *types.CreateVerifiedAccessTrustProviderOidcOptions { + if tfMap == nil { + return nil + } + + apiObject := &types.CreateVerifiedAccessTrustProviderOidcOptions{} + + if v, ok := tfMap["authorization_endpoint"].(string); ok && v != "" { + apiObject.AuthorizationEndpoint = aws.String(v) + } + if v, ok := tfMap["client_id"].(string); ok && v != "" { + apiObject.ClientId = aws.String(v) + } + if v, ok := tfMap["client_secret"].(string); ok && v != "" { + apiObject.ClientSecret = aws.String(v) + } + if v, ok := tfMap["issuer"].(string); ok && v != "" { + apiObject.Issuer = aws.String(v) + } + if v, ok := tfMap["scope"].(string); ok && v != "" { + apiObject.Scope = aws.String(v) + } + if v, ok := tfMap["token_endpoint"].(string); ok && v != "" { + apiObject.TokenEndpoint = aws.String(v) + } + if v, ok := tfMap["user_info_endpoint"].(string); ok && v != "" { + apiObject.UserInfoEndpoint = aws.String(v) + } + + return apiObject +} + +func expandModifyVerifiedAccessTrustProviderOIDCOptions(tfMap map[string]interface{}) *types.ModifyVerifiedAccessTrustProviderOidcOptions { + if tfMap == nil { + return nil + } + + apiObject := &types.ModifyVerifiedAccessTrustProviderOidcOptions{} + + if v, ok := tfMap["scope"].(string); ok && v != "" { + apiObject.Scope = aws.String(v) + } + + return apiObject +} diff --git a/internal/service/ec2/verifiedaccess_trust_provider_test.go b/internal/service/ec2/verifiedaccess_trust_provider_test.go new file mode 100644 index 00000000000..ddb5217d5b7 --- /dev/null +++ b/internal/service/ec2/verifiedaccess_trust_provider_test.go @@ -0,0 +1,319 @@ +package ec2_test +// **PLEASE DELETE THIS AND ALL TIP COMMENTS BEFORE SUBMITTING A PR FOR REVIEW!** +// +// TIP: ==== INTRODUCTION ==== +// Thank you for trying the skaff tool! +// +// You have opted to include these helpful comments. They all include "TIP:" +// to help you find and remove them when you're done with them. +// +// While some aspects of this file are customized to your input, the +// scaffold tool does *not* look at the AWS API and ensure it has correct +// function, structure, and variable names. It makes guesses based on +// commonalities. You will need to make significant adjustments. +// +// In other words, as generated, this is a rough outline of the work you will +// need to do. If something doesn't make sense for your situation, get rid of +// it. + +import ( + // TIP: ==== IMPORTS ==== + // This is a common set of imports but not customized to your code since + // your code hasn't been written yet. Make sure you, your IDE, or + // goimports -w fixes these imports. + // + // The provider linter wants your imports to be in two groups: first, + // standard library (i.e., "fmt" or "strings"), second, everything else. + // + // Also, AWS Go SDK v2 may handle nested structures differently than v1, + // using the services/ec2/types package. If so, you'll + // need to import types and reference the nested types, e.g., as + // types.. + "context" + "fmt" + "regexp" + "strings" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2/types" + 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" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/errs" + "github.com/hashicorp/terraform-provider-aws/names" + + // TIP: You will often need to import the package that this test file lives + // in. Since it is in the "test" context, it must import the package to use + // any normal context constants, variables, or functions. + tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" +) + +// TIP: File Structure. The basic outline for all test files should be as +// follows. Improve this resource's maintainability by following this +// outline. +// +// 1. Package declaration (add "_test" since this is a test file) +// 2. Imports +// 3. Unit tests +// 4. Basic test +// 5. Disappears test +// 6. All the other tests +// 7. Helper functions (exists, destroy, check, etc.) +// 8. Functions that return Terraform configurations + +// TIP: ==== UNIT TESTS ==== +// This is an example of a unit test. Its name is not prefixed with +// "TestAcc" like an acceptance test. +// +// Unlike acceptance tests, unit tests do not access AWS and are focused on a +// function (or method). Because of this, they are quick and cheap to run. +// +// In designing a resource's implementation, isolate complex bits from AWS bits +// so that they can be tested through a unit test. We encourage more unit tests +// in the provider. +// +// Cut and dry functions using well-used patterns, like typical flatteners and +// expanders, don't need unit testing. However, if they are complex or +// intricate, they should be unit tested. +func TestVerifiedaccessTrustProviderExampleUnitTest(t *testing.T) { + testCases := []struct { + TestName string + Input string + Expected string + Error bool + }{ + { + TestName: "empty", + Input: "", + Expected: "", + Error: true, + }, + { + TestName: "descriptive name", + Input: "some input", + Expected: "some output", + Error: false, + }, + { + TestName: "another descriptive name", + Input: "more input", + Expected: "more output", + Error: false, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.TestName, func(t *testing.T) { + got, err := tfec2.FunctionFromResource(testCase.Input) + + if err != nil && !testCase.Error { + t.Errorf("got error (%s), expected no error", err) + } + + if err == nil && testCase.Error { + t.Errorf("got (%s) and no error, expected error", got) + } + + if got != testCase.Expected { + t.Errorf("got %s, expected %s", got, testCase.Expected) + } + }) + } +} + +// TIP: ==== ACCEPTANCE TESTS ==== +// This is an example of a basic acceptance test. This should test as much of +// standard functionality of the resource as possible, and test importing, if +// applicable. We prefix its name with "TestAcc", the service, and the +// resource name. +// +// Acceptance test access AWS and cost money to run. +func TestAccEC2VerifiedaccessTrustProvider_basic(t *testing.T) { + ctx := acctest.Context(t) + // TIP: This is a long-running test guard for tests that run longer than + // 300s (5 min) generally. + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var verifiedaccesstrustprovider ec2.DescribeVerifiedaccessTrustProviderResponse + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_ec2_verifiedaccess_trust_provider.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(ctx, t) + acctest.PreCheckPartitionHasService(t, names.EC2EndpointID) + testAccPreCheck(ctx, t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.EC2EndpointID), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, + CheckDestroy: testAccCheckVerifiedaccessTrustProviderDestroy(ctx), + Steps: []resource.TestStep{ + { + Config: testAccVerifiedaccessTrustProviderConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckVerifiedaccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "false"), + resource.TestCheckResourceAttrSet(resourceName, "maintenance_window_start_time.0.day_of_week"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ + "console_access": "false", + "groups.#": "0", + "username": "Test", + "password": "TestTest1234", + }), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`verifiedaccesstrustprovider:+.`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"apply_immediately", "user"}, + }, + }, + }) +} + +func TestAccEC2VerifiedaccessTrustProvider_disappears(t *testing.T) { + ctx := acctest.Context(t) + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var verifiedaccesstrustprovider ec2.DescribeVerifiedaccessTrustProviderResponse + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_ec2_verifiedaccess_trust_provider.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(ctx, t) + acctest.PreCheckPartitionHasService(t, names.EC2EndpointID) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.EC2EndpointID), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, + CheckDestroy: testAccCheckVerifiedaccessTrustProviderDestroy(ctx), + Steps: []resource.TestStep{ + { + Config: testAccVerifiedaccessTrustProviderConfig_basic(rName, testAccVerifiedaccessTrustProviderVersionNewer), + Check: resource.ComposeTestCheckFunc( + testAccCheckVerifiedaccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + acctest.CheckResourceDisappears(ctx, acctest.Provider, tfec2.ResourceVerifiedaccessTrustProvider(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckVerifiedaccessTrustProviderDestroy(ctx context.Context) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_ec2_verifiedaccess_trust_provider" { + continue + } + + input := &ec2.DescribeVerifiedaccessTrustProviderInput{ + VerifiedaccessTrustProviderId: aws.String(rs.Primary.ID), + } + _, err := conn.DescribeVerifiedaccessTrustProvider(ctx, &ec2.DescribeVerifiedaccessTrustProviderInput{ + VerifiedaccessTrustProviderId: aws.String(rs.Primary.ID), + }) + if errs.IsA[*types.ResourceNotFoundException](err){ + return nil + } + if err != nil { + return nil + } + + return create.Error(names.EC2, create.ErrActionCheckingDestroyed, tfec2.ResNameVerifiedaccessTrustProvider, rs.Primary.ID, errors.New("not destroyed")) + } + + return nil + } +} + +func testAccCheckVerifiedaccessTrustProviderExists(ctx context.Context, name string, verifiedaccesstrustprovider *ec2.DescribeVerifiedaccessTrustProviderResponse) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedaccessTrustProvider, name, errors.New("not found")) + } + + if rs.Primary.ID == "" { + return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedaccessTrustProvider, name, errors.New("not set")) + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) + resp, err := conn.DescribeVerifiedaccessTrustProvider(ctx, &ec2.DescribeVerifiedaccessTrustProviderInput{ + VerifiedaccessTrustProviderId: aws.String(rs.Primary.ID), + }) + + if err != nil { + return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedaccessTrustProvider, rs.Primary.ID, err) + } + + *verifiedaccesstrustprovider = *resp + + return nil + } +} + +func testAccPreCheck(ctx context.Context, t *testing.T) { + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) + + input := &ec2.ListVerifiedaccessTrustProvidersInput{} + _, err := conn.ListVerifiedaccessTrustProviders(ctx, input) + + if acctest.PreCheckSkipError(err) { + t.Skipf("skipping acceptance testing: %s", err) + } + if err != nil { + t.Fatalf("unexpected PreCheck error: %s", err) + } +} + +func testAccCheckVerifiedaccessTrustProviderNotRecreated(before, after *ec2.DescribeVerifiedaccessTrustProviderResponse) resource.TestCheckFunc { + return func(s *terraform.State) error { + if before, after := aws.ToString(before.VerifiedaccessTrustProviderId), aws.ToString(after.VerifiedaccessTrustProviderId); before != after { + return create.Error(names.EC2, create.ErrActionCheckingNotRecreated, tfec2.ResNameVerifiedaccessTrustProvider, aws.ToString(before.VerifiedaccessTrustProviderId), errors.New("recreated")) + } + + return nil + } +} + +func testAccVerifiedaccessTrustProviderConfig_basic(rName, version string) string { + return fmt.Sprintf(` +resource "aws_security_group" "test" { + name = %[1]q +} + +resource "aws_ec2_verifiedaccess_trust_provider" "test" { + verifiedaccess_trust_provider_name = %[1]q + engine_type = "ActiveEC2" + engine_version = %[2]q + host_instance_type = "ec2.t2.micro" + security_groups = [aws_security_group.test.id] + authentication_strategy = "simple" + storage_type = "efs" + + logs { + general = true + } + + user { + username = "Test" + password = "TestTest1234" + } +} +`, rName, version) +} diff --git a/names/names_data.csv b/names/names_data.csv index 33802c9eeab..06ec549582b 100644 --- a/names/names_data.csv +++ b/names/names_data.csv @@ -357,7 +357,7 @@ transfer,transfer,transfer,transfer,,transfer,,,Transfer,Transfer,,1,,,aws_trans ,,,,,transitgateway,ec2,,TransitGateway,,,,,aws_ec2_transit_gateway,aws_transitgateway_,transitgateway_,ec2_transit_gateway,Transit Gateway,AWS,x,,x,,,Part of EC2 translate,translate,translate,translate,,translate,,,Translate,Translate,,1,,,aws_translate_,,translate_,Translate,Amazon,,x,,,, ,,,,,,,,,,,,,,,,,Trusted Advisor,AWS,x,,,,,Part of Support -,,,,,verifiedaccess,ec2,,VerifiedAccess,,,,,aws_verifiedaccess,aws_verifiedaccess_,verifiedaccess_,verifiedaccess,Verified Access,AWS,x,,x,,,Part of EC2 +,,,,,verifiedaccess,ec2,,VerifiedAccess,,,,,aws_verifiedaccess,aws_verifiedaccess_,verifiedaccess_,verifiedaccess_,Verified Access,AWS,x,,x,,,Part of EC2 ,,,,,vpc,ec2,,VPC,,,,,aws_((default_)?(network_acl|route_table|security_group|subnet|vpc(?!_ipam))|ec2_(managed|network|subnet|traffic)|egress_only_internet|flow_log|internet_gateway|main_route_table_association|nat_gateway|network_interface|prefix_list|route\b),aws_vpc_,vpc_,default_network_;default_route_;default_security_;default_subnet;default_vpc;ec2_managed_;ec2_network_;ec2_subnet_;ec2_traffic_;egress_only_;flow_log;internet_gateway;main_route_;nat_;network_;prefix_list;route_;route\.;security_group;subnet;vpc_dhcp_;vpc_endpoint;vpc_ipv;vpc_network_performance;vpc_peering_;vpc_security_group_;vpc\.;vpcs\.,VPC (Virtual Private Cloud),Amazon,x,,x,,,Part of EC2 vpc-lattice,vpclattice,vpclattice,vpclattice,,vpclattice,,,VPCLattice,VPCLattice,,,2,,aws_vpclattice_,,vpclattice_,VPC Lattice,Amazon,,,,,, ,,,,,ipam,ec2,,IPAM,,,,,aws_vpc_ipam,aws_ipam_,ipam_,vpc_ipam,VPC IPAM (IP Address Manager),Amazon,x,,x,,,Part of EC2 @@ -378,4 +378,4 @@ workspaces,workspaces,workspaces,workspaces,,workspaces,,,WorkSpaces,WorkSpaces, workspaces-web,workspacesweb,workspacesweb,workspacesweb,,workspacesweb,,,WorkSpacesWeb,WorkSpacesWeb,,1,,,aws_workspacesweb_,,workspacesweb_,WorkSpaces Web,Amazon,,x,,,, xray,xray,xray,xray,,xray,,,XRay,XRay,,,2,,aws_xray_,,xray_,X-Ray,AWS,,,,,, verifiedpermissions,verifiedpermissions,verifiedpermissions,verifiedpermissions,,verifiedpermissions,,,VerifiedPermissions,VerifiedPermissions,,,2,,aws_verifiedpermissions_,,verifiedpermissions_,Verified Permissions,Amazon,,,,,, -codecatalyst,codecatalyst,codecatalyst,codecatalyst,,codecatalyst,,,CodeCatalyst,CodeCatalyst,,,2,,aws_codecatalyst_,,codecatalyst_,CodeCatalyst,Amazon,,,,,, +codecatalyst,codecatalyst,codecatalyst,codecatalyst,,codecatalyst,,,CodeCatalyst,CodeCatalyst,,,2,,aws_codecatalyst_,,codecatalyst_,CodeCatalyst,Amazon,,,,,, \ No newline at end of file diff --git a/website/docs/r/verifiedaccess_trust_provider.html.markdown b/website/docs/r/verifiedaccess_trust_provider.html.markdown new file mode 100644 index 00000000000..9f2b35d5d46 --- /dev/null +++ b/website/docs/r/verifiedaccess_trust_provider.html.markdown @@ -0,0 +1,59 @@ +--- +subcategory: "Verified Access" +layout: "aws" +page_title: "AWS: aws_verifiedaccess_trust_provider" +description: |- + Terraform resource for managing a Verified Access Trust Provider. +--- + +# Resource: aws_verifiedaccess_trust_provider + +Terraform resource for managing a Verified Access Trust Provider. + +## Example Usage + +```terraform +resource "aws_verifiedaccess_trust_provider" "example" { + policy_reference_name = "example" + trust_provider_type = "user" + user_trust_provider_type = "iam-identity-center" +} +``` + +## Argument Reference + +The following arguments are required: + +* `policy_reference_name` - (Required) The identifier to be used when working with policy rules. +* `trust_provider_type` - (Required) The type of trust provider can be either user or device-based. + +The following arguments are optional: + +* `description` - (Optional) A description for the AWS Verified Access trust provider. +* `device_options` - (Optional) A block of options for device identity based trust providers. +* `device_trust_provider_type` (Optional) The type of device-based trust provider. +* `oidc_options` - (Optional) The OpenID Connect details for an oidc-type, user-identity based trust provider. +* `tags` - (Optional) Key-value mapping of resource tags. If configured with a provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. +* `user_trust_provider_type` - (Optional) The type of user-based trust provider. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The ID of the AWS Verified Access trust provider. + +## Timeouts + +[Configuration options](https://developer.hashicorp.com/terraform/language/resources/syntax#operation-timeouts): + +* `create` - (Default `60m`) +* `update` - (Default `180m`) +* `delete` - (Default `90m`) + +## Import + +Verified Access Trust Providers can be imported using the `id`, e.g., + +``` +$ terraform import aws_verifiedaccess_trust_provider.example vatp-8012925589 +``` From 22a22f6bfda43ea52cfff76e99e9a1245f830ecc Mon Sep 17 00:00:00 2001 From: markos kandylis Date: Sun, 27 Aug 2023 18:28:35 +0100 Subject: [PATCH 02/14] Fixed the disappears test --- internal/service/ec2/find.go | 24 + .../ec2/verifiedaccess_trust_provider.go | 71 +-- .../ec2/verifiedaccess_trust_provider_test.go | 442 ++++++++++-------- 3 files changed, 295 insertions(+), 242 deletions(-) diff --git a/internal/service/ec2/find.go b/internal/service/ec2/find.go index f23394955dd..53a8fac5b42 100644 --- a/internal/service/ec2/find.go +++ b/internal/service/ec2/find.go @@ -7020,3 +7020,27 @@ func FindInstanceConnectEndpointByID(ctx context.Context, conn *ec2_sdkv2.Client return output, nil } + +func FindVerifiedaccessTrustProviderByID(ctx context.Context, conn *ec2_sdkv2.Client, id string) (*ec2_sdkv2.DescribeVerifiedAccessTrustProvidersOutput, error) { + in := &ec2_sdkv2.DescribeVerifiedAccessTrustProvidersInput{ + VerifiedAccessTrustProviderIds: []string{id}, + } + out, err := conn.DescribeVerifiedAccessTrustProviders(ctx, in) + + if tfawserr_sdkv2.ErrCodeEquals(err, errCodeInvalidVerifiedAccessTrustProviderIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: in, + } + } + + if err != nil { + return nil, err + } + + if out == nil || out.VerifiedAccessTrustProviders == nil { + return nil, tfresource.NewEmptyResultError(in) + } + + return out, nil +} diff --git a/internal/service/ec2/verifiedaccess_trust_provider.go b/internal/service/ec2/verifiedaccess_trust_provider.go index 84d578ca20a..f1591397e73 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider.go +++ b/internal/service/ec2/verifiedaccess_trust_provider.go @@ -11,9 +11,7 @@ import ( "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -68,11 +66,6 @@ func ResourceVerifiedaccessTrustProvider() *schema.Resource { Optional: true, // ValidateFunc: validation.StringInSlice(ec2.DeviceTrustProviderType_Values(), false), }, - "dry_run": { - Type: schema.TypeBool, - ForceNew: true, - Optional: true, - }, "oidc_options": { Type: schema.TypeList, Optional: true, @@ -92,8 +85,8 @@ func ResourceVerifiedaccessTrustProvider() *schema.Resource { }, "client_secret": { Type: schema.TypeString, - ForceNew: true, Optional: true, + ForceNew: true, }, "issuer": { Type: schema.TypeString, @@ -160,10 +153,6 @@ func resourceVerifiedaccessTrustProviderCreate(ctx context.Context, d *schema.Re TrustProviderType: types.TrustProviderType(d.Get("trust_provider_type").(string)), } - if v, ok := d.GetOk("dry_run"); ok { - in.DryRun = aws.Bool(v.(bool)) - } - if v, ok := d.GetOk("description"); ok { in.Description = aws.String(v.(string)) } @@ -180,13 +169,17 @@ func resourceVerifiedaccessTrustProviderCreate(ctx context.Context, d *schema.Re in.UserTrustProviderType = types.UserTrustProviderType(v.(string)) } + if v, ok := d.GetOk("oidc_options"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + in.OidcOptions = expandCreateVerifiedAccessTrustProviderOIDCOptions(v.([]interface{})[0].(map[string]interface{})) + } + out, err := conn.CreateVerifiedAccessTrustProvider(ctx, in) if err != nil { - return append(diags, create.DiagError(names.EC2, create.ErrActionCreating, ResNameVerifiedAccessTrustProvider, d.Get("name").(string), err)...) + return append(diags, create.DiagError(names.EC2, create.ErrActionCreating, ResNameVerifiedAccessTrustProvider, "", err)...) } if out == nil { - return append(diags, create.DiagError(names.EC2, create.ErrActionCreating, ResNameVerifiedAccessTrustProvider, d.Get("name").(string), errors.New("empty output"))...) + return append(diags, create.DiagError(names.EC2, create.ErrActionCreating, ResNameVerifiedAccessTrustProvider, "", errors.New("empty output"))...) } d.SetId(aws.ToString(out.VerifiedAccessTrustProvider.VerifiedAccessTrustProviderId)) @@ -199,8 +192,8 @@ func resourceVerifiedaccessTrustProviderRead(ctx context.Context, d *schema.Reso conn := meta.(*conns.AWSClient).EC2Client(ctx) - out, err := findVerifiedaccessTrustProviderByID(ctx, conn, d.Id()) - + output, err := FindVerifiedaccessTrustProviderByID(ctx, conn, d.Id()) + // out := output.VerifiedAccessTrustProviders[0] if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EC2 VerifiedaccessTrustProvider (%s) not found, removing from state", d.Id()) d.SetId("") @@ -211,25 +204,25 @@ func resourceVerifiedaccessTrustProviderRead(ctx context.Context, d *schema.Reso return append(diags, create.DiagError(names.EC2, create.ErrActionReading, ResNameVerifiedAccessTrustProvider, d.Id(), err)...) } - d.Set("description", out.Description) + d.Set("description", output.VerifiedAccessTrustProviders[0].Description) - if v := out.DeviceOptions; v != nil { + if v := output.VerifiedAccessTrustProviders[0].DeviceOptions; v != nil { if err := d.Set("device_options", flattenDeviceOptions(v)); err != nil { return create.DiagError(names.EC2, create.ErrActionSetting, ResNameVerifiedAccessTrustProvider, d.Id(), err) } } - d.Set("device_trust_provider_type", out.DeviceTrustProviderType) + d.Set("device_trust_provider_type", output.VerifiedAccessTrustProviders[0].DeviceTrustProviderType) - if v := out.OidcOptions; v != nil { + if v := output.VerifiedAccessTrustProviders[0].OidcOptions; v != nil { if err := d.Set("oidc_options", flattenOIDCOptions(v)); err != nil { return create.DiagError(names.EC2, create.ErrActionSetting, ResNameVerifiedAccessTrustProvider, d.Id(), err) } } - d.Set("policy_reference_name", out.PolicyReferenceName) - d.Set("trust_provider_type", out.TrustProviderType) - d.Set("user_trust_provider_type", out.UserTrustProviderType) + d.Set("policy_reference_name", output.VerifiedAccessTrustProviders[0].PolicyReferenceName) + d.Set("trust_provider_type", output.VerifiedAccessTrustProviders[0].TrustProviderType) + d.Set("user_trust_provider_type", output.VerifiedAccessTrustProviders[0].UserTrustProviderType) return diags } @@ -281,7 +274,6 @@ func resourceVerifiedaccessTrustProviderDelete(ctx context.Context, d *schema.Re _, err := conn.DeleteVerifiedAccessTrustProvider(ctx, &ec2.DeleteVerifiedAccessTrustProviderInput{ VerifiedAccessTrustProviderId: aws.String(d.Id()), - DryRun: aws.Bool(d.Get("dry_run").(bool)), }) if err != nil { @@ -291,30 +283,7 @@ func resourceVerifiedaccessTrustProviderDelete(ctx context.Context, d *schema.Re return diags } -func findVerifiedaccessTrustProviderByID(ctx context.Context, conn *ec2.Client, id string) (*types.VerifiedAccessTrustProvider, error) { - in := &ec2.DescribeVerifiedAccessTrustProvidersInput{ - VerifiedAccessTrustProviderIds: []string{id}, - } - out, err := conn.DescribeVerifiedAccessTrustProviders(ctx, in) - if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessTrustProviderIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: in, - } - } - - if err != nil { - return nil, err - } - - if out == nil || out.VerifiedAccessTrustProviders == nil { - return nil, tfresource.NewEmptyResultError(in) - } - - return &out.VerifiedAccessTrustProviders[0], nil -} - -func flattenDeviceOptions(apiObject *types.DeviceOptions) map[string]interface{} { +func flattenDeviceOptions(apiObject *types.DeviceOptions) []interface{} { if apiObject == nil { return nil } @@ -325,10 +294,10 @@ func flattenDeviceOptions(apiObject *types.DeviceOptions) map[string]interface{} tfMap["tenant_id"] = aws.ToString(v) } - return tfMap + return []interface{}{tfMap} } -func flattenOIDCOptions(apiObject *types.OidcOptions) map[string]interface{} { +func flattenOIDCOptions(apiObject *types.OidcOptions) []interface{} { if apiObject == nil { return nil } @@ -357,7 +326,7 @@ func flattenOIDCOptions(apiObject *types.OidcOptions) map[string]interface{} { tfMap["user_info_endpoint"] = aws.ToString(v) } - return tfMap + return []interface{}{tfMap} } func expandCreateVerifiedAccessTrustProviderDeviceOptions(tfMap map[string]interface{}) *types.CreateVerifiedAccessTrustProviderDeviceOptions { diff --git a/internal/service/ec2/verifiedaccess_trust_provider_test.go b/internal/service/ec2/verifiedaccess_trust_provider_test.go index ddb5217d5b7..5f9b199ba25 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider_test.go +++ b/internal/service/ec2/verifiedaccess_trust_provider_test.go @@ -1,173 +1,96 @@ package ec2_test -// **PLEASE DELETE THIS AND ALL TIP COMMENTS BEFORE SUBMITTING A PR FOR REVIEW!** -// -// TIP: ==== INTRODUCTION ==== -// Thank you for trying the skaff tool! -// -// You have opted to include these helpful comments. They all include "TIP:" -// to help you find and remove them when you're done with them. -// -// While some aspects of this file are customized to your input, the -// scaffold tool does *not* look at the AWS API and ensure it has correct -// function, structure, and variable names. It makes guesses based on -// commonalities. You will need to make significant adjustments. -// -// In other words, as generated, this is a rough outline of the work you will -// need to do. If something doesn't make sense for your situation, get rid of -// it. import ( - // TIP: ==== IMPORTS ==== - // This is a common set of imports but not customized to your code since - // your code hasn't been written yet. Make sure you, your IDE, or - // goimports -w fixes these imports. - // - // The provider linter wants your imports to be in two groups: first, - // standard library (i.e., "fmt" or "strings"), second, everything else. - // - // Also, AWS Go SDK v2 may handle nested structures differently than v1, - // using the services/ec2/types package. If so, you'll - // need to import types and reference the nested types, e.g., as - // types.. "context" + "errors" "fmt" - "regexp" - "strings" "testing" - "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/ec2" - "github.com/aws/aws-sdk-go-v2/service/ec2/types" 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" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" - "github.com/hashicorp/terraform-provider-aws/internal/errs" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" - // TIP: You will often need to import the package that this test file lives - // in. Since it is in the "test" context, it must import the package to use - // any normal context constants, variables, or functions. tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" ) -// TIP: File Structure. The basic outline for all test files should be as -// follows. Improve this resource's maintainability by following this -// outline. -// -// 1. Package declaration (add "_test" since this is a test file) -// 2. Imports -// 3. Unit tests -// 4. Basic test -// 5. Disappears test -// 6. All the other tests -// 7. Helper functions (exists, destroy, check, etc.) -// 8. Functions that return Terraform configurations - -// TIP: ==== UNIT TESTS ==== -// This is an example of a unit test. Its name is not prefixed with -// "TestAcc" like an acceptance test. -// -// Unlike acceptance tests, unit tests do not access AWS and are focused on a -// function (or method). Because of this, they are quick and cheap to run. -// -// In designing a resource's implementation, isolate complex bits from AWS bits -// so that they can be tested through a unit test. We encourage more unit tests -// in the provider. -// -// Cut and dry functions using well-used patterns, like typical flatteners and -// expanders, don't need unit testing. However, if they are complex or -// intricate, they should be unit tested. -func TestVerifiedaccessTrustProviderExampleUnitTest(t *testing.T) { - testCases := []struct { - TestName string - Input string - Expected string - Error bool - }{ - { - TestName: "empty", - Input: "", - Expected: "", - Error: true, - }, - { - TestName: "descriptive name", - Input: "some input", - Expected: "some output", - Error: false, - }, - { - TestName: "another descriptive name", - Input: "more input", - Expected: "more output", - Error: false, - }, - } - - for _, testCase := range testCases { - t.Run(testCase.TestName, func(t *testing.T) { - got, err := tfec2.FunctionFromResource(testCase.Input) +func TestAccVerifiedAccessTrustProvider_basic(t *testing.T) { + ctx := acctest.Context(t) - if err != nil && !testCase.Error { - t.Errorf("got error (%s), expected no error", err) - } + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } - if err == nil && testCase.Error { - t.Errorf("got (%s) and no error, expected error", got) - } + var verifiedaccesstrustprovider ec2.DescribeVerifiedAccessTrustProvidersOutput + resourceName := "aws_verifiedaccess_trust_provider.test" + policyReferenceName := "test" + trustProviderType := "user" + userTrustProviderType := "iam-identity-center" + description := sdkacctest.RandString(10) - if got != testCase.Expected { - t.Errorf("got %s, expected %s", got, testCase.Expected) - } - }) - } + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(ctx, t) + acctest.PreCheckPartitionHasService(t, names.EC2) + testAccPreCheck(ctx, t) + acctest.PreCheckIAMServiceLinkedRole(ctx, t, "/aws-service-role/sso.amazonaws.com") + }, + ErrorCheck: acctest.ErrorCheck(t, names.EC2), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, + CheckDestroy: testAccCheckVerifiedAccessTrustProviderDestroy(ctx), + Steps: []resource.TestStep{ + { + Config: testAccVerifiedAccessTrustProviderConfig_basic(policyReferenceName, trustProviderType, userTrustProviderType, description), + Check: resource.ComposeTestCheckFunc( + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + resource.TestCheckResourceAttr(resourceName, "description", description), + resource.TestCheckResourceAttr(resourceName, "policy_reference_name", policyReferenceName), + resource.TestCheckResourceAttr(resourceName, "trust_provider_type", trustProviderType), + resource.TestCheckResourceAttr(resourceName, "user_trust_provider_type", userTrustProviderType), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"apply_immediately", "user"}, + }, + }, + }) } -// TIP: ==== ACCEPTANCE TESTS ==== -// This is an example of a basic acceptance test. This should test as much of -// standard functionality of the resource as possible, and test importing, if -// applicable. We prefix its name with "TestAcc", the service, and the -// resource name. -// -// Acceptance test access AWS and cost money to run. -func TestAccEC2VerifiedaccessTrustProvider_basic(t *testing.T) { +func TestAccVerifiedAccessTrustProvider_deviceOptions(t *testing.T) { ctx := acctest.Context(t) - // TIP: This is a long-running test guard for tests that run longer than - // 300s (5 min) generally. - if testing.Short() { - t.Skip("skipping long-running test in short mode") - } - - var verifiedaccesstrustprovider ec2.DescribeVerifiedaccessTrustProviderResponse - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - resourceName := "aws_ec2_verifiedaccess_trust_provider.test" + var verifiedaccesstrustprovider ec2.DescribeVerifiedAccessTrustProvidersOutput + resourceName := "aws_verifiedaccess_trust_provider.test" + policyReferenceName := "test" + trustProviderType := "device" + deviceTrustProviderType := "jamf" + tenantId := sdkacctest.RandString(10) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, names.EC2EndpointID) testAccPreCheck(ctx, t) }, - ErrorCheck: acctest.ErrorCheck(t, names.EC2EndpointID), + ErrorCheck: acctest.ErrorCheck(t, names.EC2), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckVerifiedaccessTrustProviderDestroy(ctx), + CheckDestroy: testAccCheckVerifiedAccessTrustProviderDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccVerifiedaccessTrustProviderConfig_basic(rName), + Config: testAccVerifiedAccessTrustProviderConfig_deviceOptions(policyReferenceName, trustProviderType, deviceTrustProviderType, tenantId), Check: resource.ComposeTestCheckFunc( - testAccCheckVerifiedaccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), - resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "false"), - resource.TestCheckResourceAttrSet(resourceName, "maintenance_window_start_time.0.day_of_week"), - resource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ - "console_access": "false", - "groups.#": "0", - "username": "Test", - "password": "TestTest1234", - }), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`verifiedaccesstrustprovider:+.`)), + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + resource.TestCheckResourceAttr(resourceName, "device_options.#", "1"), + resource.TestCheckResourceAttr(resourceName, "device_options.0.tenant_id", tenantId), + resource.TestCheckResourceAttr(resourceName, "device_trust_provider_type", deviceTrustProviderType), + resource.TestCheckResourceAttr(resourceName, "policy_reference_name", policyReferenceName), + resource.TestCheckResourceAttr(resourceName, "trust_provider_type", trustProviderType), ), }, { @@ -180,30 +103,34 @@ func TestAccEC2VerifiedaccessTrustProvider_basic(t *testing.T) { }) } -func TestAccEC2VerifiedaccessTrustProvider_disappears(t *testing.T) { +func TestAccVerifiedAccessTrustProvider_disappears(t *testing.T) { ctx := acctest.Context(t) if testing.Short() { t.Skip("skipping long-running test in short mode") } - var verifiedaccesstrustprovider ec2.DescribeVerifiedaccessTrustProviderResponse - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - resourceName := "aws_ec2_verifiedaccess_trust_provider.test" + var verifiedaccesstrustprovider ec2.DescribeVerifiedAccessTrustProvidersOutput + resourceName := "aws_verifiedaccess_trust_provider.test" + policyReferenceName := "test" + trustProviderType := "user" + userTrustProviderType := "iam-identity-center" + description := sdkacctest.RandString(10) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, names.EC2EndpointID) - testAccPreCheck(t) + acctest.PreCheckPartitionHasService(t, names.EC2) + acctest.PreCheckIAMServiceLinkedRole(ctx, t, "/aws-service-role/sso.amazonaws.com") + testAccPreCheck(ctx, t) }, - ErrorCheck: acctest.ErrorCheck(t, names.EC2EndpointID), + ErrorCheck: acctest.ErrorCheck(t, names.EC2), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckVerifiedaccessTrustProviderDestroy(ctx), + CheckDestroy: testAccCheckVerifiedAccessTrustProviderDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccVerifiedaccessTrustProviderConfig_basic(rName, testAccVerifiedaccessTrustProviderVersionNewer), + Config: testAccVerifiedAccessTrustProviderConfig_basic(policyReferenceName, trustProviderType, userTrustProviderType, description), Check: resource.ComposeTestCheckFunc( - testAccCheckVerifiedaccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), acctest.CheckResourceDisappears(ctx, acctest.Provider, tfec2.ResourceVerifiedaccessTrustProvider(), resourceName), ), ExpectNonEmptyPlan: true, @@ -212,53 +139,151 @@ func TestAccEC2VerifiedaccessTrustProvider_disappears(t *testing.T) { }) } -func testAccCheckVerifiedaccessTrustProviderDestroy(ctx context.Context) resource.TestCheckFunc { +func testAccCheckVerifiedAccessTrustProviderDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { - if rs.Type != "aws_ec2_verifiedaccess_trust_provider" { + if rs.Type != "aws_verifiedaccess_trust_provider" { continue } - input := &ec2.DescribeVerifiedaccessTrustProviderInput{ - VerifiedaccessTrustProviderId: aws.String(rs.Primary.ID), - } - _, err := conn.DescribeVerifiedaccessTrustProvider(ctx, &ec2.DescribeVerifiedaccessTrustProviderInput{ - VerifiedaccessTrustProviderId: aws.String(rs.Primary.ID), - }) - if errs.IsA[*types.ResourceNotFoundException](err){ - return nil + _, err := tfec2.FindVerifiedaccessTrustProviderByID(ctx, conn, rs.Primary.ID) + if tfresource.NotFound(err) { + continue } if err != nil { return nil } - return create.Error(names.EC2, create.ErrActionCheckingDestroyed, tfec2.ResNameVerifiedaccessTrustProvider, rs.Primary.ID, errors.New("not destroyed")) + return create.Error(names.EC2, create.ErrActionCheckingDestroyed, tfec2.ResNameVerifiedAccessTrustProvider, rs.Primary.ID, errors.New("not destroyed")) } return nil } } -func testAccCheckVerifiedaccessTrustProviderExists(ctx context.Context, name string, verifiedaccesstrustprovider *ec2.DescribeVerifiedaccessTrustProviderResponse) resource.TestCheckFunc { +func TestAccVerifiedAccessTrustProvider_oidcOptions(t *testing.T) { + ctx := acctest.Context(t) + var verifiedaccesstrustprovider ec2.DescribeVerifiedAccessTrustProvidersOutput + resourceName := "aws_verifiedaccess_trust_provider.test" + policyReferenceName := "test" + trustProviderType := "user" + userTrustProviderType := "oidc" + authorizationEndpoint := "https://authorization.example.com" + clientId := sdkacctest.RandString(10) + clientSecret := sdkacctest.RandString(10) + issuer := "https://issuer.example.com" + scope := sdkacctest.RandString(10) + tokenEndpoint := "https://token.example.com" + userInfoEndpoint := "https://user.example.com" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(ctx, t) + testAccPreCheck(ctx, t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.EC2), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, + CheckDestroy: testAccCheckVerifiedAccessTrustProviderDestroy(ctx), + Steps: []resource.TestStep{ + { + Config: testAccVerifiedAccessTrustProviderConfig_oidcOptions(policyReferenceName, trustProviderType, userTrustProviderType, authorizationEndpoint, clientId, clientSecret, issuer, scope, tokenEndpoint, userInfoEndpoint), + Check: resource.ComposeTestCheckFunc( + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + resource.TestCheckResourceAttr(resourceName, "oidc_options.#", "1"), + resource.TestCheckResourceAttr(resourceName, "oidc_options.0.authorization_endpoint", authorizationEndpoint), + resource.TestCheckResourceAttr(resourceName, "oidc_options.0.client_id", clientId), + resource.TestCheckResourceAttr(resourceName, "oidc_options.0.client_secret", clientSecret), + resource.TestCheckResourceAttr(resourceName, "oidc_options.0.issuer", issuer), + resource.TestCheckResourceAttr(resourceName, "oidc_options.0.scope", scope), + resource.TestCheckResourceAttr(resourceName, "oidc_options.0.token_endpoint", tokenEndpoint), + resource.TestCheckResourceAttr(resourceName, "oidc_options.0.user_info_endpoint", userInfoEndpoint), + resource.TestCheckResourceAttr(resourceName, "policy_reference_name", policyReferenceName), + resource.TestCheckResourceAttr(resourceName, "trust_provider_type", trustProviderType), + resource.TestCheckResourceAttr(resourceName, "user_trust_provider_type", userTrustProviderType), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"apply_immediately", "user"}, + }, + }, + }) +} + +func TestAccVerifiedAccessTrustProvider_tags(t *testing.T) { + ctx := acctest.Context(t) + var verifiedaccesstrustprovider ec2.DescribeVerifiedAccessTrustProvidersOutput + resourceName := "aws_verifiedaccess_trust_provider.test" + policyReferenceName := "test" + trustProviderType := "user" + userTrustProviderType := "iam-identity-center" + description := sdkacctest.RandString(10) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(ctx, t) + testAccPreCheck(ctx, t) + acctest.PreCheckIAMServiceLinkedRole(ctx, t, "/aws-service-role/sso.amazonaws.com") + }, + ErrorCheck: acctest.ErrorCheck(t, names.EC2), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, + CheckDestroy: testAccCheckVerifiedAccessTrustProviderDestroy(ctx), + Steps: []resource.TestStep{ + { + Config: testAccVerifiedAccessTrustProviderConfig_tags1(policyReferenceName, trustProviderType, userTrustProviderType, description, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + Config: testAccVerifiedAccessTrustProviderConfig_tags2(policyReferenceName, trustProviderType, userTrustProviderType, description, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccVerifiedAccessTrustProviderConfig_tags1(policyReferenceName, trustProviderType, userTrustProviderType, description, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"apply_immediately", "user"}, + }, + }, + }) +} + +func testAccCheckVerifiedAccessTrustProviderExists(ctx context.Context, name string, verifiedaccesstrustprovider *ec2.DescribeVerifiedAccessTrustProvidersOutput) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedaccessTrustProvider, name, errors.New("not found")) + return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedAccessTrustProvider, name, errors.New("not found")) } - if rs.Primary.ID == "" { - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedaccessTrustProvider, name, errors.New("not set")) + return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedAccessTrustProvider, name, errors.New("not set")) } conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - resp, err := conn.DescribeVerifiedaccessTrustProvider(ctx, &ec2.DescribeVerifiedaccessTrustProviderInput{ - VerifiedaccessTrustProviderId: aws.String(rs.Primary.ID), - }) + resp, err := tfec2.FindVerifiedaccessTrustProviderByID(ctx, conn, rs.Primary.ID) + fmt.Println(err) if err != nil { - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedaccessTrustProvider, rs.Primary.ID, err) + return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedAccessTrustProvider, rs.Primary.ID, err) } *verifiedaccesstrustprovider = *resp @@ -270,8 +295,8 @@ func testAccCheckVerifiedaccessTrustProviderExists(ctx context.Context, name str func testAccPreCheck(ctx context.Context, t *testing.T) { conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - input := &ec2.ListVerifiedaccessTrustProvidersInput{} - _, err := conn.ListVerifiedaccessTrustProviders(ctx, input) + input := &ec2.DescribeVerifiedAccessTrustProvidersInput{} + _, err := conn.DescribeVerifiedAccessTrustProviders(ctx, input) if acctest.PreCheckSkipError(err) { t.Skipf("skipping acceptance testing: %s", err) @@ -281,39 +306,74 @@ func testAccPreCheck(ctx context.Context, t *testing.T) { } } -func testAccCheckVerifiedaccessTrustProviderNotRecreated(before, after *ec2.DescribeVerifiedaccessTrustProviderResponse) resource.TestCheckFunc { - return func(s *terraform.State) error { - if before, after := aws.ToString(before.VerifiedaccessTrustProviderId), aws.ToString(after.VerifiedaccessTrustProviderId); before != after { - return create.Error(names.EC2, create.ErrActionCheckingNotRecreated, tfec2.ResNameVerifiedaccessTrustProvider, aws.ToString(before.VerifiedaccessTrustProviderId), errors.New("recreated")) - } +func testAccVerifiedAccessTrustProviderConfig_basic(policyReferenceName, trustProviderType, userTrustProviderType, description string) string { + return fmt.Sprintf(` +resource "aws_verifiedaccess_trust_provider" "test" { + description = %[4]q + policy_reference_name = %[1]q + trust_provider_type = %[2]q + user_trust_provider_type = %[3]q +} +`, policyReferenceName, trustProviderType, userTrustProviderType, description) +} - return nil - } +func testAccVerifiedAccessTrustProviderConfig_deviceOptions(policyReferenceName, trustProviderType, deviceTrustProviderType, tenantId string) string { + return fmt.Sprintf(` +resource "aws_verifiedaccess_trust_provider" "test" { + device_options { + tenant_id = %[4]q + } + device_trust_provider_type = %[3]q + policy_reference_name = %[1]q + trust_provider_type = %[2]q +} +`, policyReferenceName, trustProviderType, deviceTrustProviderType, tenantId) } -func testAccVerifiedaccessTrustProviderConfig_basic(rName, version string) string { +func testAccVerifiedAccessTrustProviderConfig_oidcOptions(policyReferenceName, trustProviderType, userTrustProviderType, authorizationEndpoint, clientId, clientSecret, issuer, scope, tokenEndpoint, userInfoEndpoint string) string { return fmt.Sprintf(` -resource "aws_security_group" "test" { - name = %[1]q +resource "aws_verifiedaccess_trust_provider" "test" { + oidc_options { + authorization_endpoint = %[4]q + client_id = %[5]q + client_secret = %[6]q + issuer = %[7]q + scope = %[8]q + token_endpoint = %[9]q + user_info_endpoint = %[10]q + } + policy_reference_name = %[1]q + trust_provider_type = %[2]q + user_trust_provider_type = %[3]q +} +`, policyReferenceName, trustProviderType, userTrustProviderType, authorizationEndpoint, clientId, clientSecret, issuer, scope, tokenEndpoint, userInfoEndpoint) } -resource "aws_ec2_verifiedaccess_trust_provider" "test" { - verifiedaccess_trust_provider_name = %[1]q - engine_type = "ActiveEC2" - engine_version = %[2]q - host_instance_type = "ec2.t2.micro" - security_groups = [aws_security_group.test.id] - authentication_strategy = "simple" - storage_type = "efs" - - logs { - general = true +func testAccVerifiedAccessTrustProviderConfig_tags1(policyReferenceName, trustProviderType, userTrustProviderType, description, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_verifiedaccess_trust_provider" "test" { + description = %[4]q + policy_reference_name = %[1]q + trust_provider_type = %[2]q + user_trust_provider_type = %[3]q + tags = { + %[5]q = %[6]q } +} +`, policyReferenceName, trustProviderType, userTrustProviderType, description, tagKey1, tagValue1) +} - user { - username = "Test" - password = "TestTest1234" +func testAccVerifiedAccessTrustProviderConfig_tags2(policyReferenceName, trustProviderType, userTrustProviderType, description, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_verifiedaccess_trust_provider" "test" { + description = %[4]q + policy_reference_name = %[1]q + trust_provider_type = %[2]q + user_trust_provider_type = %[3]q + tags = { + %[5]q = %[6]q + %[7]q = %[8]q } } -`, rName, version) +`, policyReferenceName, trustProviderType, userTrustProviderType, description, tagKey1, tagValue1, tagKey2, tagValue2) } From cb031fed44807e442e1025387f505894c4896a7b Mon Sep 17 00:00:00 2001 From: markos kandylis Date: Sun, 27 Aug 2023 19:10:50 +0100 Subject: [PATCH 03/14] Fixed the oidcOptions test --- .../ec2/verifiedaccess_trust_provider.go | 17 ++++++++--------- .../ec2/verifiedaccess_trust_provider_test.go | 4 ++-- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/internal/service/ec2/verifiedaccess_trust_provider.go b/internal/service/ec2/verifiedaccess_trust_provider.go index f1591397e73..ddeb2852ff7 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider.go +++ b/internal/service/ec2/verifiedaccess_trust_provider.go @@ -84,9 +84,9 @@ func ResourceVerifiedaccessTrustProvider() *schema.Resource { Optional: true, }, "client_secret": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + Sensitive: true, }, "issuer": { Type: schema.TypeString, @@ -215,7 +215,7 @@ func resourceVerifiedaccessTrustProviderRead(ctx context.Context, d *schema.Reso d.Set("device_trust_provider_type", output.VerifiedAccessTrustProviders[0].DeviceTrustProviderType) if v := output.VerifiedAccessTrustProviders[0].OidcOptions; v != nil { - if err := d.Set("oidc_options", flattenOIDCOptions(v)); err != nil { + if err := d.Set("oidc_options", flattenOIDCOptions(v, d.Get("oidc_options.0.client_secret").(string))); err != nil { return create.DiagError(names.EC2, create.ErrActionSetting, ResNameVerifiedAccessTrustProvider, d.Id(), err) } } @@ -297,12 +297,14 @@ func flattenDeviceOptions(apiObject *types.DeviceOptions) []interface{} { return []interface{}{tfMap} } -func flattenOIDCOptions(apiObject *types.OidcOptions) []interface{} { +func flattenOIDCOptions(apiObject *types.OidcOptions, clientSecret string) []interface{} { if apiObject == nil { return nil } - tfMap := map[string]interface{}{} + tfMap := map[string]interface{}{ + "client_secret": clientSecret, + } if v := apiObject.AuthorizationEndpoint; v != nil { tfMap["authorization_endpoint"] = aws.ToString(v) @@ -310,9 +312,6 @@ func flattenOIDCOptions(apiObject *types.OidcOptions) []interface{} { if v := apiObject.ClientId; v != nil { tfMap["client_id"] = aws.ToString(v) } - if v := apiObject.ClientSecret; v != nil { - tfMap["client_secret"] = aws.ToString(v) - } if v := apiObject.Issuer; v != nil { tfMap["issuer"] = aws.ToString(v) } diff --git a/internal/service/ec2/verifiedaccess_trust_provider_test.go b/internal/service/ec2/verifiedaccess_trust_provider_test.go index 5f9b199ba25..cf652588493 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider_test.go +++ b/internal/service/ec2/verifiedaccess_trust_provider_test.go @@ -208,7 +208,7 @@ func TestAccVerifiedAccessTrustProvider_oidcOptions(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"apply_immediately", "user"}, + ImportStateVerifyIgnore: []string{"oidc_options.0.client_secret"}, }, }, }) @@ -262,7 +262,7 @@ func TestAccVerifiedAccessTrustProvider_tags(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"apply_immediately", "user"}, + ImportStateVerifyIgnore: []string{}, }, }, }) From c1eb8d6f88232ad104d9dfd7990ba573032489ce Mon Sep 17 00:00:00 2001 From: markos kandylis Date: Sun, 27 Aug 2023 21:47:23 +0100 Subject: [PATCH 04/14] All tests are successfull --- .../ec2/verifiedaccess_trust_provider.go | 31 ++++++++++--------- .../ec2/verifiedaccess_trust_provider_test.go | 5 ++- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/internal/service/ec2/verifiedaccess_trust_provider.go b/internal/service/ec2/verifiedaccess_trust_provider.go index ddeb2852ff7..7533162fe9d 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider.go +++ b/internal/service/ec2/verifiedaccess_trust_provider.go @@ -16,6 +16,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/enum" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -61,10 +62,10 @@ func ResourceVerifiedaccessTrustProvider() *schema.Resource { }, }, "device_trust_provider_type": { - Type: schema.TypeString, - ForceNew: true, - Optional: true, - // ValidateFunc: validation.StringInSlice(ec2.DeviceTrustProviderType_Values(), false), + Type: schema.TypeString, + ForceNew: true, + Optional: true, + ValidateDiagFunc: enum.Validate[types.DeviceTrustProviderType](), }, "oidc_options": { Type: schema.TypeList, @@ -122,16 +123,16 @@ func ResourceVerifiedaccessTrustProvider() *schema.Resource { names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), "trust_provider_type": { - Type: schema.TypeString, - ForceNew: true, - Required: true, - // ValidateFunc: validation.StringInSlice(ec2.TrustProviderType(), false), + Type: schema.TypeString, + ForceNew: true, + Required: true, + ValidateDiagFunc: enum.Validate[types.TrustProviderType](), }, "user_trust_provider_type": { - Type: schema.TypeString, - ForceNew: true, - Optional: true, - // ValidateFunc: validation.StringInSlice(types.TrustProviderType(), false), + Type: schema.TypeString, + ForceNew: true, + Optional: true, + ValidateDiagFunc: enum.Validate[types.UserTrustProviderType](), }, }, @@ -151,6 +152,7 @@ func resourceVerifiedaccessTrustProviderCreate(ctx context.Context, d *schema.Re in := &ec2.CreateVerifiedAccessTrustProviderInput{ PolicyReferenceName: aws.String(d.Get("policy_reference_name").(string)), TrustProviderType: types.TrustProviderType(d.Get("trust_provider_type").(string)), + TagSpecifications: getTagSpecificationsInV2(ctx, types.ResourceTypeVerifiedAccessTrustProvider), } if v, ok := d.GetOk("description"); ok { @@ -193,7 +195,8 @@ func resourceVerifiedaccessTrustProviderRead(ctx context.Context, d *schema.Reso conn := meta.(*conns.AWSClient).EC2Client(ctx) output, err := FindVerifiedaccessTrustProviderByID(ctx, conn, d.Id()) - // out := output.VerifiedAccessTrustProviders[0] + + // ouxd := oux.DeviceOptions if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EC2 VerifiedaccessTrustProvider (%s) not found, removing from state", d.Id()) d.SetId("") @@ -223,7 +226,7 @@ func resourceVerifiedaccessTrustProviderRead(ctx context.Context, d *schema.Reso d.Set("policy_reference_name", output.VerifiedAccessTrustProviders[0].PolicyReferenceName) d.Set("trust_provider_type", output.VerifiedAccessTrustProviders[0].TrustProviderType) d.Set("user_trust_provider_type", output.VerifiedAccessTrustProviders[0].UserTrustProviderType) - + setTagsOutV2(ctx, output.VerifiedAccessTrustProviders[0].Tags) return diags } diff --git a/internal/service/ec2/verifiedaccess_trust_provider_test.go b/internal/service/ec2/verifiedaccess_trust_provider_test.go index cf652588493..12a7795c513 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider_test.go +++ b/internal/service/ec2/verifiedaccess_trust_provider_test.go @@ -58,7 +58,7 @@ func TestAccVerifiedAccessTrustProvider_basic(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"apply_immediately", "user"}, + ImportStateVerifyIgnore: []string{}, }, }, }) @@ -97,7 +97,7 @@ func TestAccVerifiedAccessTrustProvider_deviceOptions(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"apply_immediately", "user"}, + ImportStateVerifyIgnore: []string{}, }, }, }) @@ -281,7 +281,6 @@ func testAccCheckVerifiedAccessTrustProviderExists(ctx context.Context, name str conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) resp, err := tfec2.FindVerifiedaccessTrustProviderByID(ctx, conn, rs.Primary.ID) - fmt.Println(err) if err != nil { return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedAccessTrustProvider, rs.Primary.ID, err) } From fb40648de6f28b90bb567895c37656cb59d80fa0 Mon Sep 17 00:00:00 2001 From: markos kandylis Date: Sun, 27 Aug 2023 22:39:57 +0100 Subject: [PATCH 05/14] Tests passed successfully --- .../ec2/verifiedaccess_trust_provider.go | 1 - .../ec2/verifiedaccess_trust_provider_test.go | 6 +++--- .../verifiedaccess_trust_provider.html.markdown | 17 +++++++++++++---- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/internal/service/ec2/verifiedaccess_trust_provider.go b/internal/service/ec2/verifiedaccess_trust_provider.go index 7533162fe9d..48ef585f3e1 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider.go +++ b/internal/service/ec2/verifiedaccess_trust_provider.go @@ -10,7 +10,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" diff --git a/internal/service/ec2/verifiedaccess_trust_provider_test.go b/internal/service/ec2/verifiedaccess_trust_provider_test.go index 12a7795c513..989bd33b997 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider_test.go +++ b/internal/service/ec2/verifiedaccess_trust_provider_test.go @@ -13,10 +13,9 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" - - tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" ) func TestAccVerifiedAccessTrustProvider_basic(t *testing.T) { @@ -152,8 +151,9 @@ func testAccCheckVerifiedAccessTrustProviderDestroy(ctx context.Context) resourc if tfresource.NotFound(err) { continue } + if err != nil { - return nil + return err } return create.Error(names.EC2, create.ErrActionCheckingDestroyed, tfec2.ResNameVerifiedAccessTrustProvider, rs.Primary.ID, errors.New("not destroyed")) diff --git a/website/docs/r/verifiedaccess_trust_provider.html.markdown b/website/docs/r/verifiedaccess_trust_provider.html.markdown index 9f2b35d5d46..5a28d4a3871 100644 --- a/website/docs/r/verifiedaccess_trust_provider.html.markdown +++ b/website/docs/r/verifiedaccess_trust_provider.html.markdown @@ -36,9 +36,9 @@ The following arguments are optional: * `tags` - (Optional) Key-value mapping of resource tags. If configured with a provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. * `user_trust_provider_type` - (Optional) The type of user-based trust provider. -## Attributes Reference +## Attribute Reference -In addition to all arguments above, the following attributes are exported: +This resource exports the following attributes in addition to the arguments above: * `id` - The ID of the AWS Verified Access trust provider. @@ -52,8 +52,17 @@ In addition to all arguments above, the following attributes are exported: ## Import -Verified Access Trust Providers can be imported using the `id`, e.g., +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import Transfer Workflows using the `id`. For example: +```terraform +import { + to = aws_verifiedaccess_trust_provider.example + id = "vatp-8012925589" +} ``` -$ terraform import aws_verifiedaccess_trust_provider.example vatp-8012925589 + +Using `terraform import`, import Transfer Workflows using the `id`. For example: + +```console +% terraform import aws_verifiedaccess_trust_provider.example vatp-8012925589 ``` From 40e4f8908d08cb5643f3bd1cc6453e647d086301 Mon Sep 17 00:00:00 2001 From: markos kandylis Date: Sun, 27 Aug 2023 22:57:27 +0100 Subject: [PATCH 06/14] Added change log --- .changelog/29689.txt | 3 +++ names/names_data.csv | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 .changelog/29689.txt diff --git a/.changelog/29689.txt b/.changelog/29689.txt new file mode 100644 index 00000000000..09fecf08d9c --- /dev/null +++ b/.changelog/29689.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_verifiedaccess_trust_provider +``` \ No newline at end of file diff --git a/names/names_data.csv b/names/names_data.csv index 06ec549582b..a1b6776400f 100644 --- a/names/names_data.csv +++ b/names/names_data.csv @@ -378,4 +378,4 @@ workspaces,workspaces,workspaces,workspaces,,workspaces,,,WorkSpaces,WorkSpaces, workspaces-web,workspacesweb,workspacesweb,workspacesweb,,workspacesweb,,,WorkSpacesWeb,WorkSpacesWeb,,1,,,aws_workspacesweb_,,workspacesweb_,WorkSpaces Web,Amazon,,x,,,, xray,xray,xray,xray,,xray,,,XRay,XRay,,,2,,aws_xray_,,xray_,X-Ray,AWS,,,,,, verifiedpermissions,verifiedpermissions,verifiedpermissions,verifiedpermissions,,verifiedpermissions,,,VerifiedPermissions,VerifiedPermissions,,,2,,aws_verifiedpermissions_,,verifiedpermissions_,Verified Permissions,Amazon,,,,,, -codecatalyst,codecatalyst,codecatalyst,codecatalyst,,codecatalyst,,,CodeCatalyst,CodeCatalyst,,,2,,aws_codecatalyst_,,codecatalyst_,CodeCatalyst,Amazon,,,,,, \ No newline at end of file +codecatalyst,codecatalyst,codecatalyst,codecatalyst,,codecatalyst,,,CodeCatalyst,CodeCatalyst,,,2,,aws_codecatalyst_,,codecatalyst_,CodeCatalyst,Amazon,,,,,, From fce50ff6f25ac25552c9542b8dfe2361098c5a1a Mon Sep 17 00:00:00 2001 From: markos kandylis Date: Sun, 27 Aug 2023 23:00:21 +0100 Subject: [PATCH 07/14] changed the changelog txt --- .changelog/{29689.txt => 29723.txt} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .changelog/{29689.txt => 29723.txt} (100%) diff --git a/.changelog/29689.txt b/.changelog/29723.txt similarity index 100% rename from .changelog/29689.txt rename to .changelog/29723.txt From 3352fef8f5f3347e810b0008ec39330b05224c99 Mon Sep 17 00:00:00 2001 From: markos kandylis Date: Sun, 27 Aug 2023 23:04:30 +0100 Subject: [PATCH 08/14] added headers --- internal/service/ec2/verifiedaccess_trust_provider.go | 3 +++ internal/service/ec2/verifiedaccess_trust_provider_test.go | 3 +++ 2 files changed, 6 insertions(+) diff --git a/internal/service/ec2/verifiedaccess_trust_provider.go b/internal/service/ec2/verifiedaccess_trust_provider.go index 48ef585f3e1..c7a2e28c98b 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider.go +++ b/internal/service/ec2/verifiedaccess_trust_provider.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package ec2 import ( diff --git a/internal/service/ec2/verifiedaccess_trust_provider_test.go b/internal/service/ec2/verifiedaccess_trust_provider_test.go index 989bd33b997..71587d3979a 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider_test.go +++ b/internal/service/ec2/verifiedaccess_trust_provider_test.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package ec2_test import ( From 835d310706c15ffddf0b5eeb6767e3cf05395eb4 Mon Sep 17 00:00:00 2001 From: markos kandylis Date: Mon, 28 Aug 2023 08:58:56 +0100 Subject: [PATCH 09/14] fixed Semgrep Checks error --- internal/service/ec2/verifiedaccess_trust_provider.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/internal/service/ec2/verifiedaccess_trust_provider.go b/internal/service/ec2/verifiedaccess_trust_provider.go index c7a2e28c98b..2bb9187d7ff 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider.go +++ b/internal/service/ec2/verifiedaccess_trust_provider.go @@ -117,10 +117,12 @@ func ResourceVerifiedaccessTrustProvider() *schema.Resource { }, }, "policy_reference_name": { - Type: schema.TypeString, - ForceNew: true, - Required: true, - ValidateFunc: validation.StringMatch(regexp.MustCompile(`[a-zA-Z_][a-zA-Z0-9_]*`), ""), + Type: schema.TypeString, + ForceNew: true, + Required: true, + ValidateFunc: validation.All( + validation.StringMatch(regexp.MustCompile(`[a-zA-Z_][a-zA-Z0-9_]*`), ""), + ), }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), From 711992adb33d562a568997ea0f31f8d5148ce02e Mon Sep 17 00:00:00 2001 From: markos kandylis Date: Mon, 28 Aug 2023 09:02:09 +0100 Subject: [PATCH 10/14] removed unnecessary line --- internal/service/ec2/verifiedaccess_trust_provider.go | 1 - 1 file changed, 1 deletion(-) diff --git a/internal/service/ec2/verifiedaccess_trust_provider.go b/internal/service/ec2/verifiedaccess_trust_provider.go index 2bb9187d7ff..7b7ba5ea0a6 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider.go +++ b/internal/service/ec2/verifiedaccess_trust_provider.go @@ -200,7 +200,6 @@ func resourceVerifiedaccessTrustProviderRead(ctx context.Context, d *schema.Reso output, err := FindVerifiedaccessTrustProviderByID(ctx, conn, d.Id()) - // ouxd := oux.DeviceOptions if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EC2 VerifiedaccessTrustProvider (%s) not found, removing from state", d.Id()) d.SetId("") From 7f132c8ff679085dd3fcb71c716c405d69c35cde Mon Sep 17 00:00:00 2001 From: markos kandylis Date: Mon, 28 Aug 2023 09:08:11 +0100 Subject: [PATCH 11/14] removed regex validate from name --- internal/service/ec2/verifiedaccess_trust_provider.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/internal/service/ec2/verifiedaccess_trust_provider.go b/internal/service/ec2/verifiedaccess_trust_provider.go index 7b7ba5ea0a6..93d80be4f85 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider.go +++ b/internal/service/ec2/verifiedaccess_trust_provider.go @@ -7,7 +7,6 @@ import ( "context" "errors" "log" - "regexp" "time" "github.com/aws/aws-sdk-go-v2/aws" @@ -120,9 +119,6 @@ func ResourceVerifiedaccessTrustProvider() *schema.Resource { Type: schema.TypeString, ForceNew: true, Required: true, - ValidateFunc: validation.All( - validation.StringMatch(regexp.MustCompile(`[a-zA-Z_][a-zA-Z0-9_]*`), ""), - ), }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), From 6722a535def99a274007d5a956a5a5d83d6e7b44 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 8 Sep 2023 15:23:49 -0400 Subject: [PATCH 12/14] Correct CHANGELOG entry file name. --- .changelog/{29723.txt => 33195.txt} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .changelog/{29723.txt => 33195.txt} (100%) diff --git a/.changelog/29723.txt b/.changelog/33195.txt similarity index 100% rename from .changelog/29723.txt rename to .changelog/33195.txt From a67a701fbebf64aee546716d980716407dd7958a Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 8 Sep 2023 16:09:57 -0400 Subject: [PATCH 13/14] r/aws_verifiedaccess_trust_provider: Cosmetics. --- internal/service/ec2/errors.go | 2 +- internal/service/ec2/find.go | 52 +++++-- internal/service/ec2/service_package_gen.go | 2 +- .../ec2/verifiedaccess_trust_provider.go | 137 ++++++++---------- .../ec2/verifiedaccess_trust_provider_test.go | 96 ++++++------ 5 files changed, 149 insertions(+), 140 deletions(-) diff --git a/internal/service/ec2/errors.go b/internal/service/ec2/errors.go index c9d219010ba..672311f60be 100644 --- a/internal/service/ec2/errors.go +++ b/internal/service/ec2/errors.go @@ -93,7 +93,6 @@ const ( errCodeInvalidSubnetIdNotFound = "InvalidSubnetId.NotFound" errCodeInvalidTrafficMirrorFilterIdNotFound = "InvalidTrafficMirrorFilterId.NotFound" errCodeInvalidTrafficMirrorFilterRuleIdNotFound = "InvalidTrafficMirrorFilterRuleId.NotFound" - errCodeInvalidVerifiedAccessTrustProviderIdNotFound = "InvalidVerifiedAccessTrustProviderId.NotFound" errCodeInvalidTrafficMirrorSessionIdNotFound = "InvalidTrafficMirrorSessionId.NotFound" errCodeInvalidTrafficMirrorTargetIdNotFound = "InvalidTrafficMirrorTargetId.NotFound" errCodeInvalidTransitGatewayAttachmentIDNotFound = "InvalidTransitGatewayAttachmentID.NotFound" @@ -101,6 +100,7 @@ const ( errCodeInvalidTransitGatewayPolicyTableIdNotFound = "InvalidTransitGatewayPolicyTableId.NotFound" errCodeInvalidTransitGatewayIDNotFound = "InvalidTransitGatewayID.NotFound" errCodeInvalidTransitGatewayMulticastDomainIdNotFound = "InvalidTransitGatewayMulticastDomainId.NotFound" + errCodeInvalidVerifiedAccessTrustProviderIdNotFound = "InvalidVerifiedAccessTrustProviderId.NotFound" errCodeInvalidVolumeNotFound = "InvalidVolume.NotFound" errCodeInvalidVPCCIDRBlockAssociationIDNotFound = "InvalidVpcCidrBlockAssociationID.NotFound" errCodeInvalidVPCEndpointIdNotFound = "InvalidVpcEndpointId.NotFound" diff --git a/internal/service/ec2/find.go b/internal/service/ec2/find.go index 53a8fac5b42..4604a86a4dd 100644 --- a/internal/service/ec2/find.go +++ b/internal/service/ec2/find.go @@ -7021,26 +7021,56 @@ func FindInstanceConnectEndpointByID(ctx context.Context, conn *ec2_sdkv2.Client return output, nil } -func FindVerifiedaccessTrustProviderByID(ctx context.Context, conn *ec2_sdkv2.Client, id string) (*ec2_sdkv2.DescribeVerifiedAccessTrustProvidersOutput, error) { - in := &ec2_sdkv2.DescribeVerifiedAccessTrustProvidersInput{ - VerifiedAccessTrustProviderIds: []string{id}, +func FindVerifiedAccessTrustProvider(ctx context.Context, conn *ec2_sdkv2.Client, input *ec2_sdkv2.DescribeVerifiedAccessTrustProvidersInput) (*awstypes.VerifiedAccessTrustProvider, error) { + output, err := FindVerifiedAccessTrustProviders(ctx, conn, input) + + if err != nil { + return nil, err } - out, err := conn.DescribeVerifiedAccessTrustProviders(ctx, in) - if tfawserr_sdkv2.ErrCodeEquals(err, errCodeInvalidVerifiedAccessTrustProviderIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: in, + return tfresource.AssertSingleValueResult(output) +} + +func FindVerifiedAccessTrustProviders(ctx context.Context, conn *ec2_sdkv2.Client, input *ec2_sdkv2.DescribeVerifiedAccessTrustProvidersInput) ([]awstypes.VerifiedAccessTrustProvider, error) { + var output []awstypes.VerifiedAccessTrustProvider + paginator := ec2_sdkv2.NewDescribeVerifiedAccessTrustProvidersPaginator(conn, input) + + for paginator.HasMorePages() { + page, err := paginator.NextPage(ctx) + + if tfawserr_sdkv2.ErrCodeEquals(err, errCodeInvalidVerifiedAccessTrustProviderIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } } + + if err != nil { + return nil, err + } + + output = append(output, page.VerifiedAccessTrustProviders...) + } + + return output, nil +} + +func FindVerifiedAccessTrustProviderByID(ctx context.Context, conn *ec2_sdkv2.Client, id string) (*awstypes.VerifiedAccessTrustProvider, error) { + input := &ec2_sdkv2.DescribeVerifiedAccessTrustProvidersInput{ + VerifiedAccessTrustProviderIds: []string{id}, } + output, err := FindVerifiedAccessTrustProvider(ctx, conn, input) if err != nil { return nil, err } - if out == nil || out.VerifiedAccessTrustProviders == nil { - return nil, tfresource.NewEmptyResultError(in) + // Eventual consistency check. + if aws_sdkv2.ToString(output.VerifiedAccessTrustProviderId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } } - return out, nil + return output, nil } diff --git a/internal/service/ec2/service_package_gen.go b/internal/service/ec2/service_package_gen.go index cd5e7ddff08..60cd9c773eb 100644 --- a/internal/service/ec2/service_package_gen.go +++ b/internal/service/ec2/service_package_gen.go @@ -944,7 +944,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVerifiedaccessTrustProvider, + Factory: ResourceVerifiedAccessTrustProvider, TypeName: "aws_verifiedaccess_trust_provider", Name: "Verified Access Trust Provider", Tags: &types.ServicePackageResourceTags{ diff --git a/internal/service/ec2/verifiedaccess_trust_provider.go b/internal/service/ec2/verifiedaccess_trust_provider.go index 93d80be4f85..79f1efa106d 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider.go +++ b/internal/service/ec2/verifiedaccess_trust_provider.go @@ -5,7 +5,6 @@ package ec2 import ( "context" - "errors" "log" "time" @@ -16,8 +15,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/create" "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -26,12 +25,12 @@ import ( // @SDKResource("aws_verifiedaccess_trust_provider", name="Verified Access Trust Provider") // @Tags(identifierAttribute="id") -func ResourceVerifiedaccessTrustProvider() *schema.Resource { +func ResourceVerifiedAccessTrustProvider() *schema.Resource { return &schema.Resource{ - CreateWithoutTimeout: resourceVerifiedaccessTrustProviderCreate, - ReadWithoutTimeout: resourceVerifiedaccessTrustProviderRead, - UpdateWithoutTimeout: resourceVerifiedaccessTrustProviderUpdate, - DeleteWithoutTimeout: resourceVerifiedaccessTrustProviderDelete, + CreateWithoutTimeout: resourceVerifiedAccessTrustProviderCreate, + ReadWithoutTimeout: resourceVerifiedAccessTrustProviderRead, + UpdateWithoutTimeout: resourceVerifiedAccessTrustProviderUpdate, + DeleteWithoutTimeout: resourceVerifiedAccessTrustProviderDelete, Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, @@ -140,146 +139,128 @@ func ResourceVerifiedaccessTrustProvider() *schema.Resource { } } -const ( - ResNameVerifiedAccessTrustProvider = "Verified Access Trust Provider" -) - -func resourceVerifiedaccessTrustProviderCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceVerifiedAccessTrustProviderCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) - in := &ec2.CreateVerifiedAccessTrustProviderInput{ + input := &ec2.CreateVerifiedAccessTrustProviderInput{ PolicyReferenceName: aws.String(d.Get("policy_reference_name").(string)), - TrustProviderType: types.TrustProviderType(d.Get("trust_provider_type").(string)), TagSpecifications: getTagSpecificationsInV2(ctx, types.ResourceTypeVerifiedAccessTrustProvider), + TrustProviderType: types.TrustProviderType(d.Get("trust_provider_type").(string)), } if v, ok := d.GetOk("description"); ok { - in.Description = aws.String(v.(string)) + input.Description = aws.String(v.(string)) } if v, ok := d.GetOk("device_options"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - in.DeviceOptions = expandCreateVerifiedAccessTrustProviderDeviceOptions(v.([]interface{})[0].(map[string]interface{})) + input.DeviceOptions = expandCreateVerifiedAccessTrustProviderDeviceOptions(v.([]interface{})[0].(map[string]interface{})) } if v, ok := d.GetOk("device_trust_provider_type"); ok { - in.DeviceTrustProviderType = types.DeviceTrustProviderType(v.(string)) - } - - if v, ok := d.GetOk("user_trust_provider_type"); ok { - in.UserTrustProviderType = types.UserTrustProviderType(v.(string)) + input.DeviceTrustProviderType = types.DeviceTrustProviderType(v.(string)) } if v, ok := d.GetOk("oidc_options"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - in.OidcOptions = expandCreateVerifiedAccessTrustProviderOIDCOptions(v.([]interface{})[0].(map[string]interface{})) + input.OidcOptions = expandCreateVerifiedAccessTrustProviderOIDCOptions(v.([]interface{})[0].(map[string]interface{})) } - out, err := conn.CreateVerifiedAccessTrustProvider(ctx, in) - if err != nil { - return append(diags, create.DiagError(names.EC2, create.ErrActionCreating, ResNameVerifiedAccessTrustProvider, "", err)...) + if v, ok := d.GetOk("user_trust_provider_type"); ok { + input.UserTrustProviderType = types.UserTrustProviderType(v.(string)) } - if out == nil { - return append(diags, create.DiagError(names.EC2, create.ErrActionCreating, ResNameVerifiedAccessTrustProvider, "", errors.New("empty output"))...) + output, err := conn.CreateVerifiedAccessTrustProvider(ctx, input) + + if err != nil { + return sdkdiag.AppendErrorf(diags, "creating Verified Access Trust Provider: %s", err) } - d.SetId(aws.ToString(out.VerifiedAccessTrustProvider.VerifiedAccessTrustProviderId)) + d.SetId(aws.ToString(output.VerifiedAccessTrustProvider.VerifiedAccessTrustProviderId)) - return append(diags, resourceVerifiedaccessTrustProviderRead(ctx, d, meta)...) + return append(diags, resourceVerifiedAccessTrustProviderRead(ctx, d, meta)...) } -func resourceVerifiedaccessTrustProviderRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceVerifiedAccessTrustProviderRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) - output, err := FindVerifiedaccessTrustProviderByID(ctx, conn, d.Id()) + output, err := FindVerifiedAccessTrustProviderByID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { - log.Printf("[WARN] EC2 VerifiedaccessTrustProvider (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] EC2 Verified Access Trust Provider (%s) not found, removing from state", d.Id()) d.SetId("") return diags } if err != nil { - return append(diags, create.DiagError(names.EC2, create.ErrActionReading, ResNameVerifiedAccessTrustProvider, d.Id(), err)...) + return sdkdiag.AppendErrorf(diags, "reading Verified Access Trust Provider (%s): %s", d.Id(), err) } - d.Set("description", output.VerifiedAccessTrustProviders[0].Description) - - if v := output.VerifiedAccessTrustProviders[0].DeviceOptions; v != nil { + d.Set("description", output.Description) + if v := output.DeviceOptions; v != nil { if err := d.Set("device_options", flattenDeviceOptions(v)); err != nil { - return create.DiagError(names.EC2, create.ErrActionSetting, ResNameVerifiedAccessTrustProvider, d.Id(), err) + return sdkdiag.AppendErrorf(diags, "setting device_options: %s", err) } + } else { + d.Set("device_options", nil) } - - d.Set("device_trust_provider_type", output.VerifiedAccessTrustProviders[0].DeviceTrustProviderType) - - if v := output.VerifiedAccessTrustProviders[0].OidcOptions; v != nil { + d.Set("device_trust_provider_type", output.DeviceTrustProviderType) + if v := output.OidcOptions; v != nil { if err := d.Set("oidc_options", flattenOIDCOptions(v, d.Get("oidc_options.0.client_secret").(string))); err != nil { - return create.DiagError(names.EC2, create.ErrActionSetting, ResNameVerifiedAccessTrustProvider, d.Id(), err) + return sdkdiag.AppendErrorf(diags, "setting oidc_options: %s", err) } + } else { + d.Set("oidc_options", nil) } + d.Set("policy_reference_name", output.PolicyReferenceName) + d.Set("trust_provider_type", output.TrustProviderType) + d.Set("user_trust_provider_type", output.UserTrustProviderType) + + setTagsOutV2(ctx, output.Tags) - d.Set("policy_reference_name", output.VerifiedAccessTrustProviders[0].PolicyReferenceName) - d.Set("trust_provider_type", output.VerifiedAccessTrustProviders[0].TrustProviderType) - d.Set("user_trust_provider_type", output.VerifiedAccessTrustProviders[0].UserTrustProviderType) - setTagsOutV2(ctx, output.VerifiedAccessTrustProviders[0].Tags) return diags } -func resourceVerifiedaccessTrustProviderUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceVerifiedAccessTrustProviderUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) - update := false - - in := &ec2.ModifyVerifiedAccessTrustProviderInput{ - VerifiedAccessTrustProviderId: aws.String(d.Id()), - } + if d.HasChangesExcept("tags", "tags_all") { + input := &ec2.ModifyVerifiedAccessTrustProviderInput{ + VerifiedAccessTrustProviderId: aws.String(d.Id()), + } - if d.HasChanges("description") { - if v, ok := d.GetOk("description"); ok { - in.Description = aws.String(v.(string)) - update = true + if d.HasChanges("description") { + input.Description = aws.String(d.Get("description").(string)) } - } - if d.HasChanges("oidc_options") { - if v, ok := d.GetOk("oidc_options"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - in.OidcOptions = expandModifyVerifiedAccessTrustProviderOIDCOptions(v.([]interface{})[0].(map[string]interface{})) - update = true + if d.HasChanges("oidc_options") { + if v, ok := d.GetOk("oidc_options"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.OidcOptions = expandModifyVerifiedAccessTrustProviderOIDCOptions(v.([]interface{})[0].(map[string]interface{})) + } } - } - if !update { - return diags - } + _, err := conn.ModifyVerifiedAccessTrustProvider(ctx, input) - log.Printf("[DEBUG] Updating EC2 VerifiedaccessTrustProvider (%s): %#v", d.Id(), in) - _, err := conn.ModifyVerifiedAccessTrustProvider(ctx, in) - if err != nil { - return append(diags, create.DiagError(names.EC2, create.ErrActionUpdating, ResNameVerifiedAccessTrustProvider, d.Id(), err)...) + if err != nil { + return sdkdiag.AppendErrorf(diags, "updating Verified Access Trust Provider (%s): %s", d.Id(), err) + } } - return append(diags, resourceVerifiedaccessTrustProviderRead(ctx, d, meta)...) + return append(diags, resourceVerifiedAccessTrustProviderRead(ctx, d, meta)...) } -func resourceVerifiedaccessTrustProviderDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceVerifiedAccessTrustProviderDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) - log.Printf("[INFO] Deleting EC2 VerifiedaccessTrustProvider %s", d.Id()) - + log.Printf("[INFO] Deleting Verified Access Trust Provider: %s", d.Id()) _, err := conn.DeleteVerifiedAccessTrustProvider(ctx, &ec2.DeleteVerifiedAccessTrustProviderInput{ VerifiedAccessTrustProviderId: aws.String(d.Id()), }) if err != nil { - return append(diags, create.DiagError(names.EC2, create.ErrActionDeleting, ResNameVerifiedAccessTrustProvider, d.Id(), err)...) + return sdkdiag.AppendErrorf(diags, "deleting Verified Access Trust Provider (%s): %s", d.Id(), err) } return diags diff --git a/internal/service/ec2/verifiedaccess_trust_provider_test.go b/internal/service/ec2/verifiedaccess_trust_provider_test.go index 71587d3979a..66506adaa62 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider_test.go +++ b/internal/service/ec2/verifiedaccess_trust_provider_test.go @@ -5,17 +5,16 @@ package ec2_test import ( "context" - "errors" "fmt" "testing" "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2/types" 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" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/create" tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" @@ -28,7 +27,7 @@ func TestAccVerifiedAccessTrustProvider_basic(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var verifiedaccesstrustprovider ec2.DescribeVerifiedAccessTrustProvidersOutput + var v types.VerifiedAccessTrustProvider resourceName := "aws_verifiedaccess_trust_provider.test" policyReferenceName := "test" trustProviderType := "user" @@ -49,7 +48,7 @@ func TestAccVerifiedAccessTrustProvider_basic(t *testing.T) { { Config: testAccVerifiedAccessTrustProviderConfig_basic(policyReferenceName, trustProviderType, userTrustProviderType, description), Check: resource.ComposeTestCheckFunc( - testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", description), resource.TestCheckResourceAttr(resourceName, "policy_reference_name", policyReferenceName), resource.TestCheckResourceAttr(resourceName, "trust_provider_type", trustProviderType), @@ -68,7 +67,7 @@ func TestAccVerifiedAccessTrustProvider_basic(t *testing.T) { func TestAccVerifiedAccessTrustProvider_deviceOptions(t *testing.T) { ctx := acctest.Context(t) - var verifiedaccesstrustprovider ec2.DescribeVerifiedAccessTrustProvidersOutput + var v types.VerifiedAccessTrustProvider resourceName := "aws_verifiedaccess_trust_provider.test" policyReferenceName := "test" trustProviderType := "device" @@ -87,7 +86,7 @@ func TestAccVerifiedAccessTrustProvider_deviceOptions(t *testing.T) { { Config: testAccVerifiedAccessTrustProviderConfig_deviceOptions(policyReferenceName, trustProviderType, deviceTrustProviderType, tenantId), Check: resource.ComposeTestCheckFunc( - testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &v), resource.TestCheckResourceAttr(resourceName, "device_options.#", "1"), resource.TestCheckResourceAttr(resourceName, "device_options.0.tenant_id", tenantId), resource.TestCheckResourceAttr(resourceName, "device_trust_provider_type", deviceTrustProviderType), @@ -111,7 +110,7 @@ func TestAccVerifiedAccessTrustProvider_disappears(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var verifiedaccesstrustprovider ec2.DescribeVerifiedAccessTrustProvidersOutput + var v types.VerifiedAccessTrustProvider resourceName := "aws_verifiedaccess_trust_provider.test" policyReferenceName := "test" trustProviderType := "user" @@ -132,8 +131,8 @@ func TestAccVerifiedAccessTrustProvider_disappears(t *testing.T) { { Config: testAccVerifiedAccessTrustProviderConfig_basic(policyReferenceName, trustProviderType, userTrustProviderType, description), Check: resource.ComposeTestCheckFunc( - testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), - acctest.CheckResourceDisappears(ctx, acctest.Provider, tfec2.ResourceVerifiedaccessTrustProvider(), resourceName), + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &v), + acctest.CheckResourceDisappears(ctx, acctest.Provider, tfec2.ResourceVerifiedAccessTrustProvider(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -141,34 +140,9 @@ func TestAccVerifiedAccessTrustProvider_disappears(t *testing.T) { }) } -func testAccCheckVerifiedAccessTrustProviderDestroy(ctx context.Context) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - - for _, rs := range s.RootModule().Resources { - if rs.Type != "aws_verifiedaccess_trust_provider" { - continue - } - - _, err := tfec2.FindVerifiedaccessTrustProviderByID(ctx, conn, rs.Primary.ID) - if tfresource.NotFound(err) { - continue - } - - if err != nil { - return err - } - - return create.Error(names.EC2, create.ErrActionCheckingDestroyed, tfec2.ResNameVerifiedAccessTrustProvider, rs.Primary.ID, errors.New("not destroyed")) - } - - return nil - } -} - func TestAccVerifiedAccessTrustProvider_oidcOptions(t *testing.T) { ctx := acctest.Context(t) - var verifiedaccesstrustprovider ec2.DescribeVerifiedAccessTrustProvidersOutput + var v types.VerifiedAccessTrustProvider resourceName := "aws_verifiedaccess_trust_provider.test" policyReferenceName := "test" trustProviderType := "user" @@ -193,7 +167,7 @@ func TestAccVerifiedAccessTrustProvider_oidcOptions(t *testing.T) { { Config: testAccVerifiedAccessTrustProviderConfig_oidcOptions(policyReferenceName, trustProviderType, userTrustProviderType, authorizationEndpoint, clientId, clientSecret, issuer, scope, tokenEndpoint, userInfoEndpoint), Check: resource.ComposeTestCheckFunc( - testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &v), resource.TestCheckResourceAttr(resourceName, "oidc_options.#", "1"), resource.TestCheckResourceAttr(resourceName, "oidc_options.0.authorization_endpoint", authorizationEndpoint), resource.TestCheckResourceAttr(resourceName, "oidc_options.0.client_id", clientId), @@ -219,7 +193,7 @@ func TestAccVerifiedAccessTrustProvider_oidcOptions(t *testing.T) { func TestAccVerifiedAccessTrustProvider_tags(t *testing.T) { ctx := acctest.Context(t) - var verifiedaccesstrustprovider ec2.DescribeVerifiedAccessTrustProvidersOutput + var v types.VerifiedAccessTrustProvider resourceName := "aws_verifiedaccess_trust_provider.test" policyReferenceName := "test" trustProviderType := "user" @@ -239,7 +213,7 @@ func TestAccVerifiedAccessTrustProvider_tags(t *testing.T) { { Config: testAccVerifiedAccessTrustProviderConfig_tags1(policyReferenceName, trustProviderType, userTrustProviderType, description, "key1", "value1"), Check: resource.ComposeTestCheckFunc( - testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), @@ -247,7 +221,7 @@ func TestAccVerifiedAccessTrustProvider_tags(t *testing.T) { { Config: testAccVerifiedAccessTrustProviderConfig_tags2(policyReferenceName, trustProviderType, userTrustProviderType, description, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), @@ -256,7 +230,7 @@ func TestAccVerifiedAccessTrustProvider_tags(t *testing.T) { { Config: testAccVerifiedAccessTrustProviderConfig_tags1(policyReferenceName, trustProviderType, userTrustProviderType, description, "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &verifiedaccesstrustprovider), + testAccCheckVerifiedAccessTrustProviderExists(ctx, resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), @@ -271,24 +245,48 @@ func TestAccVerifiedAccessTrustProvider_tags(t *testing.T) { }) } -func testAccCheckVerifiedAccessTrustProviderExists(ctx context.Context, name string, verifiedaccesstrustprovider *ec2.DescribeVerifiedAccessTrustProvidersOutput) resource.TestCheckFunc { +func testAccCheckVerifiedAccessTrustProviderExists(ctx context.Context, n string, v *types.VerifiedAccessTrustProvider) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[name] + rs, ok := s.RootModule().Resources[n] if !ok { - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedAccessTrustProvider, name, errors.New("not found")) - } - if rs.Primary.ID == "" { - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedAccessTrustProvider, name, errors.New("not set")) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - resp, err := tfec2.FindVerifiedaccessTrustProviderByID(ctx, conn, rs.Primary.ID) + output, err := tfec2.FindVerifiedAccessTrustProviderByID(ctx, conn, rs.Primary.ID) + if err != nil { - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameVerifiedAccessTrustProvider, rs.Primary.ID, err) + return err } - *verifiedaccesstrustprovider = *resp + *v = *output + + return nil + } +} + +func testAccCheckVerifiedAccessTrustProviderDestroy(ctx context.Context) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_verifiedaccess_trust_provider" { + continue + } + + _, err := tfec2.FindVerifiedAccessTrustProviderByID(ctx, conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("Verified Access Trust Provider %s still exists", rs.Primary.ID) + } return nil } From 7698f2674aa4a2ce0448d198c0e7468698aac328 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 8 Sep 2023 16:11:59 -0400 Subject: [PATCH 14/14] 'testAccPreCheck' -> 'testAccPreCheckVerifiedAccess'. --- .../ec2/verifiedaccess_trust_provider_test.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/internal/service/ec2/verifiedaccess_trust_provider_test.go b/internal/service/ec2/verifiedaccess_trust_provider_test.go index 66506adaa62..5c9deab6aac 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider_test.go +++ b/internal/service/ec2/verifiedaccess_trust_provider_test.go @@ -38,7 +38,7 @@ func TestAccVerifiedAccessTrustProvider_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(ctx, t) acctest.PreCheckPartitionHasService(t, names.EC2) - testAccPreCheck(ctx, t) + testAccPreCheckVerifiedAccess(ctx, t) acctest.PreCheckIAMServiceLinkedRole(ctx, t, "/aws-service-role/sso.amazonaws.com") }, ErrorCheck: acctest.ErrorCheck(t, names.EC2), @@ -77,7 +77,7 @@ func TestAccVerifiedAccessTrustProvider_deviceOptions(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - testAccPreCheck(ctx, t) + testAccPreCheckVerifiedAccess(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, @@ -122,7 +122,7 @@ func TestAccVerifiedAccessTrustProvider_disappears(t *testing.T) { acctest.PreCheck(ctx, t) acctest.PreCheckPartitionHasService(t, names.EC2) acctest.PreCheckIAMServiceLinkedRole(ctx, t, "/aws-service-role/sso.amazonaws.com") - testAccPreCheck(ctx, t) + testAccPreCheckVerifiedAccess(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, @@ -158,7 +158,7 @@ func TestAccVerifiedAccessTrustProvider_oidcOptions(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - testAccPreCheck(ctx, t) + testAccPreCheckVerifiedAccess(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, @@ -203,7 +203,7 @@ func TestAccVerifiedAccessTrustProvider_tags(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - testAccPreCheck(ctx, t) + testAccPreCheckVerifiedAccess(ctx, t) acctest.PreCheckIAMServiceLinkedRole(ctx, t, "/aws-service-role/sso.amazonaws.com") }, ErrorCheck: acctest.ErrorCheck(t, names.EC2), @@ -292,7 +292,7 @@ func testAccCheckVerifiedAccessTrustProviderDestroy(ctx context.Context) resourc } } -func testAccPreCheck(ctx context.Context, t *testing.T) { +func testAccPreCheckVerifiedAccess(ctx context.Context, t *testing.T) { conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeVerifiedAccessTrustProvidersInput{}