Skip to content

Commit

Permalink
wip adding support for a2action team association
Browse files Browse the repository at this point in the history
  • Loading branch information
imjaroiswebdev committed Dec 14, 2022
1 parent ec4edbe commit 9cf9ed0
Show file tree
Hide file tree
Showing 5 changed files with 262 additions and 38 deletions.
61 changes: 31 additions & 30 deletions pagerduty/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,36 +65,37 @@ func Provider() *schema.Provider {
},

ResourcesMap: map[string]*schema.Resource{
"pagerduty_addon": resourcePagerDutyAddon(),
"pagerduty_escalation_policy": resourcePagerDutyEscalationPolicy(),
"pagerduty_maintenance_window": resourcePagerDutyMaintenanceWindow(),
"pagerduty_schedule": resourcePagerDutySchedule(),
"pagerduty_service": resourcePagerDutyService(),
"pagerduty_service_integration": resourcePagerDutyServiceIntegration(),
"pagerduty_team": resourcePagerDutyTeam(),
"pagerduty_team_membership": resourcePagerDutyTeamMembership(),
"pagerduty_user": resourcePagerDutyUser(),
"pagerduty_user_contact_method": resourcePagerDutyUserContactMethod(),
"pagerduty_user_notification_rule": resourcePagerDutyUserNotificationRule(),
"pagerduty_extension": resourcePagerDutyExtension(),
"pagerduty_extension_servicenow": resourcePagerDutyExtensionServiceNow(),
"pagerduty_event_rule": resourcePagerDutyEventRule(),
"pagerduty_ruleset": resourcePagerDutyRuleset(),
"pagerduty_ruleset_rule": resourcePagerDutyRulesetRule(),
"pagerduty_business_service": resourcePagerDutyBusinessService(),
"pagerduty_service_dependency": resourcePagerDutyServiceDependency(),
"pagerduty_response_play": resourcePagerDutyResponsePlay(),
"pagerduty_tag": resourcePagerDutyTag(),
"pagerduty_tag_assignment": resourcePagerDutyTagAssignment(),
"pagerduty_service_event_rule": resourcePagerDutyServiceEventRule(),
"pagerduty_slack_connection": resourcePagerDutySlackConnection(),
"pagerduty_business_service_subscriber": resourcePagerDutyBusinessServiceSubscriber(),
"pagerduty_webhook_subscription": resourcePagerDutyWebhookSubscription(),
"pagerduty_event_orchestration": resourcePagerDutyEventOrchestration(),
"pagerduty_event_orchestration_router": resourcePagerDutyEventOrchestrationPathRouter(),
"pagerduty_event_orchestration_unrouted": resourcePagerDutyEventOrchestrationPathUnrouted(),
"pagerduty_event_orchestration_service": resourcePagerDutyEventOrchestrationPathService(),
"pagerduty_automation_actions_runner": resourcePagerDutyAutomationActionsRunner(),
"pagerduty_addon": resourcePagerDutyAddon(),
"pagerduty_escalation_policy": resourcePagerDutyEscalationPolicy(),
"pagerduty_maintenance_window": resourcePagerDutyMaintenanceWindow(),
"pagerduty_schedule": resourcePagerDutySchedule(),
"pagerduty_service": resourcePagerDutyService(),
"pagerduty_service_integration": resourcePagerDutyServiceIntegration(),
"pagerduty_team": resourcePagerDutyTeam(),
"pagerduty_team_membership": resourcePagerDutyTeamMembership(),
"pagerduty_user": resourcePagerDutyUser(),
"pagerduty_user_contact_method": resourcePagerDutyUserContactMethod(),
"pagerduty_user_notification_rule": resourcePagerDutyUserNotificationRule(),
"pagerduty_extension": resourcePagerDutyExtension(),
"pagerduty_extension_servicenow": resourcePagerDutyExtensionServiceNow(),
"pagerduty_event_rule": resourcePagerDutyEventRule(),
"pagerduty_ruleset": resourcePagerDutyRuleset(),
"pagerduty_ruleset_rule": resourcePagerDutyRulesetRule(),
"pagerduty_business_service": resourcePagerDutyBusinessService(),
"pagerduty_service_dependency": resourcePagerDutyServiceDependency(),
"pagerduty_response_play": resourcePagerDutyResponsePlay(),
"pagerduty_tag": resourcePagerDutyTag(),
"pagerduty_tag_assignment": resourcePagerDutyTagAssignment(),
"pagerduty_service_event_rule": resourcePagerDutyServiceEventRule(),
"pagerduty_slack_connection": resourcePagerDutySlackConnection(),
"pagerduty_business_service_subscriber": resourcePagerDutyBusinessServiceSubscriber(),
"pagerduty_webhook_subscription": resourcePagerDutyWebhookSubscription(),
"pagerduty_event_orchestration": resourcePagerDutyEventOrchestration(),
"pagerduty_event_orchestration_router": resourcePagerDutyEventOrchestrationPathRouter(),
"pagerduty_event_orchestration_unrouted": resourcePagerDutyEventOrchestrationPathUnrouted(),
"pagerduty_event_orchestration_service": resourcePagerDutyEventOrchestrationPathService(),
"pagerduty_automation_actions_runner": resourcePagerDutyAutomationActionsRunner(),
"pagerduty_automation_actions_action_team_association": resourcePagerDutyAutomationActionsActionTeamAssociation(),
},
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package pagerduty

