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

Add Personal Access Token Resource/Data Source to create/update/revok… #1140

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
110 changes: 110 additions & 0 deletions azdosdkmocks/tokens_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,40 @@
//go:build (all || data_sources || data_agent_queue) && (!exclude_data_sources || !exclude_data_agent_queue)
// +build all data_sources data_agent_queue
// +build !exclude_data_sources !exclude_data_agent_queue

package acceptancetests

import (
"testing"

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

func TestAccPersonAccessToken_DataSource(t *testing.T) {
authorization_id := uuid.New().String()
personalAccessTokenData := testutils.HclPersonalAccessTokenDataSource(authorization_id)

tfNode := "data.azuredevops_personal_access_token.pat"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testutils.PreCheck(t, nil) },
Providers: testutils.GetProviders(),
Steps: []resource.TestStep{
{
Config: personalAccessTokenData,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(tfNode, "id", authorization_id),
resource.TestCheckResourceAttr(tfNode, "authorization_id", authorization_id),
resource.TestCheckResourceAttrSet(tfNode, "name"),
resource.TestCheckResourceAttrSet(tfNode, "scope"),
resource.TestCheckResourceAttrSet(tfNode, "target_accounts"),
resource.TestCheckResourceAttrSet(tfNode, "token"),
resource.TestCheckResourceAttrSet(tfNode, "valid_from"),
resource.TestCheckResourceAttrSet(tfNode, "valid_to"),
resource.TestCheckResourceAttrSet(tfNode, "valid_to"),
),
},
},
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//go:build (all || resource_agent_queue) && !exclude_resource_agent_queue
// +build all resource_agent_queue
// +build !exclude_resource_agent_queue

package acceptancetests

import (
"testing"

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

func TestAccResourcePersonalAccessToken_CreateAndUpdate(t *testing.T) {
tokenName := testutils.GenerateResourceName()
tfNode := "azuredevops_personal_access_token.pat"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testutils.PreCheck(t, nil) },
Providers: testutils.GetProviders(),
Steps: []resource.TestStep{
{
Config: testutils.HclPersonalAccessTokenResource(tokenName),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet(tfNode, "id"),
resource.TestCheckResourceAttrSet(tfNode, "authorization_id"),
resource.TestCheckResourceAttrSet(tfNode, "scope"),
resource.TestCheckResourceAttrSet(tfNode, "target_accounts"),
resource.TestCheckResourceAttrSet(tfNode, "token"),
resource.TestCheckResourceAttrSet(tfNode, "valid_from"),
resource.TestCheckResourceAttrSet(tfNode, "valid_to"),
),
}, {
ResourceName: tfNode,
ImportStateIdFunc: testutils.ComputeProjectQualifiedResourceImportID(tfNode),
ImportState: true,
ImportStateVerify: true,
},
},
})
}
17 changes: 17 additions & 0 deletions azuredevops/internal/acceptancetests/testutils/hcl.go
Original file line number Diff line number Diff line change
Expand Up @@ -1110,3 +1110,20 @@ resource "azuredevops_wiki" "project_wiki" {
}
`, projectResource)
}

// HclPersonalAccessTokenDataSource HCL describing a data source for Personal Access Token definitions
func HclPersonalAccessTokenDataSource(authorization_id string) string {
return fmt.Sprintf(`
data "azuredevops_personal_access_token" "pat" {
authorization_id = %s
}
`, authorization_id)
}

// HclPersonalAccessTokenResource HCL describing an Azure DevOps Personal Access Token
func HclPersonalAccessTokenResource(tokenName string) string {
return fmt.Sprintf(`
resource "azuredevops_personal_access_token" "pat" {
name = "%s"
}`, tokenName)
}
9 changes: 9 additions & 0 deletions azuredevops/internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/microsoft/azure-devops-go-api/azuredevops/v7/serviceendpoint"
"github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks"
"github.com/microsoft/azure-devops-go-api/azuredevops/v7/taskagent"
"github.com/microsoft/azure-devops-go-api/azuredevops/v7/tokens"
"github.com/microsoft/azure-devops-go-api/azuredevops/v7/wiki"
"github.com/microsoft/azure-devops-go-api/azuredevops/v7/workitemtracking"
"github.com/microsoft/terraform-provider-azuredevops/azuredevops/utils/pipelineschecksextras"
Expand Down Expand Up @@ -68,6 +69,7 @@ type AggregatedClient struct {
ServiceHooksClient servicehooks.Client
Ctx context.Context
SecurityRolesClient securityroles.Client
TokensClient tokens.Client
}

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

securityRolesClient := securityroles.NewClient(ctx, connection)

tokensClient, err := tokens.NewClient(ctx, connection)
if err != nil {
log.Printf("getAzdoClient(): tokens.NewClient failed.")
return nil, err
}

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

Expand Down
88 changes: 88 additions & 0 deletions azuredevops/internal/service/tokens/data_personal_access_token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package tokens

import (
"fmt"
"time"

"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/azure-devops-go-api/azuredevops/v7/tokens"
"github.com/microsoft/terraform-provider-azuredevops/azuredevops/internal/client"
"github.com/microsoft/terraform-provider-azuredevops/azuredevops/internal/utils/suppress"
)

// DataAgentQueue schema and implementation for agent queue source
func DataPersonalAccessToken() *schema.Resource {
return &schema.Resource{
Read: dataPersonalAccessTokenRead,
Timeouts: &schema.ResourceTimeout{
Read: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"authorization_id": {
Type: schema.TypeString,
Required: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"scope": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: suppress.CaseDifference,
},
"target_accounts": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"token": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"valid_from": {
Type: schema.TypeString,
Optional: true,
},
"valid_to": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.IsRFC3339Time,
},
},
}
}

func dataPersonalAccessTokenRead(d *schema.ResourceData, m interface{}) error {
clients := m.(*client.AggregatedClient)

authorizationID, err := uuid.Parse(d.Get("authorization_id").(string))
if err != nil {
return fmt.Errorf(" parse token authorization ID: %+v", err)
}

token, err := clients.TokensClient.GetPat(clients.Ctx, tokens.GetPatArgs{AuthorizationId: &authorizationID})
if err != nil {
return fmt.Errorf("Error getting personal access token by authorization ID: %v", err)
}

if token == nil {
d.SetId("")
return nil
}

d.SetId(token.PatToken.AuthorizationId.String())
d.Set("name", token.PatToken.DisplayName)
d.Set("authorization_id", token.PatToken.AuthorizationId.String())
d.Set("scope", token.PatToken.Scope)
d.Set("target_accounts", token.PatToken.TargetAccounts)
d.Set("token", token.PatToken.Token)
d.Set("valid_from", token.PatToken.ValidFrom)
d.Set("valid_to", token.PatToken.ValidTo)
return nil
}
Loading