Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
6 changes: 3 additions & 3 deletions internal/provider/license_resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func TestAccLicenseResource(t *testing.T) {
t.Skip("No license found for license resource tests, skipping")
}

cfg1 := testAccLicenseResourceconfig{
cfg1 := testAccLicenseResourceConfig{
URL: client.URL.String(),
Token: client.SessionToken(),
License: license,
Expand All @@ -42,13 +42,13 @@ func TestAccLicenseResource(t *testing.T) {
})
}

type testAccLicenseResourceconfig struct {
type testAccLicenseResourceConfig struct {
URL string
Token string
License string
}

func (c testAccLicenseResourceconfig) String(t *testing.T) string {
func (c testAccLicenseResourceConfig) String(t *testing.T) string {
t.Helper()
tpl := `
provider coderd {
Expand Down
1 change: 1 addition & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ func (p *CoderdProvider) Resources(ctx context.Context) []func() resource.Resour
NewWorkspaceProxyResource,
NewLicenseResource,
NewOrganizationResource,
NewProvisionerKeyResource,
}
}

Expand Down
153 changes: 153 additions & 0 deletions internal/provider/provisioner_key_resource.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package provider

import (
"context"
"fmt"

"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/mapplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"

"github.com/coder/coder/v2/codersdk"
)

// Ensure provider defined types fully satisfy framework interfaces.
var _ resource.Resource = &ProvisionerKeyResource{}

func NewProvisionerKeyResource() resource.Resource {
return &ProvisionerKeyResource{}
}

// ProvisionerKeyResource defines the resource implementation.
type ProvisionerKeyResource struct {
*CoderdProviderData
}

// ProvisionerKeyResourceModel describes the resource data model.
type ProvisionerKeyResourceModel struct {
OrganizationID UUID `tfsdk:"organization_id"`
Name types.String `tfsdk:"name"`
Tags types.Map `tfsdk:"tags"`
Key types.String `tfsdk:"key"`
}

func (r *ProvisionerKeyResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_provisioner_key"
}

func (r *ProvisionerKeyResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "A provisioner key for a Coder deployment.",

Attributes: map[string]schema.Attribute{
"organization_id": schema.StringAttribute{
CustomType: UUIDType,
MarkdownDescription: "The organization that provisioners connected with this key will be connected to.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"name": schema.StringAttribute{
MarkdownDescription: "The name of the key.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"tags": schema.MapAttribute{
ElementType: types.StringType,
Optional: true,
MarkdownDescription: "The tags that the provisioner will accept jobs for.",
PlanModifiers: []planmodifier.Map{
mapplanmodifier.RequiresReplace(),
},
},
"key": schema.StringAttribute{
MarkdownDescription: "A provisionerkey key for Coder.",
Computed: true,
Sensitive: true,
},
},
}
}

func (r *ProvisionerKeyResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}

data, ok := req.ProviderData.(*CoderdProviderData)

if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *CoderdProviderData, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)

return
}

r.CoderdProviderData = data
}

func (r *ProvisionerKeyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
// Read Terraform plan data into the model
var data ProvisionerKeyResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}

createKeyResult, err := r.Client.CreateProvisionerKey(ctx, data.OrganizationID.ValueUUID(), codersdk.CreateProvisionerKeyRequest{
Name: data.Name.ValueString(),
Tags: map[string]string{},
})
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to create provisioner_key, got error: %s", err))
return
}

data.Key = types.StringValue(createKeyResult.Key)
// Save data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}

func (r *ProvisionerKeyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
// Read Terraform prior state data into the model
var data ProvisionerKeyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}

// Provisioner keys are immutable, no reading necessary.

// Save updated data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}

func (r *ProvisionerKeyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
// Provisioner keys are immutable, updating is always invalid.
resp.Diagnostics.Append(diag.NewErrorDiagnostic("invalid update", "terraform is attempting to update a resource which must be replaced"))
}

func (r *ProvisionerKeyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
// Read Terraform prior state data into the model
var data ProvisionerKeyResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}

err := r.Client.DeleteProvisionerKey(ctx, data.OrganizationID.ValueUUID(), data.Name.ValueString())
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to delete provisionerkey, got error: %s", err))
return
}
}
96 changes: 96 additions & 0 deletions internal/provider/provisioner_key_resource_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package provider

import (
"context"
"os"
"strings"
"testing"
"text/template"

"github.com/coder/terraform-provider-coderd/integration"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/stretchr/testify/require"
)

func TestAccProvisionerKeyResource(t *testing.T) {
if os.Getenv("TF_ACC") == "" {
t.Skip("Acceptance tests are disabled.")
}
ctx := context.Background()
client := integration.StartCoder(ctx, t, "license_acc", true)
orgs, err := client.Organizations(ctx)
require.NoError(t, err)
firstOrg := orgs[0].ID

license := os.Getenv("CODER_ENTERPRISE_LICENSE")
if license == "" {
t.Skip("No license found for license resource tests, skipping")
}

cfg1 := testAccProvisionerKeyResourceConfig{
URL: client.URL.String(),
Token: client.SessionToken(),

OrganizationID: firstOrg,
Name: "example-provisioner-key",
}

cfg2 := cfg1
cfg2.Name = "different-provisioner-key"
cfg2.Tags = map[string]string{
"wibble": "wobble",
}

resource.Test(t, resource.TestCase{
IsUnitTest: true,
PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
Config: cfg1.String(t),
},
{
Config: cfg2.String(t),
},
},
})
}

type testAccProvisionerKeyResourceConfig struct {
URL string
Token string

OrganizationID uuid.UUID
Name string
Tags map[string]string
}

func (c testAccProvisionerKeyResourceConfig) String(t *testing.T) string {
t.Helper()
tpl := `
provider coderd {
url = "{{.URL}}"
token = "{{.Token}}"
}

resource "coderd_provisioner_key" "test" {
organization_id = "{{.OrganizationID}}"
name = "{{.Name}}"

tags = {
{{- range $key, $value := .Tags}}
{{$key}} = "{{$value}}"
{{- end}}
}
}
`

buf := strings.Builder{}
tmpl, err := template.New("provisionerKeyResource").Parse(tpl)
require.NoError(t, err)

err = tmpl.Execute(&buf, c)
require.NoError(t, err)
return buf.String()
}