import (
"fmt"
"log"
"time"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func resourcePagerDutyAutomationActionsActionTeamAssociation() *schema.Resource {
return &schema.Resource{
Create: resourcePagerDutyAutomationActionsActionTeamAssociationCreate,
Read: resourcePagerDutyAutomationActionsActionTeamAssociationRead,
Delete: resourcePagerDutyAutomationActionsActionTeamAssociationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"action_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"team_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}

func resourcePagerDutyAutomationActionsActionTeamAssociationCreate(d *schema.ResourceData, meta interface{}) error {
client, err := meta.(*Config).Client()
if err != nil {
return err
}

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

log.Printf("[INFO] Creating PagerDuty AutomationActionsActionTeamAssociation %s:%s", d.Get("actionID").(string), d.Get("team_id").(string))

retryErr := resource.Retry(10*time.Second, func() *resource.RetryError {
if teamRef, _, err := client.AutomationActionsAction.AssociateToTeam(actionID, teamID); err != nil {
if isErrCode(err, 429) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}

return resource.NonRetryableError(err)
} else if teamRef != nil {
d.SetId(fmt.Sprintf("%s:%s", actionID, teamID))
}
return nil
})

if retryErr != nil {
return retryErr
}

return fetchPagerDutyAutomationActionsActionTeamAssociation(d, meta, handleNotFoundError)
}

func fetchPagerDutyAutomationActionsActionTeamAssociation(d *schema.ResourceData, meta interface{}, errCallback func(error, *schema.ResourceData) error) error {
client, err := meta.(*Config).Client()
if err != nil {
return err
}

actionID, teamID := resourcePagerDutyParseColonCompoundID(d.Id())
log.Printf("[DEBUG] Reading a2 action: %s from team: %s", actionID, teamID)
return resource.Retry(30*time.Second, func() *resource.RetryError {
teamRef, _, err := client.AutomationActionsAction.GetAssociationToTeam(actionID, teamID)
if err != nil {
errResp := errCallback(err, d)
if errResp != nil {
time.Sleep(2 * time.Second)
return resource.RetryableError(errResp)
}

return nil
}

if teamRef.ID != teamID {
log.Printf("[WARN] Removing %s since the user: %s is not a member of: %s", d.Id(), actionID, teamID)
d.SetId("")
return nil
}

d.Set("action_id", actionID)
d.Set("team_id", teamRef.ID)

return nil
})
}

func resourcePagerDutyAutomationActionsActionTeamAssociationRead(d *schema.ResourceData, meta interface{}) error {
return fetchPagerDutyAutomationActionsActionTeamAssociation(d, meta, handleNotFoundError)
}

func resourcePagerDutyAutomationActionsActionTeamAssociationDelete(d *schema.ResourceData, meta interface{}) error {
client, err := meta.(*Config).Client()
if err != nil {
return err
}

actionID, teamID := resourcePagerDutyParseColonCompoundID(d.Id())
log.Printf("[INFO] Deleting PagerDuty AutomationActionsActionTeamAssociation %s", d.Id())

retryErr := resource.Retry(2*time.Minute, func() *resource.RetryError {
if _, err := client.AutomationActionsAction.DissociateToTeam(actionID, teamID); err != nil {
return resource.RetryableError(err)
}
return nil
})
if retryErr != nil {
time.Sleep(2 * time.Second)
return retryErr
}
d.SetId("")

// giving the API time to catchup
time.Sleep(time.Second)
return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
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 init() {
resource.AddTestSweepers("pagerduty_automation_actions_action_team_association", &resource.Sweeper{
Name: "pagerduty_automation_actions_action_team_association",
F: testSweepAutomationActionsActionTeamAssociation,
})
}

func testSweepAutomationActionsActionTeamAssociation(region string) error {
return nil
}

func TestAccPagerDutyAutomationActionsActionTeamAssociation_Basic(t *testing.T) {
teamName := fmt.Sprintf("tf-%s", acctest.RandString(5))

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckPagerDutyAutomationActionsActionTeamAssociationDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckPagerDutyAutomationActionsActionTeamAssociationConfig(teamName),
Check: resource.ComposeTestCheckFunc(
testAccCheckPagerDutyAutomationActionsActionTeamAssociationExists("pagerduty_automation_actions_action_team_association.foo"),
resource.TestCheckResourceAttrSet("pagerduty_automation_actions_action_team_association.foo", "action_id"),
resource.TestCheckResourceAttrSet("pagerduty_automation_actions_action_team_association.foo", "team_id"),
),
},
},
})
}

