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

azuredevops_securityrole_definitions, azuredevops_securityrole_assignment - New resource and data source for securityrole assignments #982

Merged
merged 20 commits into from
Apr 3, 2024
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,6 @@ dist

#GoLand Editor configuration
.idea
.fleet

.DS_Store
109 changes: 109 additions & 0 deletions azdosdkmocks/securityroles_sdk_mock.go

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//go:build (all || core || data_sources || data_securityrole_definitions) && (!data_sources || !exclude_data_securityrole_definitions)
// +build all core data_sources data_securityrole_definitions
// +build !data_sources !exclude_data_securityrole_definitions

package acceptancetests

import (
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/microsoft/terraform-provider-azuredevops/azuredevops/internal/acceptancetests/testutils"
)

func TestAccAzureDevOpsSecurityroles_DataSource_Securityrole_Definitions(t *testing.T) {
securityroleDefinitionsData := testutils.HclSecurityroleDefinitionsDataSource()

tfNode := "data.azuredevops_securityrole_definitions.definitions-list"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testutils.PreCheck(t, nil) },
ProviderFactories: testutils.GetProviderFactories(),
Steps: []resource.TestStep{
{
Config: securityroleDefinitionsData,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet(tfNode, "definitions.#"),
),
},
},
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
//go:build (all || core || resource_securityrole_assignment) && !exclude_resource_securityrole_assignment
// +build all core resource_securityrole_assignment
// +build !exclude_resource_securityrole_assignment

package acceptancetests

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/microsoft/terraform-provider-azuredevops/azuredevops/internal/acceptancetests/testutils"
)

func TestAccSecurityroleAssignmentResource_Basic(t *testing.T) {
projectName := testutils.GenerateResourceName()
groupName := testutils.GenerateResourceName()

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testutils.PreCheck(t, nil) },
Providers: testutils.GetProviders(),
Steps: []resource.TestStep{
{
Config: hclSecurityroleAssignmentBasic(projectName, groupName),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet("azuredevops_securityrole_assignment.test", "scope"),
resource.TestCheckResourceAttr("azuredevops_securityrole_assignment.test", "role_name", "Administrator"),
),
},
},
})
}

func hclSecurityroleAssignmentBasic(projectName, groupName string) string {

return fmt.Sprintf(`
resource "azuredevops_project" "test" {
name = "%[1]s"
description = "%[1]s-description"
visibility = "private"
version_control = "Git"
work_item_template = "Agile"
}

resource "azuredevops_group" "test" {
scope = azuredevops_project.test.id
display_name = "%[2]s"
}

resource "azuredevops_environment" "test" {
project_id = azuredevops_project.test.id
name = "Example Environment"
description = "Example pipeline deployment environment"
}

resource "azuredevops_securityrole_assignment" "test" {
scope = "distributedtask.environmentreferencerole"
resource_id = "${azuredevops_project.test.id}_${azuredevops_environment.test.id}"
identity_id = azuredevops_group.test.origin_id
role_name = "Administrator"
}
`, projectName, groupName)
}
9 changes: 9 additions & 0 deletions azuredevops/internal/acceptancetests/testutils/hcl.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,15 @@ func HclProjectGitRepoImportPrivate(projectName, gitRepoName, gitImportRepoName,
return fmt.Sprintf("%s\n%s\n%s", gitRepoResource, serviceEndpointResource, importGitRepoResource)
}

// HclSecurityroleDefinitionsDataSource HCL describing a data source for securityrole definitions
func HclSecurityroleDefinitionsDataSource() string {
return `
data "azuredevops_securityrole_definitions" "definitions-list" {
scope = "distributedtask.environmentreferencerole"
}
`
}

