Skip to content

Commit

Permalink
feat(user_management): addition of a resource to manage users (#2575)
Browse files Browse the repository at this point in the history
  • Loading branch information
pranav-new-relic authored Feb 15, 2024
1 parent 42026bf commit 26c5b49
Show file tree
Hide file tree
Showing 11 changed files with 660 additions and 9 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ require (
github.com/mitchellh/go-homedir v1.1.0
github.com/newrelic/go-agent/v3 v3.29.1
github.com/newrelic/go-insights v1.0.3
github.com/newrelic/newrelic-client-go/v2 v2.24.0
github.com/newrelic/newrelic-client-go/v2 v2.25.0
github.com/stretchr/testify v1.8.4
golang.org/x/exp v0.0.0-20240119083558-1b970713d09a
)
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,8 @@ github.com/newrelic/go-agent/v3 v3.29.1 h1:OINNRev5ImiyRq0IUYwhfTmtqQgQFYyDNQEtb
github.com/newrelic/go-agent/v3 v3.29.1/go.mod h1:9utrgxlSryNqRrTvII2XBL+0lpofXbqXApvVWPpbzUg=
github.com/newrelic/go-insights v1.0.3 h1:zSNp1CEZnXktzSIEsbHJk8v6ZihdPFP2WsO/fzau3OQ=
github.com/newrelic/go-insights v1.0.3/go.mod h1:A20BoT8TNkqPGX2nS/Z2fYmKl3Cqa3iKZd4whzedCY4=
github.com/newrelic/newrelic-client-go/v2 v2.24.0 h1:L4T0+wQ0P+GvxsbkNGMUW9umpBaQ2BjaTD98eyDeBCY=
github.com/newrelic/newrelic-client-go/v2 v2.24.0/go.mod h1:SO5KJuFJ/+l3lT8nOdNLTrcE9FoZ4m60kechCVb+1N4=
github.com/newrelic/newrelic-client-go/v2 v2.25.0 h1:epPYpgyN8+BliSGRosgBiEm8x84ZamApESHlWoJYllM=
github.com/newrelic/newrelic-client-go/v2 v2.25.0/go.mod h1:SO5KJuFJ/+l3lT8nOdNLTrcE9FoZ4m60kechCVb+1N4=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw=
github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA=
Expand Down
8 changes: 4 additions & 4 deletions newrelic/data_source_newrelic_authentication_domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@ func dataSourceNewRelicAuthenticationDomainRead(ctx context.Context, d *schema.R

resp, err := client.UserManagement.GetAuthenticationDomainsWithContext(ctx, "", []string{})

if resp == nil {
return diag.FromErr(fmt.Errorf("failed to fetch authentication domains"))
}

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

if resp == nil {
return diag.FromErr(fmt.Errorf("failed to fetch authentication domains"))
}

for _, authenticationDomain := range resp.AuthenticationDomains {
if name == authenticationDomain.Name {
matchingAuthenticationDomainID = authenticationDomain.ID
Expand Down
100 changes: 100 additions & 0 deletions newrelic/data_source_newrelic_user_management.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package newrelic

import (
"context"
"fmt"
"log"

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

func dataSourceNewRelicUser() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceNewRelicUserRead,
Schema: map[string]*schema.Schema{
"authentication_domain_id": {
Type: schema.TypeString,
Required: true,
Description: "The ID of the Authentication Domain the user being queried would belong to.",
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The name of the user to be queried.",
AtLeastOneOf: []string{"name", "email_id"},
},
"email_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The email ID of the user to be queried.",
AtLeastOneOf: []string{"name", "email_id"},
},
"id": {
Type: schema.TypeString,
Computed: true,
Description: "The ID of the fetched user.",
},
},
}
}

func dataSourceNewRelicUserRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConfig := meta.(*ProviderConfig)
client := providerConfig.NewClient

log.Printf("[INFO] Fetching Users")

name, nameOk := d.GetOk("name")
email, emailOk := d.GetOk("email_id")
authDomainID, authDomainIDOk := d.GetOk("authentication_domain_id")

nameQuery := ""
emailQuery := ""

if nameOk && name != "" {
nameQuery = name.(string)
}

if emailOk && email != "" {
emailQuery = email.(string)
}

if !authDomainIDOk {
return diag.FromErr(fmt.Errorf("'authentication_domain_id' is required"))
}

authenticationDomainID := authDomainID.(string)

resp, err := client.UserManagement.UserManagementGetUsersWithContext(
ctx,
[]string{authenticationDomainID},
[]string{},
nameQuery,
emailQuery,
)

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

if resp == nil {
return diag.FromErr(fmt.Errorf("failed to fetch users"))
}

for _, authDomain := range resp.AuthenticationDomains {
if authDomain.ID == authenticationDomainID {
for _, u := range authDomain.Users.Users {
d.SetId(u.ID)
_ = d.Set("name", u.Name)
_ = d.Set("email_id", u.Email)
return nil
}
}
}

return diag.FromErr(fmt.Errorf("no user found with the specified parameters"))

}
85 changes: 85 additions & 0 deletions newrelic/data_source_newrelic_user_management_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
//go:build integration
// +build integration

package newrelic

import (
"fmt"
"regexp"
"strings"
"testing"

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

var authenticationDomainName = "Test-Auth-Domain DO NOT DELETE"
var existingUserEmail = strings.ReplaceAll(userEmailPrefix, "#", "integration")
var existingUserName = "Integration Test User 1 DO NOT DELETE"

func TestAccNewRelicUserDataSource_Basic(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccNewRelicUserDataSourceConfiguration(authenticationDomainName, existingUserEmail, ""),
Check: resource.ComposeTestCheckFunc(
testAccNewRelicCheckUserDataSourceExists(t, "data.newrelic_user.foo"),
),
},
},
})
}

