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

resource/pagerduty_team_membership: Support team member's role #151

Merged
merged 14 commits into from
Mar 19, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/terraform-providers/terraform-provider-pagerduty
require (
github.com/google/go-querystring v1.0.0 // indirect
github.com/hashicorp/terraform-plugin-sdk v1.0.0
github.com/heimweh/go-pagerduty v0.0.0-20190807171021-2a6540956dc5
github.com/heimweh/go-pagerduty v0.0.0-20190903123207-5a16d0d0290f
)

go 1.13
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d h1:kJCB4vdITiW1eC1
github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM=
github.com/heimweh/go-pagerduty v0.0.0-20190807171021-2a6540956dc5 h1:UZQ03lpxS/AUrMTlh1yQ/MJEJ+2he5bCItZ4W9Lgs1c=
github.com/heimweh/go-pagerduty v0.0.0-20190807171021-2a6540956dc5/go.mod h1:6+bccpjQ/PM8uQY9m8avM4MJea+3vo3ta9r8kGQ4XFY=
github.com/heimweh/go-pagerduty v0.0.0-20190903123207-5a16d0d0290f h1:KxRmqNpunRKzTdjqdM5IG5v38NGWCpQjZ/vGULImZjQ=
github.com/heimweh/go-pagerduty v0.0.0-20190903123207-5a16d0d0290f/go.mod h1:6+bccpjQ/PM8uQY9m8avM4MJea+3vo3ta9r8kGQ4XFY=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
Expand Down
23 changes: 23 additions & 0 deletions pagerduty/import_pagerduty_team_membership_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,26 @@ func TestAccPagerDutyTeamMembership_import(t *testing.T) {
},
})
}

func TestAccPagerDutyTeamMembership_importWithRole(t *testing.T) {
user := fmt.Sprintf("tf-%s", acctest.RandString(5))
team := fmt.Sprintf("tf-%s", acctest.RandString(5))
role := "manager"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the original test should probably be left untouched to ensure no regression is introduced.

Maybe a new TestAccPagerDutyTeamMembership_importWithRole test should be introduced.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. Created a new testcase for withRole.
hashicorp@6ce1d0c


resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckPagerDutyTeamMembershipDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckPagerDutyTeamMembershipWithRoleConfig(user, team, role),
},

{
ResourceName: "pagerduty_team_membership.foo",
ImportState: true,
ImportStateVerify: true,
},
},
})
}
63 changes: 55 additions & 8 deletions pagerduty/resource_pagerduty_team_membership.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ func resourcePagerDutyTeamMembership() *schema.Resource {
return &schema.Resource{
Create: resourcePagerDutyTeamMembershipCreate,
Read: resourcePagerDutyTeamMembershipRead,
Update: resourcePagerDutyTeamMembershipUpdate,
Delete: resourcePagerDutyTeamMembershipDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
Expand All @@ -30,6 +31,16 @@ func resourcePagerDutyTeamMembership() *schema.Resource {
Required: true,
ForceNew: true,
},
"role": {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validation could probably be added:

The role of the user on the team.
Can be observer, responder or manager

https://api-reference.pagerduty.com/#!/Teams/put_teams_id_users_user_id

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Type: schema.TypeString,
Optional: true,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I remember there are issues when Optional and Computed are used together, not sure if it applies here.
This probably needs more attention.

hashicorp/terraform-provider-google#3477 (comment)
hashicorp/terraform#20505 (comment)
hashicorp/terraform-provider-google#4326

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed to Optional only, as developers can set value by themselves or use the default value.
hashicorp@003ba6c

Default: "manager",
ValidateFunc: validateValueFunc([]string{
"observer",
"responder",
"manager",
}),
},
},
}
}
Expand All @@ -38,11 +49,12 @@ func resourcePagerDutyTeamMembershipCreate(d *schema.ResourceData, meta interfac

userID := d.Get("user_id").(string)
teamID := d.Get("team_id").(string)
role := d.Get("role").(string)

log.Printf("[DEBUG] Adding user: %s to team: %s", userID, teamID)
log.Printf("[DEBUG] Adding user: %s to team: %s with role: %s", userID, teamID, role)

retryErr := resource.Retry(2*time.Minute, func() *resource.RetryError {
if _, err := client.Teams.AddUser(teamID, userID); err != nil {
if _, err := client.Teams.AddUserWithRole(teamID, userID, role); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if the role is empty? Shouldn't client.Teams.AddUser(teamID, userID) be used instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I defined a default value for role to be the same as the current API behavior, calling AddUser API without role.
hashicorp@a560e09

With validation implemented at hashicorp@8521226, this resource guarantees a valid value is set in role at every time. So I think it's okay to use AddUserWithRole at every time too.

if isErrCode(err, 500) {
return resource.RetryableError(err)
}
Expand All @@ -68,18 +80,53 @@ func resourcePagerDutyTeamMembershipRead(d *schema.ResourceData, meta interface{

log.Printf("[DEBUG] Reading user: %s from team: %s", userID, teamID)

user, _, err := client.Users.Get(userID, &pagerduty.GetUserOptions{})
resp, _, err := client.Teams.GetMembers(teamID, &pagerduty.GetMembersOptions{})
if err != nil {
return handleNotFoundError(err, d)
}

if !isTeamMember(user, teamID) {
log.Printf("[WARN] Removing %s since the user: %s is not a member of: %s", d.Id(), userID, teamID)
d.SetId("")
for _, member := range resp.Members {
if member.User.ID == userID {
d.Set("user_id", userID)
d.Set("team_id", teamID)
d.Set("role", member.Role)

return nil
}
}

log.Printf("[WARN] Removing %s since the user: %s is not a member of: %s", d.Id(), userID, teamID)
d.SetId("")

return nil
}

func resourcePagerDutyTeamMembershipUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*pagerduty.Client)

userID := d.Get("user_id").(string)
teamID := d.Get("team_id").(string)
role := d.Get("role").(string)

log.Printf("[DEBUG] Updating user: %s to team: %s with role: %s", userID, teamID, role)

// To update existing membership resource, We can use the same API as creating a new membership.
retryErr := resource.Retry(2*time.Minute, func() *resource.RetryError {
if _, err := client.Teams.AddUserWithRole(teamID, userID, role); err != nil {
if isErrCode(err, 500) {
return resource.RetryableError(err)
}

return resource.NonRetryableError(err)
}

return nil
})
if retryErr != nil {
return retryErr
}

d.Set("user_id", userID)
d.Set("team_id", teamID)
d.SetId(fmt.Sprintf("%s:%s", userID, teamID))

return nil
}
Expand Down
54 changes: 54 additions & 0 deletions pagerduty/resource_pagerduty_team_membership_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,26 @@ func TestAccPagerDutyTeamMembership_Basic(t *testing.T) {
})
}

func TestAccPagerDutyTeamMembership_WithRole(t *testing.T) {
user := fmt.Sprintf("tf-%s", acctest.RandString(5))
team := fmt.Sprintf("tf-%s", acctest.RandString(5))
role := "manager"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the original test should probably be left untouched to ensure no regression is introduced.

Maybe a new TestAccPagerDutyTeamMembership_WithRole test should be introduced.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. Created a new testcase for withRole.
hashicorp@89b0e5f


resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckPagerDutyTeamMembershipDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckPagerDutyTeamMembershipWithRoleConfig(user, team, role),
Check: resource.ComposeTestCheckFunc(
testAccCheckPagerDutyTeamMembershipExists("pagerduty_team_membership.foo"),
),
},
},
})
}

func testAccCheckPagerDutyTeamMembershipDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*pagerduty.Client)
for _, r := range s.RootModule().Resources {
Expand Down Expand Up @@ -62,6 +82,7 @@ func testAccCheckPagerDutyTeamMembershipExists(n string) resource.TestCheckFunc

userID := rs.Primary.Attributes["user_id"]
teamID := rs.Primary.Attributes["team_id"]
role := rs.Primary.Attributes["role"]

user, _, err := client.Users.Get(userID, &pagerduty.GetUserOptions{})
if err != nil {
Expand All @@ -72,6 +93,19 @@ func testAccCheckPagerDutyTeamMembershipExists(n string) resource.TestCheckFunc
return fmt.Errorf("%s is not a member of: %s", userID, teamID)
}

resp, _, err := client.Teams.GetMembers(teamID, &pagerduty.GetMembersOptions{})
if err != nil {
return err
}

for _, member := range resp.Members {
if member.User.ID == userID {
if member.Role != role {
return fmt.Errorf("%s does not have the role: %s in: %s", userID, role, teamID)
}
}
}

return nil
}
}
Expand All @@ -94,3 +128,23 @@ resource "pagerduty_team_membership" "foo" {
}
`, user, team)
}

func testAccCheckPagerDutyTeamMembershipWithRoleConfig(user, team, role string) string {
return fmt.Sprintf(`
resource "pagerduty_user" "foo" {
name = "%[1]v"
email = "%[1]v@foo.com"
}

resource "pagerduty_team" "foo" {
name = "%[2]v"
description = "foo"
}

resource "pagerduty_team_membership" "foo" {
user_id = "${pagerduty_user.foo.id}"
team_id = "${pagerduty_team.foo.id}"
role = "%[3]v"
}
`, user, team, role)
}
48 changes: 48 additions & 0 deletions vendor/github.com/heimweh/go-pagerduty/pagerduty/team.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion vendor/modules.txt
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ github.com/hashicorp/terraform-plugin-sdk/plugin
github.com/hashicorp/terraform-plugin-sdk/terraform
# github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d
github.com/hashicorp/yamux
# github.com/heimweh/go-pagerduty v0.0.0-20190807171021-2a6540956dc5
# github.com/heimweh/go-pagerduty v0.0.0-20190903123207-5a16d0d0290f
github.com/heimweh/go-pagerduty/pagerduty
# github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af
github.com/jmespath/go-jmespath
Expand Down
3 changes: 3 additions & 0 deletions website/docs/r/team_membership.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ resource "pagerduty_team" "foo" {
resource "pagerduty_team_membership" "foo" {
user_id = "${pagerduty_user.foo.id}"
team_id = "${pagerduty_team.foo.id}"
role = "manager"
}
```

Expand All @@ -35,13 +36,15 @@ The following arguments are supported:

* `user_id` - (Required) The ID of the user to add to the team.
* `team_id` - (Required) The ID of the team in which the user will belong.
* `role` - (Optional) The role of the user in the team. One of `observer`, `responder`, or `manager`. Defaults to `observer`.

## Attributes Reference

The following attributes are exported:

* `user_id` - The ID of the user belonging to the team.
* `team_id` - The team ID the user belongs to.
* `role` - The role of the user in the team.


## Import
Expand Down