Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add quicksight group membership resource #20687

Merged
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/20687.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
aws_quicksight_group_membership
```
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -964,6 +964,7 @@ func Provider() *schema.Provider {
"aws_proxy_protocol_policy": resourceAwsProxyProtocolPolicy(),
"aws_qldb_ledger": resourceAwsQLDBLedger(),
"aws_quicksight_group": resourceAwsQuickSightGroup(),
"aws_quicksight_group_membership": resourceAwsQuickSightGroupMembership(),
"aws_quicksight_user": resourceAwsQuickSightUser(),
"aws_ram_principal_association": resourceAwsRamPrincipalAssociation(),
"aws_ram_resource_association": resourceAwsRamResourceAssociation(),
Expand Down
177 changes: 177 additions & 0 deletions aws/resource_aws_quicksight_group_membership.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
package aws

import (
"context"
"fmt"
"log"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/quicksight"
"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"
)

func resourceAwsQuickSightGroupMembership() *schema.Resource {
return &schema.Resource{
CreateContext: resourceAwsQuickSightGroupMembershipCreate,
ReadContext: resourceAwsQuickSightGroupMembershipRead,
DeleteContext: resourceAwsQuickSightGroupMembershipDelete,
anGie44 marked this conversation as resolved.
Show resolved Hide resolved

Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
},

Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},

"aws_account_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},

"member_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"group_name": {
Type: schema.TypeString,
Optional: true,
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
ForceNew: true,
},

"namespace": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "default",
ValidateFunc: validation.StringInSlice([]string{
"default",
}, false),
},
},
}
}

func resourceAwsQuickSightGroupMembershipCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*AWSClient).quicksightconn

awsAccountID := meta.(*AWSClient).accountid
namespace := d.Get("namespace").(string)
groupName := d.Get("group_name").(string)

if v, ok := d.GetOk("aws_account_id"); ok {
awsAccountID = v.(string)
}

createOpts := &quicksight.CreateGroupMembershipInput{
AwsAccountId: aws.String(awsAccountID),
GroupName: aws.String(groupName),
MemberName: aws.String(d.Get("member_name").(string)),
Namespace: aws.String(namespace),
}

resp, err := conn.CreateGroupMembershipWithContext(ctx, createOpts)
if err != nil {
return diag.Errorf("Error adding QuickSight user to group: %s", err)
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
}

d.SetId(fmt.Sprintf("%s/%s/%s/%s", awsAccountID, namespace, groupName, aws.StringValue(resp.GroupMember.MemberName)))

return resourceAwsQuickSightGroupMembershipRead(ctx, d, meta)
}

func resourceAwsQuickSightGroupMembershipRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*AWSClient).quicksightconn

awsAccountID, namespace, groupName, userName, err := resourceAwsQuickSightGroupMembershipParseID(d.Id())
if err != nil {
return diag.Errorf("%s", err)
}

listOpts := &quicksight.ListUserGroupsInput{
AwsAccountId: aws.String(awsAccountID),
Namespace: aws.String(namespace),
UserName: aws.String(userName),
}

found := false

for {
resp, err := conn.ListUserGroupsWithContext(ctx, listOpts)
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
if isAWSErr(err, quicksight.ErrCodeResourceNotFoundException, "") {
log.Printf("[WARN] QuickSight User %s is not found", d.Id())
d.SetId("")
return nil
}
if err != nil {
return diag.Errorf("Error listing QuickSight User groups (%s): %s", d.Id(), err)
}

for _, group := range resp.GroupList {
if aws.StringValue(group.GroupName) == groupName {
found = true
break
}
}

if found || resp.NextToken == nil {
break
}

listOpts.NextToken = resp.NextToken
}

if found {
d.Set("aws_account_id", awsAccountID)
d.Set("namespace", namespace)
d.Set("member_name", userName)
d.Set("group_name", groupName)
} else {
log.Printf("[WARN] QuickSight User-group membership %s is not found", d.Id())
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
d.SetId("")
}
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
anGie44 marked this conversation as resolved.
Show resolved Hide resolved

return nil
}

func resourceAwsQuickSightGroupMembershipDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*AWSClient).quicksightconn

awsAccountID, namespace, groupName, userName, err := resourceAwsQuickSightGroupMembershipParseID(d.Id())
if err != nil {
return diag.Errorf("%s", err)
}

deleteOpts := &quicksight.DeleteGroupMembershipInput{
AwsAccountId: aws.String(awsAccountID),
Namespace: aws.String(namespace),
MemberName: aws.String(userName),
GroupName: aws.String(groupName),
}

if _, err := conn.DeleteGroupMembershipWithContext(ctx, deleteOpts); err != nil {
if isAWSErr(err, quicksight.ErrCodeResourceNotFoundException, "") {
return nil
}
return diag.Errorf("Error deleting QuickSight User-group membership %s: %s", d.Id(), err)
}

return nil
}

func resourceAwsQuickSightGroupMembershipParseID(id string) (string, string, string, string, error) {
parts := strings.SplitN(id, "/", 4)
if len(parts) < 4 || parts[0] == "" || parts[1] == "" || parts[2] == "" || parts[3] == "" {
return "", "", "", "", fmt.Errorf("unexpected format of ID (%s), expected AWS_ACCOUNT_ID/NAMESPACE/GROUP_NAME/USER_NAME", id)
}
return parts[0], parts[1], parts[2], parts[3], nil
}
149 changes: 149 additions & 0 deletions aws/resource_aws_quicksight_group_membership_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package aws

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/quicksight"
"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"
)

func TestAccAWSQuickSightGroupMembership_basic(t *testing.T) {
groupName := acctest.RandomWithPrefix("tf-acc-test")
memberName := "tfacctest" + acctest.RandString(10)
resourceName := "aws_quicksight_group_membership.default"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
// There's no way to actual retrieve a group membership after
// the user and group have been destroyed.
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
ErrorCheck: testAccErrorCheck(t, quicksight.EndpointsID),
CheckDestroy: testAccCheckQuickSightGroupMembershipWaveHandsEverythingsOkay,
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccAWSQuickSightGroupMembershipConfig(groupName, memberName),
Check: resource.ComposeTestCheckFunc(
testAccCheckQuickSightGroupMembershipExists(resourceName),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func TestAccAWSQuickSightGroupMembership_disappears(t *testing.T) {
groupName := acctest.RandomWithPrefix("tf-acc-test")
memberName := "tfacctest" + acctest.RandString(10)
resourceName := "aws_quicksight_group_membership.default"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ErrorCheck: testAccErrorCheck(t, quicksight.EndpointsID),
Providers: testAccProviders,
// There's no way to actual retrieve a group membership after
// the user and group have been destroyed.
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
CheckDestroy: testAccCheckQuickSightGroupMembershipWaveHandsEverythingsOkay,
Steps: []resource.TestStep{
{
Config: testAccAWSQuickSightGroupMembershipConfig(groupName, memberName),
Check: resource.ComposeTestCheckFunc(
testAccCheckQuickSightGroupMembershipExists(resourceName),
testAccCheckQuickSightGroupMembershipDisappears(groupName, memberName),
lacernetic marked this conversation as resolved.
Show resolved Hide resolved
),
ExpectNonEmptyPlan: true,
},
},
})
}

func testAccCheckQuickSightGroupMembershipWaveHandsEverythingsOkay(s *terraform.State) error {
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
return nil
}

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

awsAccountID, namespace, groupName, userName, err := resourceAwsQuickSightGroupMembershipParseID(rs.Primary.ID)
if err != nil {
return err
}

conn := testAccProvider.Meta().(*AWSClient).quicksightconn

input := &quicksight.ListUserGroupsInput{
AwsAccountId: aws.String(awsAccountID),
Namespace: aws.String(namespace),
UserName: aws.String(userName),
}

output, err := conn.ListUserGroups(input)

if err != nil {
return err
}

if output == nil || output.GroupList == nil {
return fmt.Errorf("QuickSight Group (%s) not found", rs.Primary.ID)
}

for _, group := range output.GroupList {
if *group.GroupName == groupName {
return nil
}
}

return fmt.Errorf("QuickSight Group (%s) not found in user's group list", rs.Primary.ID)
}
}

func testAccCheckQuickSightGroupMembershipDisappears(groupName string, memberName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).quicksightconn

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

awsAccountID, namespace, groupName, userName, err := resourceAwsQuickSightGroupMembershipParseID(rs.Primary.ID)
if err != nil {
return err
}

input := &quicksight.DeleteGroupMembershipInput{
AwsAccountId: aws.String(awsAccountID),
Namespace: aws.String(namespace),
MemberName: aws.String(userName),
GroupName: aws.String(groupName),
}

if _, err := conn.DeleteGroupMembership(input); err != nil {
return err
}
}
return nil
}
}
anGie44 marked this conversation as resolved.
Show resolved Hide resolved

func testAccAWSQuickSightGroupMembershipConfig(groupName string, memberName string) string {
return fmt.Sprintf(`
%s
%s
resource "aws_quicksight_group_membership" "default" {
group_name = aws_quicksight_group.default.group_name
member_name = aws_quicksight_user.%s.user_name
}
`, testAccAWSQuickSightGroupConfig(groupName), testAccAWSQuickSightUserConfig(memberName), memberName)
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
}
41 changes: 41 additions & 0 deletions website/docs/r/quicksight_group_membership.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
subcategory: "QuickSight"
layout: "aws"
page_title: "AWS: aws_quicksight_group_membership"
description: |-
Manages a Resource QuickSight Group Membership.
---

# Resource: aws_quicksight_group_membership

Resource for managing QuickSight Group Membership

## Example Usage

```terraform
resource "aws_quicksight_group_membership" "example" {
group_name = "all-access-users"
member_name = "john_smith"
}
```

## Argument Reference

The following arguments are supported:

* `group_name` - (Required) The name of the group in which the member will be added.
* `member_name` - (Required) The name of the member to add to the group.
* `aws_account_id` - (Optional) The ID for the AWS account that the group is in. Currently, you use the ID for the AWS account that contains your Amazon QuickSight account.
* `namespace` - (Optional) The namespace. Currently, you should set this to `default`.
anGie44 marked this conversation as resolved.
Show resolved Hide resolved

## Attributes Reference

All arguments above are exported.

## Import

QuickSight Group membership can be imported using the AWS account ID, namespace, group name and member name separated by `/`.

```
$ terraform import aws_quicksight_group.example 123456789123/default/all-access-users/john_smith
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
```