-
Notifications
You must be signed in to change notification settings - Fork 138
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 new resource opsgenie_team_membership, refs #65 #167
Open
arnisoph
wants to merge
1
commit into
opsgenie:master
Choose a base branch
from
arnisoph:team_membership-resource2
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
package opsgenie | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"github.com/hashicorp/terraform-plugin-sdk/helper/schema" | ||
"github.com/opsgenie/opsgenie-go-sdk-v2/team" | ||
"log" | ||
"strings" | ||
) | ||
|
||
func resourceOpsGenieTeamMembership() *schema.Resource { //TODO encode the e-mail addrs (e.g. because of +)? https://github.com/opsgenie/opsgenie-go-sdk-v2/issues/62 | ||
return &schema.Resource{ | ||
Create: resourceOpsGenieTeamMembershipCreate, | ||
Read: handleNonExistentResource(resourceOpsGenieTeamMembershipRead), | ||
//Update: resourceOpsGenieTeamMembershipUpdate, // requires https://github.com/opsgenie/opsgenie-go-sdk-v2/issues/59 | ||
Delete: resourceOpsGenieTeamMembershipDelete, | ||
Importer: &schema.ResourceImporter{ | ||
State: schema.ImportStatePassthrough, | ||
}, | ||
Schema: map[string]*schema.Schema{ | ||
"user_id": { | ||
Type: schema.TypeString, | ||
Required: true, | ||
ForceNew: true, | ||
}, | ||
"role": { | ||
Type: schema.TypeString, | ||
Optional: true, | ||
Default: "user", | ||
ForceNew: true, | ||
}, | ||
"team_id": { | ||
Type: schema.TypeString, | ||
Required: true, | ||
ForceNew: true, | ||
}, | ||
}, | ||
} | ||
} | ||
|
||
func resourceOpsGenieTeamMembershipCreate(d *schema.ResourceData, meta interface{}) error { | ||
|
||
userID := d.Get("user_id").(string) | ||
role := d.Get("role").(string) | ||
teamID := d.Get("team_id").(string) | ||
|
||
log.Printf("[INFO] Adding user %q to team %q", teamID, userID) | ||
|
||
client, err := team.NewClient(meta.(*OpsgenieClient).client.Config) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
// add member to team | ||
_, err = client.AddMember(context.Background(), &team.AddTeamMemberRequest{ | ||
TeamIdentifierType: team.Id, | ||
TeamIdentifierValue: teamID, | ||
User: team.User{ | ||
ID: userID, | ||
}, | ||
Role: role, | ||
}) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
d.SetId(buildTwoPartID(teamID, userID)) | ||
|
||
return resourceOpsGenieTeamMembershipRead(d, meta) | ||
} | ||
|
||
func resourceOpsGenieTeamMembershipRead(d *schema.ResourceData, meta interface{}) error { | ||
|
||
teamID, userID, err := parseTwoPartID(d.Id(), "teamID", "userID") | ||
if err != nil { | ||
return err | ||
} | ||
|
||
getRequest := &team.GetTeamRequest{ | ||
IdentifierType: team.Id, | ||
IdentifierValue: teamID, | ||
} | ||
|
||
log.Printf("[INFO] Retrieving membership of user %q in team %q", userID, teamID) | ||
|
||
client, err := team.NewClient(meta.(*OpsgenieClient).client.Config) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
getResponse, err := client.Get(context.Background(), getRequest) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
role, err := getUserRole(userID, teamID, getResponse.Members) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
d.Set("user_id", userID) | ||
d.Set("role", role) | ||
d.Set("team_id", teamID) | ||
|
||
return nil | ||
} | ||
|
||
func resourceOpsGenieTeamMembershipDelete(d *schema.ResourceData, meta interface{}) error { | ||
userID := d.Get("user_id").(string) | ||
teamID := d.Get("team_id").(string) | ||
|
||
log.Printf("[INFO] Deleting membership of user %q in team %q", userID, teamID) | ||
|
||
client, err := team.NewClient(meta.(*OpsgenieClient).client.Config) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
_, err = client.RemoveMember(context.Background(), &team.RemoveTeamMemberRequest{ | ||
TeamIdentifierType: team.Id, | ||
TeamIdentifierValue: teamID, | ||
MemberIdentifierType: team.Id, | ||
MemberIdentifierValue: userID, | ||
}) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func getUserRole(userID string, teamID string, input []team.Member) (string, error) { | ||
role := "" | ||
|
||
for _, inputMember := range input { | ||
if inputMember.User.ID == userID { | ||
role = inputMember.Role | ||
return role, nil | ||
} | ||
} | ||
|
||
return "", fmt.Errorf("did not found user %q in team %q (%#v)", userID, teamID, input) | ||
} | ||
|
||
// format the strings into an id `a:b` | ||
func buildTwoPartID(a, b string) string { | ||
return fmt.Sprintf("%s:%s", a, b) | ||
} | ||
|
||
// return the pieces of id `left:right` as left, right | ||
func parseTwoPartID(id, left, right string) (string, string, error) { | ||
parts := strings.SplitN(id, ":", 2) | ||
if len(parts) != 2 { | ||
return "", "", fmt.Errorf("unexpected ID format %q, expected %s:%s", id, left, right) | ||
} | ||
|
||
return parts[0], parts[1], nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,194 @@ | ||
package opsgenie | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"github.com/hashicorp/terraform-plugin-sdk/terraform" | ||
"github.com/opsgenie/opsgenie-go-sdk-v2/team" | ||
"testing" | ||
|
||
"github.com/hashicorp/terraform-plugin-sdk/helper/acctest" | ||
"github.com/hashicorp/terraform-plugin-sdk/helper/resource" | ||
) | ||
|
||
func TestAccOpsGenieTeamMembership_basic(t *testing.T) { | ||
rString := acctest.RandString(6) | ||
|
||
resource.Test(t, resource.TestCase{ | ||
Providers: testAccProviders, | ||
|
||
Steps: []resource.TestStep{ | ||
{ | ||
Config: testAccOpsGenieTeamMembership_basic(rString), | ||
Destroy: false, | ||
Check: resource.ComposeTestCheckFunc( | ||
testCheckOpsGenieTeamExists("opsgenie_team.monkeys"), | ||
testCheckOpsGenieUserExists("opsgenie_user.kong"), | ||
testCheckOpsGenieTeamMembershipExists("opsgenie_team_membership.chaos_kong", "opsgenie_team.monkeys", "opsgenie_user.kong"), | ||
), | ||
}, | ||
{ | ||
Config: testAccOpsGenieTeamMembership_basicUpdated(rString), | ||
Check: resource.ComposeTestCheckFunc( | ||
testCheckOpsGenieTeamExists("opsgenie_team.monkeys"), | ||
testCheckOpsGenieUserExists("opsgenie_user.kong"), | ||
testCheckOpsGenieTeamMembershipExists("opsgenie_team_membership.chaos_kong", "opsgenie_team.monkeys", "opsgenie_user.kong"), | ||
), | ||
}, | ||
{ | ||
Config: testAccOpsGenieTeamMembership_basicWithoutMembership(rString), | ||
Check: resource.ComposeTestCheckFunc( | ||
testCheckOpsGenieTeamExists("opsgenie_team.monkeys"), | ||
testCheckOpsGenieUserExists("opsgenie_user.kong"), | ||
testCheckOpsGenieTeamMembershipRemoved("opsgenie_team_membership.chaos_kong", "opsgenie_team.monkeys", "opsgenie_user.kong"), | ||
), | ||
}, | ||
}, | ||
}) | ||
} | ||
|
||
func testCheckOpsGenieTeamMembershipExists(membershipResource string, teamResource string, userResource string) resource.TestCheckFunc { | ||
return func(s *terraform.State) error { | ||
|
||
rsMembership, ok := s.RootModule().Resources[membershipResource] | ||
if !ok { | ||
return fmt.Errorf("not found: %s", membershipResource) | ||
} | ||
|
||
rsTeam, ok := s.RootModule().Resources[teamResource] | ||
if !ok { | ||
return fmt.Errorf("not found: %s", teamResource) | ||
} | ||
teamName := rsTeam.Primary.Attributes["name"] | ||
|
||
rsUser, ok := s.RootModule().Resources[userResource] | ||
if !ok { | ||
return fmt.Errorf("not found: %s", userResource) | ||
} | ||
userName := rsUser.Primary.Attributes["username"] | ||
|
||
client, err := team.NewClient(testAccProvider.Meta().(*OpsgenieClient).client.Config) | ||
if err != nil { | ||
return err | ||
} | ||
req := team.GetTeamRequest{ | ||
IdentifierType: team.Name, | ||
IdentifierValue: teamName, | ||
} | ||
getResponse, err := client.Get(context.Background(), &req) | ||
if err != nil { | ||
return fmt.Errorf("failed to detect team membership for user %q in team %q: %s", userName, teamName, err) | ||
} | ||
|
||
// compare what we've actually done | ||
if len(getResponse.Members) != 1 { | ||
return fmt.Errorf("there's no team membership at all. something went wrong :(") | ||
} | ||
|
||
if getResponse.Members[0].User.Username != userName { | ||
return fmt.Errorf("expected userName in team membership (%q) doesn't match actual username (%q)", userName, getResponse.Members[0].User.Username) | ||
} | ||
|
||
if getResponse.Members[0].User.ID != rsUser.Primary.ID { | ||
return fmt.Errorf("expected user ID in team membership (%q) doesn't match actual username (%q)", rsUser.Primary.ID, getResponse.Members[0].User.ID) | ||
} | ||
|
||
if getResponse.Members[0].Role != rsMembership.Primary.Attributes["role"] { | ||
return fmt.Errorf("expected user role in team membership (%q) doesn't match actual user role (%q)", rsMembership.Primary.Attributes["role"], getResponse.Members[0].Role) | ||
} | ||
|
||
return nil | ||
} | ||
} | ||
|
||
func testCheckOpsGenieTeamMembershipRemoved(membershipResource string, teamResource string, userResource string) resource.TestCheckFunc { | ||
return func(s *terraform.State) error { | ||
|
||
_, ok := s.RootModule().Resources[membershipResource] | ||
if ok { | ||
return fmt.Errorf("resource %s still in state. this is bad", membershipResource) | ||
} | ||
|
||
rsTeam, ok := s.RootModule().Resources[teamResource] | ||
if !ok { | ||
return fmt.Errorf("not found: %s", teamResource) | ||
} | ||
teamName := rsTeam.Primary.Attributes["name"] | ||
|
||
client, err := team.NewClient(testAccProvider.Meta().(*OpsgenieClient).client.Config) | ||
if err != nil { | ||
return err | ||
} | ||
req := team.GetTeamRequest{ | ||
IdentifierType: team.Name, | ||
IdentifierValue: teamName, | ||
} | ||
getResponse, err := client.Get(context.Background(), &req) | ||
if err != nil { | ||
return fmt.Errorf("failed to verify team memberships of team %q: %s", teamName, err) | ||
} | ||
|
||
// compare what we've actually done | ||
if len(getResponse.Members) != 0 { | ||
return fmt.Errorf("there is still an unexpected number of team membership(s) (%#v). something went wrong :(", getResponse.Members) | ||
} | ||
|
||
return nil | ||
} | ||
} | ||
|
||
func testAccOpsGenieTeamMembership_basic(rString string) string { | ||
return fmt.Sprintf(` | ||
resource "opsgenie_team" "monkeys" { | ||
name = "monkeys-%s" | ||
description = "They exist." | ||
ignore_members = true | ||
} | ||
resource "opsgenie_user" "kong" { | ||
username = "kong-%[email protected]" | ||
full_name = "Chaos Kong" | ||
role = "User" | ||
} | ||
resource "opsgenie_team_membership" "chaos_kong" { | ||
username = opsgenie_user.kong.username | ||
role = "user" | ||
team = opsgenie_team.monkeys.name | ||
} | ||
`, rString, rString) | ||
} | ||
|
||
func testAccOpsGenieTeamMembership_basicUpdated(rString string) string { | ||
return fmt.Sprintf(` | ||
resource "opsgenie_team" "monkeys" { | ||
name = "monkeys-%s" | ||
description = "They exist." | ||
ignore_members = true | ||
} | ||
resource "opsgenie_user" "kong" { | ||
username = "kong-%[email protected]" | ||
full_name = "Chaos Kong" | ||
role = "User" | ||
} | ||
resource "opsgenie_team_membership" "chaos_kong" { | ||
username = opsgenie_user.kong.username | ||
role = "admin" | ||
team = opsgenie_team.monkeys.name | ||
} | ||
`, rString, rString) | ||
} | ||
|
||
func testAccOpsGenieTeamMembership_basicWithoutMembership(rString string) string { | ||
return fmt.Sprintf(` | ||
resource "opsgenie_team" "monkeys" { | ||
name = "monkeys-%s" | ||
description = "They exist." | ||
ignore_members = true | ||
depends_on = [opsgenie_user.kong] # Just a hack for the test to destroy resources in the right order | ||
} | ||
resource "opsgenie_user" "kong" { | ||
username = "kong-%[email protected]" | ||
full_name = "Chaos Kong" | ||
role = "User" | ||
} | ||
`, rString, rString) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pr looks good i'll talk with the internal team about go-sdk-v2 membership update status
Thank you @arnisoph
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we don't have update support. if we introduce this users cannot change roles in their teams. I'll create a internal ticket and let you know.
maybe we can use update function to
-> get team -> update our user role -> update team flow
This way we can update our team members ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't even plan to implement it, it's just a comment :D