func TestAccNewRelicUserDataSource_EmailAndName(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccNewRelicUserDataSourceConfiguration(authenticationDomainName, existingUserEmail, existingUserName),
Check: resource.ComposeTestCheckFunc(
testAccNewRelicCheckUserDataSourceExists(t, "data.newrelic_user.foo"),
),
},
},
})
}

func TestAccNewRelicUserDataSource_MissingError(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccNewRelicUserDataSourceConfiguration(authenticationDomainName, "", fmt.Sprintf("%s-Invalid", existingUserName)),
ExpectError: regexp.MustCompile(`no user found with the specified parameters`),
},
},
})
}

func testAccNewRelicCheckUserDataSourceExists(t *testing.T, n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
r := s.RootModule().Resources[n]
a := r.Primary.Attributes

if a["id"] == "" {
return fmt.Errorf("expected to get an ID of the matching user")
}

return nil
}
}

func testAccNewRelicUserDataSourceConfiguration(authenticationDomainName string, userEmailID string, userName string) string {
return fmt.Sprintf(`
data "newrelic_authentication_domain" "foo" {
name = "%s"
}
data "newrelic_user" "foo" {
authentication_domain_id = data.newrelic_authentication_domain.foo.id
email_id = "%s"
name = "%s"
}
`, authenticationDomainName, userEmailID, userName)
}
4 changes: 3 additions & 1 deletion newrelic/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,11 @@ func Provider() *schema.Provider {
"newrelic_synthetics_secure_credential": dataSourceNewRelicSyntheticsSecureCredential(),
"newrelic_test_grok_pattern": dataSourceNewRelicTestGrokPattern(),
"newrelic_service_level_alert_helper": dataSourceNewRelicServiceLevelAlertHelper(),
"newrelic_user": dataSourceNewRelicUser(),
},

ResourcesMap: map[string]*schema.Resource{
"newrelic_account_management": resourceNewRelicAccountManagement(),
"newrelic_alert_channel": resourceNewRelicAlertChannel(),
"newrelic_alert_condition": resourceNewRelicAlertCondition(),
"newrelic_alert_muting_rule": resourceNewRelicAlertMutingRule(),
Expand Down Expand Up @@ -181,7 +183,7 @@ func Provider() *schema.Provider {
"newrelic_synthetics_step_monitor": resourceNewRelicSyntheticsStepMonitor(),
"newrelic_workflow": resourceNewRelicWorkflow(),
"newrelic_workload": resourceNewRelicWorkload(),
"newrelic_account_management": resourceNewRelicWorkloadAccountManagement(),
"newrelic_user": resourceNewRelicUser(),
},
}

Expand Down
2 changes: 1 addition & 1 deletion newrelic/resource_newrelic_account_management.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"github.com/newrelic/newrelic-client-go/v2/pkg/accountmanagement"
)

func resourceNewRelicWorkloadAccountManagement() *schema.Resource {
func resourceNewRelicAccountManagement() *schema.Resource {
return &schema.Resource{
CreateContext: resourceNewRelicAccountCreate,
ReadContext: resourceNewRelicAccountRead,
Expand Down
Loading

0 comments on commit 26c5b49

Please sign in to comment.