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

Allow managing project permissions #768

Merged
merged 4 commits into from
Jan 26, 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ ENHANCEMENTS:

FEATURES:
* **New Provider Config**: `organization` defines a default organization for all resources, making all resource-specific organization arguments optional.
* **New Resource**: r/tfe_team_project_access is a new resource that allows managing team project permissions.
* **New Data Source**: d/tfe_team_project_access is a new datasource to allows reading existing team project permissions.
* r/tfe_team: Teams can now be imported using `<ORGANIZATION NAME>/<TEAM NAME>` ([#745](https://github.com/hashicorp/terraform-provider-tfe/pull/745))
* r/tfe_team: Add attribute `manage_projects` to `tfe_team`.
* r/tfe_team_organization_member: Team Organization Memberships can now be imported using `<ORGANIZATION NAME>/<USER EMAIL>/<TEAM NAME>` ([#745](https://github.com/hashicorp/terraform-provider-tfe/pull/745))

## v0.41.0 (January 4, 2023)
Expand Down
75 changes: 75 additions & 0 deletions tfe/data_source_team_project_access.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package tfe

import (
"context"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"

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

func dataSourceTFETeamProjectAccess() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceTFETeamProjectAccessRead,

Schema: map[string]*schema.Schema{
"access": {
Type: schema.TypeString,
Computed: true,
},

"team_id": {
Type: schema.TypeString,
Required: true,
},

"project_id": {
Type: schema.TypeString,
Required: true,
},
},
}
}

func dataSourceTFETeamProjectAccessRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(ConfiguredClient)

// Get the team ID.
teamID := d.Get("team_id").(string)

// Get the project
projectID := d.Get("project_id").(string)
proj, err := config.Client.Projects.Read(ctx, projectID)
if err != nil {
return diag.Errorf(
"Error retrieving project %s: %v", projectID, err)
}

options := tfe.TeamProjectAccessListOptions{
ProjectID: proj.ID,
}

for {
l, err := config.Client.TeamProjectAccess.List(ctx, options)
if err != nil {
return diag.Errorf("Error retrieving team access list: %v", err)
}

for _, ta := range l.Items {
if ta.Team.ID == teamID {
d.SetId(ta.ID)
return resourceTFETeamProjectAccessRead(ctx, d, meta)
}
}

// Exit the loop when we've seen all pages.
if l.CurrentPage >= l.TotalPages {
break
}

// Update the page number to get the next page.
options.PageNumber = l.NextPage
}

return diag.Errorf("could not find team project access for %s and project %s", teamID, proj.Name)
}
62 changes: 62 additions & 0 deletions tfe/data_source_team_project_access_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package tfe

import (
"fmt"
"testing"

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

func TestAccTFETeamProjectAccessDataSource_basic(t *testing.T) {
skipUnlessBeta(t)

tfeClient, err := getClientUsingEnv()
if err != nil {
t.Fatal(err)
}

org, orgCleanup := createBusinessOrganization(t, tfeClient)
t.Cleanup(orgCleanup)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccTFETeamProjectAccessDataSourceConfig(org.Name),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr(
"data.tfe_team_project_access.foobar", "access", "read"),
resource.TestCheckResourceAttrSet("data.tfe_team_project_access.foobar", "id"),
resource.TestCheckResourceAttrSet("data.tfe_team_project_access.foobar", "team_id"),
resource.TestCheckResourceAttrSet("data.tfe_team_project_access.foobar", "project_id"),
),
},
},
})
}

func testAccTFETeamProjectAccessDataSourceConfig(organization string) string {
return fmt.Sprintf(`
resource "tfe_team" "foobar" {
name = "team-test"
organization = "%s"
}

resource "tfe_project" "foobar" {
name = "projecttest"
organization = "%s"
}

resource "tfe_team_project_access" "foobar" {
access = "read"
team_id = tfe_team.foobar.id
project_id = tfe_project.foobar.id
}

data "tfe_team_project_access" "foobar" {
team_id = tfe_team.foobar.id
project_id = tfe_project.foobar.id
depends_on = [tfe_team_project_access.foobar]
}`, organization, organization)
}
2 changes: 2 additions & 0 deletions tfe/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ func Provider() *schema.Provider {
"tfe_ssh_key": dataSourceTFESSHKey(),
"tfe_team": dataSourceTFETeam(),
"tfe_team_access": dataSourceTFETeamAccess(),
"tfe_team_project_access": dataSourceTFETeamProjectAccess(),
"tfe_workspace": dataSourceTFEWorkspace(),
"tfe_workspace_ids": dataSourceTFEWorkspaceIDs(),
"tfe_workspace_run_task": dataSourceTFEWorkspaceRunTask(),
Expand Down Expand Up @@ -146,6 +147,7 @@ func Provider() *schema.Provider {
"tfe_team_access": resourceTFETeamAccess(),
"tfe_team_organization_member": resourceTFETeamOrganizationMember(),
"tfe_team_organization_members": resourceTFETeamOrganizationMembers(),
"tfe_team_project_access": resourceTFETeamProjectAccess(),
"tfe_team_member": resourceTFETeamMember(),
"tfe_team_members": resourceTFETeamMembers(),
"tfe_team_token": resourceTFETeamToken(),
Expand Down
3 changes: 3 additions & 0 deletions tfe/resource_tfe_project.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@ import (
tfe "github.com/hashicorp/go-tfe"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"regexp"
)

var projectIDRegexp = regexp.MustCompile("^prj-[a-zA-Z0-9]{16}$")

func resourceTFEProject() *schema.Resource {
return &schema.Resource{
CreateContext: resourceTFEProjectCreate,
Expand Down
8 changes: 8 additions & 0 deletions tfe/resource_tfe_team.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ func resourceTFETeam() *schema.Resource {
Optional: true,
Default: false,
},
"manage_projects": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
},
},
Expand Down Expand Up @@ -121,6 +126,7 @@ func resourceTFETeamCreate(d *schema.ResourceData, meta interface{}) error {
ManageProviders: tfe.Bool(organizationAccess["manage_providers"].(bool)),
ManageModules: tfe.Bool(organizationAccess["manage_modules"].(bool)),
ManageRunTasks: tfe.Bool(organizationAccess["manage_run_tasks"].(bool)),
ManageProjects: tfe.Bool(organizationAccess["manage_projects"].(bool)),
}
}

Expand Down Expand Up @@ -177,6 +183,7 @@ func resourceTFETeamRead(d *schema.ResourceData, meta interface{}) error {
"manage_providers": team.OrganizationAccess.ManageProviders,
"manage_modules": team.OrganizationAccess.ManageModules,
"manage_run_tasks": team.OrganizationAccess.ManageRunTasks,
"manage_projects": team.OrganizationAccess.ManageProjects,
}}
if err := d.Set("organization_access", organizationAccess); err != nil {
return fmt.Errorf("error setting organization access for team %s: %w", d.Id(), err)
Expand Down Expand Up @@ -210,6 +217,7 @@ func resourceTFETeamUpdate(d *schema.ResourceData, meta interface{}) error {
ManageProviders: tfe.Bool(organizationAccess["manage_providers"].(bool)),
ManageModules: tfe.Bool(organizationAccess["manage_modules"].(bool)),
ManageRunTasks: tfe.Bool(organizationAccess["manage_run_tasks"].(bool)),
ManageProjects: tfe.Bool(organizationAccess["manage_projects"].(bool)),
}
}