func testAccCheckPagerDutyAutomationActionsActionTeamAssociationDestroy(s *terraform.State) error {
client, _ := testAccProvider.Meta().(*Config).Client()
for _, r := range s.RootModule().Resources {
if r.Type != "pagerduty_automation_actions_action_team_association" {
continue
}
actionID, teamID := resourcePagerDutyParseColonCompoundID(r.Primary.ID)
if _, _, err := client.AutomationActionsAction.GetAssociationToTeam(actionID, teamID); err == nil {
return fmt.Errorf("Automation Actions Runner still exists")
}
}
return nil
}

func testAccCheckPagerDutyAutomationActionsActionTeamAssociationExists(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No Automation Actions Runner ID is set")
}

client, _ := testAccProvider.Meta().(*Config).Client()
actionID, teamID := resourcePagerDutyParseColonCompoundID(rs.Primary.ID)
found, _, err := client.AutomationActionsAction.GetAssociationToTeam(actionID, teamID)
if err != nil {
return err
}
if found.ID != rs.Primary.ID {
return fmt.Errorf("Automation Actions Action association to team not found: %v - %v", rs.Primary.ID, found)
}

return nil
}
}

func testAccCheckPagerDutyAutomationActionsActionTeamAssociationConfig(teamName string) string {
return fmt.Sprintf(`
resource "pagerduty_team" "foo" {
name = "%s"
description = "foo"
}
# expecting action resource to be here
resource "pagerduty_automation_actions_action_team_association" "foo" {
action_id = "action_id_will_be_here"
team_id = pagerduty_team.foo.id
}
`, teamName)
}
10 changes: 2 additions & 8 deletions pagerduty/resource_pagerduty_team_membership.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package pagerduty
import (
"fmt"
"log"
"strings"
"time"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
Expand Down Expand Up @@ -51,7 +50,7 @@ func fetchPagerDutyTeamMembership(d *schema.ResourceData, meta interface{}, errC
return err
}

userID, teamID := resourcePagerDutyTeamMembershipParseID(d.Id())
userID, teamID := resourcePagerDutyParseColonCompoundID(d.Id())
log.Printf("[DEBUG] Reading user: %s from team: %s", userID, teamID)
return resource.Retry(2*time.Minute, func() *resource.RetryError {
resp, _, err := client.Teams.GetMembers(teamID, &pagerduty.GetMembersOptions{})
Expand Down Expand Up @@ -156,7 +155,7 @@ func resourcePagerDutyTeamMembershipDelete(d *schema.ResourceData, meta interfac
return err
}

userID, teamID := resourcePagerDutyTeamMembershipParseID(d.Id())
userID, teamID := resourcePagerDutyParseColonCompoundID(d.Id())

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

Expand Down Expand Up @@ -275,11 +274,6 @@ func associateEPsBackToTeam(c *pagerduty.Client, teamID string, eps []string) er
return nil
}

func resourcePagerDutyTeamMembershipParseID(id string) (string, string) {
parts := strings.Split(id, ":")
return parts[0], parts[1]
}

func isTeamMember(user *pagerduty.User, teamID string) bool {
var found bool

Expand Down
5 changes: 5 additions & 0 deletions pagerduty/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,8 @@ func unique(s []string) []string {
}
return result
}

func resourcePagerDutyParseColonCompoundID(id string) (string, string) {
parts := strings.Split(id, ":")
return parts[0], parts[1]
}

0 comments on commit 9cf9ed0

Please sign in to comment.