// HclUserEntitlementResource HCL describing an AzDO UserEntitlement
func HclUserEntitlementResource(principalName string) string {
return fmt.Sprintf(`
Expand Down
5 changes: 5 additions & 0 deletions azuredevops/internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
"github.com/microsoft/azure-devops-go-api/azuredevops/v7/workitemtracking"
"github.com/microsoft/terraform-provider-azuredevops/azuredevops/utils/pipelineschecksextras"
"github.com/microsoft/terraform-provider-azuredevops/azuredevops/utils/sdk"
"github.com/microsoft/terraform-provider-azuredevops/azuredevops/utils/securityroles"
"github.com/microsoft/terraform-provider-azuredevops/version"
)

Expand Down Expand Up @@ -62,6 +63,7 @@ type AggregatedClient struct {
WorkItemTrackingClient workitemtracking.Client
ServiceHooksClient servicehooks.Client
Ctx context.Context
SecurityRolesClient securityroles.Client
}

// GetAzdoClient builds and provides a connection to the Azure DevOps API
Expand Down Expand Up @@ -173,6 +175,8 @@ func GetAzdoClient(azdoTokenProvider func() (string, error), organizationURL str

serviceHooksClient := servicehooks.NewClient(ctx, connection)

securityRolesClient := securityroles.NewClient(ctx, connection)

aggregatedClient := &AggregatedClient{
OrganizationURL: organizationURL,
CoreClient: coreClient,
Expand All @@ -195,6 +199,7 @@ func GetAzdoClient(azdoTokenProvider func() (string, error), organizationURL str
IdentityClient: identityClient,
WorkItemTrackingClient: workitemtrackingClient,
ServiceHooksClient: serviceHooksClient,
SecurityRolesClient: securityRolesClient,
Ctx: ctx,
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package securityroles

import (
"fmt"

"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/microsoft/terraform-provider-azuredevops/azuredevops/internal/client"
"github.com/microsoft/terraform-provider-azuredevops/azuredevops/internal/utils/tfhelper"
"github.com/microsoft/terraform-provider-azuredevops/azuredevops/utils/securityroles"
)

func DataSecurityRoleDefinitions() *schema.Resource {
return &schema.Resource{
Read: dataSecurityRoleDefinitiosRead,
Schema: map[string]*schema.Schema{
"scope": {
Type: schema.TypeString,
ValidateFunc: validation.NoZeroValues,
Required: true,
},
"definitions": {
Type: schema.TypeSet,
Computed: true,
Set: getSRDHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},

"display_name": {
Type: schema.TypeString,
Computed: true,
},

"allow_permissions": {
Type: schema.TypeInt,
Computed: true,
},

"deny_permissions": {
Type: schema.TypeInt,
Optional: true,
},

"identifier": {
Type: schema.TypeString,
Computed: true,
},

"description": {
Type: schema.TypeString,
Computed: true,
},

"scope": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}

func dataSecurityRoleDefinitiosRead(d *schema.ResourceData, m interface{}) error {
clients := m.(*client.AggregatedClient)
scope := d.Get("scope").(string)

defs, err := clients.SecurityRolesClient.ListSecurityRoleDefinitions(clients.Ctx, &securityroles.ListSecurityRoleDefinitionsArgs{
Scope: &scope,
})
if err != nil {
errMsg := "Error finding security role definitions"
if scope != "" {
errMsg = fmt.Sprintf("%s for scope %s", errMsg, scope)
}
return fmt.Errorf("%s. Error: %v", errMsg, err)
}

fdefs, err := flattenSRD(defs)
if err != nil {
return fmt.Errorf("flattening security role definitions. Error: %w", err)
}

d.SetId("secroledefs-" + uuid.New().String())
d.Set("definitions", fdefs)

return nil
}

func getSRDHash(v interface{}) int {
return tfhelper.HashString(v.(map[string]interface{})["identifier"].(string))
}

func flattenSRD(srds *[]securityroles.SecurityRoleDefinition) ([]interface{}, error) {
if srds == nil {
return []interface{}{}, nil
}

results := make([]interface{}, len(*srds))
for i, srd := range *srds {
s := make(map[string]interface{})

if srd.Identifier != nil {
s["identifier"] = *srd.Identifier
} else {
return nil, fmt.Errorf("Security Role Definition Object does not contain an identifier")
}
if srd.DisplayName != nil {
s["display_name"] = *srd.DisplayName
}
if srd.Name != nil {
s["name"] = *srd.Name
}
if srd.Description != nil {
s["description"] = *srd.Description
}
if srd.Scope != nil {
s["scope"] = *srd.Scope
}

if srd.AllowPermissions != nil {
s["allow_permissions"] = *srd.AllowPermissions
}

if srd.DenyPermissions != nil {
s["deny_permissions"] = *srd.DenyPermissions
}

results[i] = s
}
return results, nil
}
Loading