Skip to content

Commit

Permalink
add tests and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
ilia-medvedev-codefresh committed Jan 7, 2025
1 parent c78b225 commit 1654c4e
Show file tree
Hide file tree
Showing 7 changed files with 324 additions and 61 deletions.
5 changes: 3 additions & 2 deletions codefresh/resource_api_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ import (
func resourceApiKey() *schema.Resource {
return &schema.Resource{
Description: `
Manages an API Key tied to an Account and a User.
Requires a Codefresh admin token and applies only to Codefresh on-premises installations.
Manages an API Key tied to a user within an account or a service account within the current account.
On the Codefresh SaaS platfrom this resource is only usable for service accounts.
Management of API keys for users in other accounts requires admin priveleges and hence can only be done on Codefresh on-premises installations.
`,
Create: resourceApiKeyCreate,
Read: resourceApiKeyRead,
Expand Down
133 changes: 133 additions & 0 deletions codefresh/resource_api_key_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package codefresh

import (
"fmt"
"testing"

"github.com/codefresh-io/terraform-provider-codefresh/codefresh/cfclient"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

var apiKeyNamePrefix = "TerraformAccTest_"

func TestAccCodefreshAPIKey_ServiceUser(t *testing.T) {
name := apiKeyNamePrefix + acctest.RandString(10)

resourceName := "codefresh_api_key.test_apikey"
serviceAccountResourceName := "codefresh_service_account.test_apikey"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckCodefreshServiceUserAndAPIKeyDestroyed,
Steps: []resource.TestStep{
{
Config: testAccCodefreshAPIKeyServiceAccount(name, name),
Check: resource.ComposeTestCheckFunc(
testAccCheckCodefreshServiceUserAPIKeyExists(resourceName, serviceAccountResourceName),
resource.TestCheckResourceAttr(resourceName, "name", name),
resource.TestCheckResourceAttr(resourceName, "scopes.0", "agent"),
),
},
{
ResourceName: resourceName,
RefreshState: true,
},
},
})
}

func testAccCheckCodefreshServiceUserAPIKeyExists(apiKeyResource string, serviceUserResource string) resource.TestCheckFunc {
return func(state *terraform.State) error {
serviceUserState, ok := state.RootModule().Resources[serviceUserResource]

if !ok {
return fmt.Errorf("Not found: %s", serviceUserResource)
}

if serviceUserState.Primary.ID == "" {
return fmt.Errorf("No Record ID is set")
}

apiKeyState, ok := state.RootModule().Resources[apiKeyResource]

if !ok {
return fmt.Errorf("Not found: %s", apiKeyResource)
}

if apiKeyState.Primary.ID == "" {
return fmt.Errorf("No Record ID is set for team")
}

serviceUserID := serviceUserState.Primary.ID
apiKeyID := apiKeyState.Primary.ID

apiClient := testAccProvider.Meta().(*cfclient.Client)
_, err := apiClient.GetAPIKeyServiceUser(apiKeyID, serviceUserID)

if err != nil {
return fmt.Errorf("error fetching service user api key for resource %s. %s", apiKeyID, err)
}

return nil
}
}

func testAccCheckCodefreshServiceUserAndAPIKeyDestroyed(s *terraform.State) error {
apiClient := testAccProvider.Meta().(*cfclient.Client)

for _, rs := range s.RootModule().Resources {

if rs.Type != "codefresh_service_account" && rs.Type != "codefresh_api_key" {
continue
}

var (
serviceAccountId string
apiKeyId string
)

if rs.Type == "codefresh_service_account" {
serviceAccountId = rs.Primary.ID
_, err := apiClient.GetServiceUserByID(serviceAccountId)

if err == nil {
return fmt.Errorf("Alert service account still exists")
}
}

if rs.Type == "codefresh_api_key" {
apiKeyId = rs.Primary.ID
_, err := apiClient.GetAPIKeyServiceUser(apiKeyId, serviceAccountId)

if err == nil {
return fmt.Errorf("Alert api key still exists")
}
}
}

return nil
}

func testAccCodefreshAPIKeyServiceAccount(apiKeyName string, serviceUserName string) string {
return fmt.Sprintf(`
resource "codefresh_service_account" "test_apikey" {
name = "%s"
}
resource "codefresh_api_key" "test_apikey" {
service_account_id = codefresh_service_account.test_apikey.id
name = "%s"
scopes = [
"agent",
"agents",
"audit",
"api-keys"
]
}
`, serviceUserName, apiKeyName)
}
56 changes: 11 additions & 45 deletions codefresh/resource_service_account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,24 @@ import (

var serviceUserNamePrefix = "TerraformAccTest_"

func TestAccCodefreshServiceUser_basic(t *testing.T) {
func TestAccCodefreshServiceUser_WithTeamAssignment(t *testing.T) {
name := serviceUserNamePrefix + acctest.RandString(10)

resourceName := "codefresh_service_account.test"
teamResourceName := "codefresh_team.test"
resourceName := "codefresh_service_account.test_serviceaccount"
teamResourceName := "codefresh_team.test_serviceaccount"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckCodefreshServiceUserDestroy,
Steps: []resource.TestStep{
{
Config: testAccCodefreshServiceUserTeamToken(name, name),
Config: testAccCodefreshServiceUserTeam(name, name, false),
Check: resource.ComposeTestCheckFunc(
testAccCheckCodefreshServiceUserExists(resourceName),
testAccCheckCodefreshServiceUserAssignedToTeam(resourceName, teamResourceName),
resource.TestCheckResourceAttr(resourceName, "name", name),
resource.TestCheckResourceAttr(resourceName, "assign_admin_role", "false"),
),
},
{
Expand Down Expand Up @@ -137,52 +138,17 @@ func testAccCheckCodefreshServiceUserDestroy(s *terraform.State) error {
return nil
}

func testAccCodefreshServiceUserTeamToken(serviceUserName string, teamName string) string {
func testAccCodefreshServiceUserTeam(serviceUserName string, teamName string, assignAdminRole bool) string {
return fmt.Sprintf(`
resource "codefresh_team" "test" {
resource "codefresh_team" "test_serviceaccount" {
name = "%s"
}
resource "codefresh_service_account" "test" {
resource "codefresh_service_account" "test_serviceaccount" {
name = "%s"
assigned_teams = [codefresh_team.test.id]
}
`, serviceUserName, teamName)
}

// CONFIGS
func testAccCodefreshServiceUserBasicConfig(rName string) string {
return fmt.Sprintf(`
resource "codefresh_service_account" "test" {
name = "%s"
}
`, rName)
}
assigned_teams = [codefresh_team.test_serviceaccount.id]
assign_admin_role = %t
func testAccCodefreshServiceUserBasicConfigTags(rName, tag1, tag2 string) string {
return fmt.Sprintf(`
resource "codefresh_service_user" "test" {
name = "%s"
tags = [
%q,
%q,
]
}
`, rName, tag1, tag2)
}

func testAccCodefreshServiceUserBasicConfigVariables(rName, var1Name, var1Value, var2Name, var2Value, encrytedVar1Name, encrytedVar1Value string) string {
return fmt.Sprintf(`
resource "codefresh_serviceUser" "test" {
name = "%s"
variables = {
%q = %q
%q = %q
}
encrypted_variables = {
%q = %q
}
}
`, rName, var1Name, var1Value, var2Name, var2Value, encrytedVar1Name, encrytedVar1Value)
`, serviceUserName, teamName, assignAdminRole)
}
60 changes: 50 additions & 10 deletions docs/resources/api_key.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,60 @@
page_title: "codefresh_api_key Resource - terraform-provider-codefresh"
subcategory: ""
description: |-
Manages an API Key tied to an Account and a User.
Requires a Codefresh admin token and applies only to Codefresh on-premises installations.
Manages an API Key tied to a user within an account or a service account within the current account.
On the Codefresh SaaS platfrom this resource is only usable for service accounts.
Management of API keys for users in other accounts requires admin priveleges and hence can only be done on Codefresh on-premises installations.
---

# codefresh_api_key (Resource)

Manages an API Key tied to an Account and a User.
Requires a Codefresh admin token and applies only to Codefresh on-premises installations.

terraform-provider-codefresh itself uses an API key, passed as provider's attribute, but it's possible to use that API Key to generate a new one.
This resource requires Codefresh system admin permissions, hence is relevant for on-prem deployments of Codefresh only.
Manages an API Key tied to a user within an account or a service account within the current account.
On the Codefresh SaaS platfrom this resource is only usable for service accounts.
Management of API keys for users in other accounts requires admin priveleges and hence can only be done on Codefresh on-premises installations.

terraform-provider-codefresh itself uses an API key, passed as provider's attribute, but it's possible to use that API Key to generate a new one.

## Example usage

### With service accounts

```hcl
provider "codefresh" {
api_url = "my API URL"
token = "my init API token"
}
resource "codefresh_service_account" "example" {
name = "example-service-account"
}
resource "codefresh_api_key" "example" {
service_account_id = codefresh_service_account.example.id
name = "example-token"
scopes = [
"project"
]
}
provider "codefresh" {
alias = "project_creator_sa"
api_url = "my API URL"
token = codefresh_api_key.example.token
}
resource "codefresh_project" "example" {
provider = codefresh.project_creator_sa
name = "myproject"
tags = [
"team_1"
]
}
```

### With user and account combination (on-premise only)
```hcl
provider "codefresh" {
api_url = "my API URL"
Expand Down Expand Up @@ -79,12 +118,11 @@ resource "codefresh_team" "team_1" {

### Required

- `account_id` (String) The ID of account in which the API key will be created.
- `name` (String) The display name for the API key.
- `user_id` (String) The ID of a user within the referenced `account_id` that will own the API key.

### Optional

- `account_id` (String) The ID of account in which the API key will be created. Required if user_id is set.
- `scopes` (Set of String) A list of access scopes for the API key. The possible values:
* agent
* agents
Expand All @@ -104,8 +142,10 @@ resource "codefresh_team" "team_1" {
* step-types
* view
* workflow
- `service_account_id` (String) The ID of the service account to create the API key for.
- `user_id` (String) The ID of a user within the referenced `account_id` that will own the API key. Requires a Codefresh admin token and can be used only in Codefresh on-premises installations.

### Read-Only

- `id` (String) The ID of this resource.
- `token` (String, Sensitive) The resulting API key.
- `token` (String, Sensitive) The resulting API key.
50 changes: 50 additions & 0 deletions docs/resources/service_account.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
page_title: "codefresh_service_account Resource - terraform-provider-codefresh"
subcategory: ""
description: |-
A service account is an identity that provides automated processes, applications, and services with the necessary permissions to interact securely with the Codefresh platform
---

# codefresh_service_account (Resource)

A service account is an identity that provides automated processes, applications, and services with the necessary permissions to interact securely with the Codefresh platform

For more information about service accounts in Codefresh see [official documentation](https://codefresh.io/docs/docs/administration/account-user-management/service-accounts).

It is also possible to generate API tokens for service accounts, see the documentation for `codefresh_api_key` resource for usage example.

## Example Usage

```hcl
data "codefresh_team" "serviceaccounts" {
name = "service-accounts"
}
resource "codefresh_service_account" "example" {
name = "tf-test1"
assign_admin_role = true
assigned_teams = [data.codefresh_team.serviceaccounts.id]
}
```

<!-- schema generated by tfplugindocs -->
## Schema

### Required

- `name` (String) Service account display name

### Optional

- `assign_admin_role` (Boolean) Whether or not to assign account admin role to the service account
- `assigned_teams` (Set of String) A list of team IDs the service account is be assigned to

### Read-Only

- `id` (String) The ID of this resource.

## Import

```sh
terraform import codefresh_service_account.test xxxxxxxxxxxxxxxxxxx
```
Loading

0 comments on commit 1654c4e

Please sign in to comment.