Skip to content

Commit

Permalink
Merge pull request #24907 from DrFaust92/redshift-auth-profile
Browse files Browse the repository at this point in the history
r/redshift_authentication_profile - new resource
  • Loading branch information
ewbankkit authored May 23, 2022
2 parents 077be83 + db3e2ac commit fc42f46
Show file tree
Hide file tree
Showing 7 changed files with 385 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .changelog/24907.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
aws_redshift_authentication_profile
```
1 change: 1 addition & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1761,6 +1761,7 @@ func Provider() *schema.Provider {
"aws_rds_cluster_role_association": rds.ResourceClusterRoleAssociation(),
"aws_rds_global_cluster": rds.ResourceGlobalCluster(),

"aws_redshift_authentication_profile": redshift.ResourceAuthenticationProfile(),
"aws_redshift_cluster": redshift.ResourceCluster(),
"aws_redshift_event_subscription": redshift.ResourceEventSubscription(),
"aws_redshift_hsm_client_certificate": redshift.ResourceHsmClientCertificate(),
Expand Down
125 changes: 125 additions & 0 deletions internal/service/redshift/authentication_profile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package redshift

import (
"fmt"
"log"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/redshift"
"github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
)

func ResourceAuthenticationProfile() *schema.Resource {
return &schema.Resource{
Create: resourceAuthenticationProfileCreate,
Read: resourceAuthenticationProfileRead,
Update: resourceAuthenticationProfileUpdate,
Delete: resourceAuthenticationProfileDelete,

Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"authentication_profile_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"authentication_profile_content": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringIsJSON,
DiffSuppressFunc: verify.SuppressEquivalentJSONDiffs,
StateFunc: func(v interface{}) string {
json, _ := structure.NormalizeJsonString(v)
return json
},
},
},
}
}

func resourceAuthenticationProfileCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).RedshiftConn

authProfileName := d.Get("authentication_profile_name").(string)

input := redshift.CreateAuthenticationProfileInput{
AuthenticationProfileName: aws.String(authProfileName),
AuthenticationProfileContent: aws.String(d.Get("authentication_profile_content").(string)),
}

out, err := conn.CreateAuthenticationProfile(&input)

if err != nil {
return fmt.Errorf("error creating Redshift Authentication Profile (%s): %s", authProfileName, err)
}

d.SetId(aws.StringValue(out.AuthenticationProfileName))

return resourceAuthenticationProfileRead(d, meta)
}

func resourceAuthenticationProfileRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).RedshiftConn

out, err := FindAuthenticationProfileByID(conn, d.Id())
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] Redshift Authentication Profile (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}

if err != nil {
return fmt.Errorf("error reading Redshift Authentication Profile (%s): %w", d.Id(), err)
}

d.Set("authentication_profile_content", out.AuthenticationProfileContent)
d.Set("authentication_profile_name", out.AuthenticationProfileName)

return nil
}

func resourceAuthenticationProfileUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).RedshiftConn

input := &redshift.ModifyAuthenticationProfileInput{
AuthenticationProfileName: aws.String(d.Id()),
AuthenticationProfileContent: aws.String(d.Get("authentication_profile_content").(string)),
}

_, err := conn.ModifyAuthenticationProfile(input)

if err != nil {
return fmt.Errorf("error modifying Redshift Authentication Profile (%s): %w", d.Id(), err)
}

return resourceAuthenticationProfileRead(d, meta)
}

func resourceAuthenticationProfileDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).RedshiftConn

deleteInput := redshift.DeleteAuthenticationProfileInput{
AuthenticationProfileName: aws.String(d.Id()),
}

log.Printf("[DEBUG] Deleting Redshift Authentication Profile: %s", d.Id())
_, err := conn.DeleteAuthenticationProfile(&deleteInput)

if err != nil {
if tfawserr.ErrCodeEquals(err, redshift.ErrCodeAuthenticationProfileNotFoundFault) {
return nil
}
return err
}

return err
}
133 changes: 133 additions & 0 deletions internal/service/redshift/authentication_profile_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package redshift_test

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/service/redshift"
sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/hashicorp/terraform-provider-aws/internal/acctest"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
tfredshift "github.com/hashicorp/terraform-provider-aws/internal/service/redshift"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
)

func TestAccRedshiftAuthenticationProfile_basic(t *testing.T) {
resourceName := "aws_redshift_authentication_profile.test"
rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)
rNameUpdated := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID),
ProviderFactories: acctest.ProviderFactories,
CheckDestroy: testAccCheckAuthenticationProfileDestroy,
Steps: []resource.TestStep{
{
Config: testAccAuthenticationProfileBasic(rName, rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAuthenticationProfileExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "authentication_profile_name", rName),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccAuthenticationProfileBasic(rName, rNameUpdated),
Check: resource.ComposeTestCheckFunc(
testAccCheckAuthenticationProfileExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "authentication_profile_name", rName),
),
},
},
})
}

func TestAccRedshiftAuthenticationProfile_disappears(t *testing.T) {
resourceName := "aws_redshift_authentication_profile.test"
rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID),
ProviderFactories: acctest.ProviderFactories,
CheckDestroy: testAccCheckAuthenticationProfileDestroy,
Steps: []resource.TestStep{
{
Config: testAccAuthenticationProfileBasic(rName, rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAuthenticationProfileExists(resourceName),
acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceAuthenticationProfile(), resourceName),
),
ExpectNonEmptyPlan: true,
},
},
})
}

func testAccCheckAuthenticationProfileDestroy(s *terraform.State) error {
conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn

for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_redshift_authentication_profile" {
continue
}

_, err := tfredshift.FindAuthenticationProfileByID(conn, rs.Primary.ID)

if tfresource.NotFound(err) {
continue
}

if err != nil {
return err
}

return fmt.Errorf("Redshift Authentication Profile %s still exists", rs.Primary.ID)
}

return nil
}

func testAccCheckAuthenticationProfileExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[name]
if !ok {
return fmt.Errorf("not found: %s", name)
}

if rs.Primary.ID == "" {
return fmt.Errorf("Authentication Profile ID is not set")
}

conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn

_, err := tfredshift.FindAuthenticationProfileByID(conn, rs.Primary.ID)

if err != nil {
return err
}

return nil
}
}

func testAccAuthenticationProfileBasic(rName, id string) string {
return fmt.Sprintf(`
resource "aws_redshift_authentication_profile" "test" {
authentication_profile_name = %[1]q
authentication_profile_content = jsonencode(
{
AllowDBUserOverride = "1"
Client_ID = "ExampleClientID"
App_ID = %[2]q
}
)
}
`, rName, id)
}
28 changes: 28 additions & 0 deletions internal/service/redshift/find.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,31 @@ func FindUsageLimitByID(conn *redshift.Redshift, id string) (*redshift.UsageLimi

return output.UsageLimits[0], nil
}

func FindAuthenticationProfileByID(conn *redshift.Redshift, id string) (*redshift.AuthenticationProfile, error) {
input := redshift.DescribeAuthenticationProfilesInput{
AuthenticationProfileName: aws.String(id),
}

out, err := conn.DescribeAuthenticationProfiles(&input)
if tfawserr.ErrCodeEquals(err, redshift.ErrCodeAuthenticationProfileNotFoundFault) {
return nil, &resource.NotFoundError{
LastError: err,
LastRequest: input,
}
}

if err != nil {
return nil, err
}

if out == nil || len(out.AuthenticationProfiles) == 0 {
return nil, tfresource.NewEmptyResultError(input)
}

if count := len(out.AuthenticationProfiles); count > 1 {
return nil, tfresource.NewTooManyResultsError(count, input)
}

return out.AuthenticationProfiles[0], nil
}
48 changes: 48 additions & 0 deletions internal/service/redshift/sweep.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ func init() {
F: sweepHsmClientCertificates,
})

resource.AddTestSweepers("aws_redshift_authentication_profile", &resource.Sweeper{
Name: "aws_redshift_authentication_profile",
F: sweepAuthenticationProfiles,
})

resource.AddTestSweepers("aws_redshift_event_subscription", &resource.Sweeper{
Name: "aws_redshift_event_subscription",
F: sweepEventSubscriptions,
Expand Down Expand Up @@ -385,3 +390,46 @@ func sweepHsmClientCertificates(region string) error {

return errs.ErrorOrNil()
}

func sweepAuthenticationProfiles(region string) error {
client, err := sweep.SharedRegionalSweepClient(region)

if err != nil {
return fmt.Errorf("error getting client: %s", err)
}

conn := client.(*conns.AWSClient).RedshiftConn
sweepResources := make([]*sweep.SweepResource, 0)
var errs *multierror.Error

input := &redshift.DescribeAuthenticationProfilesInput{}
output, err := conn.DescribeAuthenticationProfiles(input)

if len(output.AuthenticationProfiles) == 0 {
log.Print("[DEBUG] No Redshift Authentication Profiles to sweep")
}

if err != nil {
errs = multierror.Append(errs, fmt.Errorf("error describing Redshift Authentication Profiles: %w", err))
// in case work can be done, don't jump out yet
}

for _, c := range output.AuthenticationProfiles {
r := ResourceAuthenticationProfile()
d := r.Data(nil)
d.SetId(aws.StringValue(c.AuthenticationProfileName))

sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client))
}

if err = sweep.SweepOrchestrator(sweepResources); err != nil {
errs = multierror.Append(errs, fmt.Errorf("error sweeping Redshift Authentication Profiles for %s: %w", region, err))
}

if sweep.SkipSweepError(errs.ErrorOrNil()) {
log.Printf("[WARN] Skipping Redshift Authentication Profile sweep for %s: %s", region, err)
return nil
}

return errs.ErrorOrNil()
}
Loading

0 comments on commit fc42f46

Please sign in to comment.