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 pagerduty_team_members data source #717

Merged
merged 4 commits into from
Dec 21, 2023
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
100 changes: 100 additions & 0 deletions pagerduty/data_source_pagerduty_team_members.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package pagerduty

import (
"context"
"log"
"net/http"
"strconv"
"time"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/heimweh/go-pagerduty/pagerduty"
)

func dataSourcePagerDutyTeamMembers() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourcePagerDutyTeamMembersRead,

Schema: map[string]*schema.Schema{
"team_id": {
Type: schema.TypeString,
Required: true,
Description: "The ID of the team to find via the PagerDuty API",
},
"members": {
Type: schema.TypeList,
Computed: true,
Description: "The set of team memberships associated with the team",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"summary": {
Type: schema.TypeString,
Computed: true,
},
"role": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}

func dataSourcePagerDutyTeamMembersRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client, err := meta.(*Config).Client()
if err != nil {
return diag.FromErr(err)
}

teamID := d.Get("team_id").(string)

log.Printf("[INFO] Reading PagerDuty team members of %s", teamID)

retryErr := resource.RetryContext(ctx, 5*time.Minute, func() *resource.RetryError {
resp, _, err := client.Teams.GetMembers(teamID, &pagerduty.GetMembersOptions{})
if err != nil {
if isErrCode(err, http.StatusBadRequest) {
return resource.NonRetryableError(err)
}

return resource.RetryableError(err)
}

var mems []map[string]interface{}
for _, member := range resp.Members {
mems = append(mems, map[string]interface{}{
"id": member.User.ID,
"type": member.User.Type,
"summary": member.User.Summary,
"role": member.Role,
})
}

// Since this data doesn't have an unique ID, this forces the data to be
// refreshed with each Terraform apply.
d.SetId(strconv.FormatInt(time.Now().Unix(), 10))

d.Set("members", mems)
d.Set("team_id", teamID)

return nil
})

if retryErr != nil {
return diag.FromErr(retryErr)
}

return nil
}
87 changes: 87 additions & 0 deletions pagerduty/data_source_pagerduty_team_members_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package pagerduty

import (
"fmt"
"testing"

"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 TestAccDataSourcePagerDutyTeamMembers_Basic(t *testing.T) {
teamName := fmt.Sprintf("tf-%s", acctest.RandString(5))
userName := fmt.Sprintf("tf-%s", acctest.RandString(5))
userEmail := fmt.Sprintf("%s@foo.test", userName)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourcePagerDutyTeamMembersConfig(teamName, userName, userEmail),
Check: resource.ComposeTestCheckFunc(
testAccDataSourcePagerDutyTeamMembers("pagerduty_team.test", "pagerduty_user.test", "data.pagerduty_team_members.test"),
resource.TestCheckResourceAttr("data.pagerduty_team_members.test", "members.#", "1"),
resource.TestCheckResourceAttr("data.pagerduty_team_members.test", "members.0.summary", userName),
resource.TestCheckResourceAttr("data.pagerduty_team_members.test", "members.0.role", "manager"),
resource.TestCheckResourceAttr("data.pagerduty_team_members.test", "members.0.type", "user_reference"),
),
},
},
})
}

func testAccDataSourcePagerDutyTeamMembers(teamResource, userResource, teamMembershipDataSource string) resource.TestCheckFunc {
return func(s *terraform.State) error {
userR := s.RootModule().Resources[userResource]
userRAs := userR.Primary.Attributes

teamR := s.RootModule().Resources[teamResource]
teamRAS := teamR.Primary.Attributes

teamMembershipDS := s.RootModule().Resources[teamMembershipDataSource]
as := teamMembershipDS.Primary.Attributes

if as["id"] == "" {
return fmt.Errorf("Expected team members ID not to be empty")
}

if as["team_id"] != teamRAS["id"] {
return fmt.Errorf("Expected team ID to be %s, but got %s", teamRAS["id"], as["team_id"])
}

if as["members.0.id"] != userRAs["id"] {
return fmt.Errorf("Expected team member ID to match user ID")
}

return nil
}
}

func testAccDataSourcePagerDutyTeamMembersConfig(teamName, userName, userEmail string) string {
return fmt.Sprintf(`
resource "pagerduty_team" "test" {
name = "%s"
description = "%s"
}

resource "pagerduty_user" "test" {
name = "%s"
email = "%s"
}

resource "pagerduty_team_membership" "test" {
user_id = pagerduty_user.test.id
team_id = pagerduty_team.test.id
}

data "pagerduty_team_members" "test" {
depends_on = [
pagerduty_team_membership.test,
]

team_id = pagerduty_team.test.id
}
`, teamName, teamName, userName, userEmail)
}
1 change: 1 addition & 0 deletions pagerduty/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ func Provider() *schema.Provider {
"pagerduty_automation_actions_action": dataSourcePagerDutyAutomationActionsAction(),
"pagerduty_incident_workflow": dataSourcePagerDutyIncidentWorkflow(),
"pagerduty_incident_custom_field": dataSourcePagerDutyIncidentCustomField(),
"pagerduty_team_members": dataSourcePagerDutyTeamMembers(),
},

ResourcesMap: map[string]*schema.Resource{
Expand Down
43 changes: 43 additions & 0 deletions website/docs/d/team_members.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
layout: "pagerduty"
page_title: "PagerDuty: pagerduty_team_members"
sidebar_current: "docs-pagerduty-datasource-team-members"
description: |-
Get information about a team's members..
---

# pagerduty\_team\_members

Use this data source to get information about a specific [team's members][1].

## Example Usage

```hcl
data "pagerduty_team" "devops" {
name = "devops"
}

data "pagerduty_team_members" "devops_members" {
team_id = data.pagerduty_team.devops.id
}
```

## Argument Reference

The following arguments are supported:

* `team_id` - (Required) The ID of the team to find in the PagerDuty API.

## Attributes Reference

* `id` - The ID of the found team.
* `members` - The users of the found team.

### Members (`members`) supports the following:

* `id` - The ID of the found user.
* `role` - The team role of the found user.
* `type` - The type of object. The value returned will be `user_reference`. Can be used for passing to another object as dependency.
* `summary` - A short-form, server-generated string that provides succinct, important information about an object suitable for primary labeling of an entity in a client. In many cases, this will be identical to name, though it is not intended to be an identifier.

[1]: https://developer.pagerduty.com/api-reference/e35802f3c4ba4-list-members-of-a-team
3 changes: 3 additions & 0 deletions website/pagerduty.erb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
<li<%= sidebar_current("docs-pagerduty-datasource-team") %>>
<a href="/docs/providers/pagerduty/d/team.html">pagerduty_team</a>
</li>
<li<%= sidebar_current("docs-pagerduty-datasource-team-members") %>>
<a href="/docs/providers/pagerduty/d/team_members.html">pagerduty_team_members</a>
</li>
<li<%= sidebar_current("docs-pagerduty-datasource-tag") %>>
<a href="/docs/providers/pagerduty/d/tag.html">pagerduty_tag</a>
</li>
Expand Down
Loading