Skip to content

Commit

Permalink
CRaaS V1: add token resource (#232)
Browse files Browse the repository at this point in the history
Implement `selectel_craas_token_v1` resource with acceptance test.

Update the documentation.
  • Loading branch information
kolsean authored Jun 29, 2023
1 parent 6b24114 commit 91a568f
Show file tree
Hide file tree
Showing 6 changed files with 329 additions and 1 deletion.
5 changes: 4 additions & 1 deletion selectel/craas.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import (
"github.com/selectel/craas-go/pkg/v1/registry"
)

const craasV1Endpoint = "https://cr.selcloud.ru/api/v1"
const (
craasV1Endpoint = "https://cr.selcloud.ru/api/v1"
craasV1TokenUsername = "token"
)

func waitForCRaaSRegistryV1StableState(
ctx context.Context, client *v1.ServiceClient, registryID string, timeout time.Duration,
Expand Down
2 changes: 2 additions & 0 deletions selectel/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const (
objectAdmissionControllers = "admission-controllers"
objectLogicalReplicationSlot = "logical-replication-slot"
objectRegistry = "registry"
objectRegistryToken = "registry token"
)

// This is a global MutexKV for use within this plugin.
Expand Down Expand Up @@ -112,6 +113,7 @@ func Provider() *schema.Provider {
"selectel_dbaas_prometheus_metric_token_v1": resourceDBaaSPrometheusMetricTokenV1(),
"selectel_dbaas_postgresql_logical_replication_slot_v1": resourceDBaaSPostgreSQLLogicalReplicationSlotV1(),
"selectel_craas_registry_v1": resourceCRaaSRegistryV1(),
"selectel_craas_token_v1": resourceCRaaSTokenV1(),
},
ConfigureContextFunc: configureProvider,
}
Expand Down
141 changes: 141 additions & 0 deletions selectel/resource_selectel_craas_token_v1.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package selectel

import (
"context"
"log"
"net/http"
"strconv"

"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"
v1 "github.com/selectel/craas-go/pkg"
"github.com/selectel/craas-go/pkg/v1/token"
"github.com/selectel/go-selvpcclient/v2/selvpcclient/resell/v2/tokens"
"github.com/terraform-providers/terraform-provider-selectel/selectel/internal/hashcode"
)

func resourceCRaaSTokenV1() *schema.Resource {
return &schema.Resource{
CreateContext: resourceCRaaSTokenV1Create,
ReadContext: resourceCRaaSTokenV1Read,
DeleteContext: resourceCRaaSTokenV1Delete,
Schema: map[string]*schema.Schema{
"project_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"token_ttl": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(token.TTL12Hours),
string(token.TTL1Year),
}, false),
Default: string(token.TTL1Year),
},
"username": {
Type: schema.TypeString,
Sensitive: true,
Computed: true,
},
"token": {
Type: schema.TypeString,
Sensitive: true,
Computed: true,
},
},
}
}

func resourceCRaaSTokenV1Create(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(*Config)
resellV2Client := config.resellV2Client()
selTokenOpts := tokens.TokenOpts{
ProjectID: d.Get("project_id").(string),
}

log.Print(msgCreate(objectToken, selTokenOpts))
selToken, _, err := tokens.Create(ctx, resellV2Client, selTokenOpts)
if err != nil {
return diag.FromErr(errCreatingObject(objectToken, err))
}

craasClient := v1.NewCRaaSClientV1(selToken.ID, craasV1Endpoint)
tokenTTL := d.Get("token_ttl").(string)
createOpts := &token.CreateOpts{
TokenTTL: token.TTL(tokenTTL),
}

log.Print(msgCreate(objectRegistryToken, createOpts))
newToken, _, err := token.Create(ctx, craasClient, createOpts)
if err != nil {
return diag.FromErr(errCreatingObject(objectRegistryToken, err))
}

tokenID := strconv.Itoa(hashcode.String(newToken.Token))
d.SetId(tokenID)
d.Set("token", newToken.Token)

return resourceCRaaSTokenV1Read(ctx, d, meta)
}

func resourceCRaaSTokenV1Read(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(*Config)
resellV2Client := config.resellV2Client()
selTokenOpts := tokens.TokenOpts{
ProjectID: d.Get("project_id").(string),
}

log.Print(msgCreate(objectToken, selTokenOpts))
selToken, _, err := tokens.Create(ctx, resellV2Client, selTokenOpts)
if err != nil {
return diag.FromErr(errCreatingObject(objectToken, err))
}

craasClient := v1.NewCRaaSClientV1(selToken.ID, craasV1Endpoint)

log.Print(msgGet(objectRegistryToken, d.Id()))
craasToken, response, err := token.Get(ctx, craasClient, d.Get("token").(string))
if err != nil {
if response != nil {
if response.StatusCode == http.StatusNotFound {
d.SetId("")
return nil
}
}

return diag.FromErr(errGettingObject(objectRegistryToken, d.Id(), err))
}

d.Set("username", craasV1TokenUsername)
d.Set("token", craasToken.Token)

return nil
}

func resourceCRaaSTokenV1Delete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(*Config)
resellV2Client := config.resellV2Client()
selTokenOpts := tokens.TokenOpts{
ProjectID: d.Get("project_id").(string),
}

log.Print(msgCreate(objectToken, selTokenOpts))
selToken, _, err := tokens.Create(ctx, resellV2Client, selTokenOpts)
if err != nil {
return diag.FromErr(errCreatingObject(objectToken, err))
}

craasClient := v1.NewCRaaSClientV1(selToken.ID, craasV1Endpoint)