Expand Down
162 changes: 162 additions & 0 deletions tfe/resource_tfe_team_project_access.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package tfe

import (
"context"
"errors"
tfe "github.com/hashicorp/go-tfe"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"log"
)

func resourceTFETeamProjectAccess() *schema.Resource {
return &schema.Resource{
CreateContext: resourceTFETeamProjectAccessCreate,
ReadContext: resourceTFETeamProjectAccessRead,
UpdateContext: resourceTFETeamProjectAccessUpdate,
DeleteContext: resourceTFETeamProjectAccessDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},

SchemaVersion: 1,

Schema: map[string]*schema.Schema{
"access": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(
[]string{
string(tfe.TeamProjectAccessAdmin),
string(tfe.TeamProjectAccessRead),
},
false,
),
},

"team_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"project_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(
projectIDRegexp,
"must be a valid project ID (prj-<RANDOM STRING>)",
),
},
},
}
}

func resourceTFETeamProjectAccessCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(ConfiguredClient)

// Get the access level
access := d.Get("access").(string)

// Get the project
projectID := d.Get("project_id").(string)
proj, err := config.Client.Projects.Read(ctx, projectID)
if err != nil {
return diag.Errorf(
"Error retrieving project %s: %v", projectID, err)
}

// Get the team.
teamID := d.Get("team_id").(string)
tm, err := config.Client.Teams.Read(ctx, teamID)
if err != nil {
return diag.Errorf("Error retrieving team %s: %v", teamID, err)
}

// Create a new options struct.
options := tfe.TeamProjectAccessAddOptions{
Access: *tfe.ProjectAccess(tfe.TeamProjectAccessType(access)),
Team: tm,
Project: proj,
}

log.Printf("[DEBUG] Give team %s %s access to project: %s", tm.Name, access, proj.Name)
tmAccess, err := config.Client.TeamProjectAccess.Add(ctx, options)
if err != nil {
return diag.Errorf(
"Error giving team %s %s access to project %s: %v", tm.Name, access, proj.Name, err)
}

d.SetId(tmAccess.ID)

return resourceTFETeamProjectAccessRead(ctx, d, meta)
}

func resourceTFETeamProjectAccessRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(ConfiguredClient)

log.Printf("[DEBUG] Read configuration of team access: %s", d.Id())
tmAccess, err := config.Client.TeamProjectAccess.Read(ctx, d.Id())
if err != nil {
if errors.Is(err, tfe.ErrResourceNotFound) {
log.Printf("[DEBUG] Team project access %s no longer exists", d.Id())
d.SetId("")
return nil
}
return diag.Errorf("Error reading configuration of team project access %s: %v", d.Id(), err)
}

// Update config.
d.Set("access", string(tmAccess.Access))

if tmAccess.Team != nil {
d.Set("team_id", tmAccess.Team.ID)
} else {
d.Set("team_id", "")
}

if tmAccess.Project != nil {
d.Set("project_id", tmAccess.Project.ID)
} else {
d.Set("project_id", "")
}
sebasslash marked this conversation as resolved.
Show resolved Hide resolved

return nil
}

func resourceTFETeamProjectAccessUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(ConfiguredClient)

// create an options struct
options := tfe.TeamProjectAccessUpdateOptions{}

// Set access level
access := d.Get("access").(string)
options.Access = tfe.ProjectAccess(tfe.TeamProjectAccessType(access))

log.Printf("[DEBUG] Update team project access: %s", d.Id())
_, err := config.Client.TeamProjectAccess.Update(ctx, d.Id(), options)
if err != nil {
return diag.Errorf(
"Error updating team project access %s: %v", d.Id(), err)
}

return nil
}

func resourceTFETeamProjectAccessDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(ConfiguredClient)

log.Printf("[DEBUG] Delete team access: %s", d.Id())
err := config.Client.TeamAccess.Remove(ctx, d.Id())
if err != nil {
if errors.Is(err, tfe.ErrResourceNotFound) {
return nil
}
return diag.Errorf("Error deleting team project access %s: %v", d.Id(), err)
}

return nil
}
Loading