log.Print(msgDelete(objectRegistryToken, d.Id()))
_, err = token.Revoke(ctx, craasClient, d.Get("token").(string))
if err != nil {
return diag.FromErr(errDeletingObject(objectRegistryToken, d.Id(), err))
}

return nil
}
103 changes: 103 additions & 0 deletions selectel/resource_selectel_craas_token_v1_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package selectel

import (
"context"
"errors"
"fmt"
"testing"

"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"
v1 "github.com/selectel/craas-go/pkg"
"github.com/selectel/craas-go/pkg/v1/token"
"github.com/selectel/go-selvpcclient/v2/selvpcclient/resell/v2/projects"
"github.com/selectel/go-selvpcclient/v2/selvpcclient/resell/v2/tokens"
)

func TestAccCRaaSTokenV1Basic(t *testing.T) {
var (
project projects.Project
craasToken token.Token
)

projectName := acctest.RandomWithPrefix("tf-acc")

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccSelectelPreCheck(t) },
ProviderFactories: testAccProviders,
CheckDestroy: testAccCheckVPCV2ProjectDestroy,
Steps: []resource.TestStep{
{
Config: testAccCRaaSTokenV1Basic(projectName),
Check: resource.ComposeTestCheckFunc(
testAccCheckVPCV2ProjectExists("selectel_vpc_project_v2.project_tf_acc_test_1", &project),
testAccCheckCRaaSTokenV1Exists("selectel_craas_token_v1.token_tf_acc_test_1", &craasToken),
resource.TestCheckResourceAttr("selectel_craas_token_v1.token_tf_acc_test_1", "token_ttl", "1y"),
resource.TestCheckResourceAttr("selectel_craas_token_v1.token_tf_acc_test_1", "username", "token"),
),
},
},
})
}

func testAccCheckCRaaSTokenV1Exists(n string, craasToken *token.Token) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("not found: %s", n)
}

if rs.Primary.ID == "" {
return errors.New("no ID is set")
}

var projectID string
if id, ok := rs.Primary.Attributes["project_id"]; ok {
projectID = id
}

var tokenID string
if t, ok := rs.Primary.Attributes["token"]; ok {
tokenID = t
}

config := testAccProvider.Meta().(*Config)
resellV2Client := config.resellV2Client()
ctx := context.Background()

selTokenOpts := tokens.TokenOpts{
ProjectID: projectID,
}
selToken, _, err := tokens.Create(ctx, resellV2Client, selTokenOpts)
if err != nil {
return errCreatingObject(objectToken, err)
}

craasClient := v1.NewCRaaSClientV1(selToken.ID, craasV1Endpoint)
foundToken, _, err := token.Get(ctx, craasClient, tokenID)
if err != nil {
return err
}

if foundToken.Token != tokenID {
return errors.New("token not found")
}

*craasToken = *foundToken

return nil
}
}

func testAccCRaaSTokenV1Basic(projectName string) string {
return fmt.Sprintf(`
resource "selectel_vpc_project_v2" "project_tf_acc_test_1" {
name = "%s"
}
resource "selectel_craas_token_v1" "token_tf_acc_test_1" {
project_id = selectel_vpc_project_v2.project_tf_acc_test_1.id
}
`, projectName)
}
76 changes: 76 additions & 0 deletions website/docs/r/craas_token_v1.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
---
layout: "selectel"
page_title: "Selectel: selectel_craas_token_v1"
sidebar_current: "docs-selectel-resource-craas-token-v1"
description: |-
Manages a V1 token resource within Selectel Container Registry Service.
---

# selectel\_craas\_token\_v1

Manages a V1 token resource within Selectel Container Registry Service.

## Basic usage example

```hcl
resource "selectel_vpc_project_v2" "project_1" {
name = "my-first-project"
}
resource "selectel_craas_token_v1" "token_1" {
project_id = selectel_vpc_project_v2.project_1.id
}
```

## Docker CLI login example

```hcl
resource "selectel_vpc_project_v2" "project_1" {
name = "my-first-project"
}
resource "selectel_craas_token_v1" "token_1" {
project_id = selectel_vpc_project_v2.project_1.id
}
output "registry_username" {
value = selectel_craas_token_v1.token_1.username
sensitive = true
}
output "registry_token" {
value = selectel_craas_token_v1.token_1.token
sensitive = true
}
```

```shell
REGISTRY_USERNAME=$(terraform output -raw registry_username)
REGISTRY_TOKEN=$(terraform output -raw registry_token)
echo $REGISTRY_TOKEN | docker login cr.selcloud.ru --username $REGISTRY_USERNAME --password-stdin
```

## Argument Reference

The following arguments are supported:

* `project_id` - (Required) An associated Selectel VPC project.
Changing this creates a new token.

* `token_ttl` - (Optional) Represents token expiration duration.
Accepts "1y" or "12h". Default is "1y".
Changing this creates a new token.

## Attributes Reference

The following attributes are exported:

* `username` - Contains a username to access container registry.
Sensitive value.

* `token` - Contains a token to access container registry.
Sensitive value.

## Import

Token resource import is not supported.
3 changes: 3 additions & 0 deletions website/selectel.erb
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,9 @@
<li<%= sidebar_current("docs-selectel-resource-craas-registry-v1") %>>
<a href="/docs/providers/selectel/r/craas_registry_v1.html">selectel_craas_registry_v1</a>
</li>
<li<%= sidebar_current("docs-selectel-resource-craas-token-v1") %>>
<a href="/docs/providers/selectel/r/craas_token_v1.html">selectel_craas_token_v1</a>
</li>
</ul>
</li>

Expand Down

0 comments on commit 91a568f

Please sign in to comment.