Complete rewrite of the VirtFusion Terraform provider with full API coverage: - 20 managed resources (server, build, SSH key, user, firewall, IP blocks, etc.) - 30 data sources (hypervisors, packages, servers, IP blocks, self-service, etc.) - New HTTP client with proper error handling, query parameter support, and automatic multipage pagination via GetAllPages (fetches all pages from Laravel-style paginated endpoints and merges into a single response) - Fixed type mismatches against live API: ServerData.Suspended (int→bool), IPBlockData.Type (string→int), PackageData json tags (primaryStorage, etc.), ServerData nested CPU/Settings/Resources structure, HypervisorGroupResources array response - Configurable results-per-page (default 300) on all list data sources - Migrated CI from GitHub Actions to Gitea Actions - Updated goreleaser config, go.mod dependencies, and examples Verified against live VirtFusion instance at cp.vps.ezscale.tech: all data sources return correct data with full pagination support. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
195 lines
6.9 KiB
Go
195 lines
6.9 KiB
Go
// Copyright (c) EZSCALE.
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
package provider
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"time"
|
|
|
|
"terraform-provider-virtfusion/internal/client"
|
|
|
|
"github.com/hashicorp/terraform-plugin-framework/path"
|
|
"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"
|
|
)
|
|
|
|
// Ensure provider-defined types fully satisfy framework interfaces.
|
|
var (
|
|
_ resource.Resource = &UserServerAuthTokenResource{}
|
|
_ resource.ResourceWithConfigure = &UserServerAuthTokenResource{}
|
|
)
|
|
|
|
// NewUserServerAuthTokenResource creates a new user server auth token resource.
|
|
func NewUserServerAuthTokenResource() resource.Resource {
|
|
return &UserServerAuthTokenResource{}
|
|
}
|
|
|
|
// UserServerAuthTokenResource defines the resource implementation.
|
|
type UserServerAuthTokenResource struct {
|
|
client *client.Client
|
|
}
|
|
|
|
// UserServerAuthTokenResourceModel describes the resource data model.
|
|
type UserServerAuthTokenResourceModel struct {
|
|
ID types.String `tfsdk:"id"`
|
|
ExtRelationID types.String `tfsdk:"ext_relation_id"`
|
|
ServerID types.Int64 `tfsdk:"server_id"`
|
|
Token types.String `tfsdk:"token"`
|
|
URL types.String `tfsdk:"url"`
|
|
Triggers types.Map `tfsdk:"triggers"`
|
|
}
|
|
|
|
func (r *UserServerAuthTokenResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
|
resp.TypeName = req.ProviderTypeName + "_user_server_auth_token"
|
|
}
|
|
|
|
func (r *UserServerAuthTokenResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
|
resp.Schema = schema.Schema{
|
|
MarkdownDescription: "Generates a server-scoped authentication token for a VirtFusion user. This is a trigger-style resource — the token is generated on create and can be re-generated by changing the `triggers` attribute.",
|
|
Attributes: map[string]schema.Attribute{
|
|
"id": schema.StringAttribute{
|
|
MarkdownDescription: "The identifier for this server auth token generation.",
|
|
Computed: true,
|
|
PlanModifiers: []planmodifier.String{
|
|
stringplanmodifier.UseStateForUnknown(),
|
|
},
|
|
},
|
|
"ext_relation_id": schema.StringAttribute{
|
|
MarkdownDescription: "The external relation ID of the user to generate the server auth token for.",
|
|
Required: true,
|
|
},
|
|
"server_id": schema.Int64Attribute{
|
|
MarkdownDescription: "The ID of the server to scope the auth token to.",
|
|
Required: true,
|
|
},
|
|
"token": schema.StringAttribute{
|
|
MarkdownDescription: "The generated server authentication token.",
|
|
Computed: true,
|
|
Sensitive: true,
|
|
PlanModifiers: []planmodifier.String{
|
|
stringplanmodifier.UseStateForUnknown(),
|
|
},
|
|
},
|
|
"url": schema.StringAttribute{
|
|
MarkdownDescription: "The authentication URL for the generated server token.",
|
|
Computed: true,
|
|
PlanModifiers: []planmodifier.String{
|
|
stringplanmodifier.UseStateForUnknown(),
|
|
},
|
|
},
|
|
"triggers": schema.MapAttribute{
|
|
MarkdownDescription: "A map of arbitrary strings that, when changed, will cause the server auth token to be re-generated. Works like `triggers` in `terraform_data`.",
|
|
ElementType: types.StringType,
|
|
Optional: true,
|
|
PlanModifiers: []planmodifier.Map{
|
|
mapplanmodifier.RequiresReplace(),
|
|
},
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
func (r *UserServerAuthTokenResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
|
if req.ProviderData == nil {
|
|
return
|
|
}
|
|
|
|
c, ok := req.ProviderData.(*client.Client)
|
|
if !ok {
|
|
resp.Diagnostics.AddError(
|
|
"Unexpected Resource Configure Type",
|
|
fmt.Sprintf("Expected *client.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
|
|
)
|
|
return
|
|
}
|
|
|
|
r.client = c
|
|
}
|
|
|
|
func (r *UserServerAuthTokenResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
|
var data UserServerAuthTokenResourceModel
|
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
apiPath := fmt.Sprintf("/users/%s/serverAuthenticationTokens/%d", data.ExtRelationID.ValueString(), data.ServerID.ValueInt64())
|
|
rawResp, err := r.client.Post(ctx, apiPath, nil)
|
|
if err != nil {
|
|
resp.Diagnostics.AddError(
|
|
"Error Generating User Server Auth Token",
|
|
fmt.Sprintf("Could not generate server auth token for user %q on server %d: %s", data.ExtRelationID.ValueString(), data.ServerID.ValueInt64(), err),
|
|
)
|
|
return
|
|
}
|
|
|
|
// Parse the response for the token and URL.
|
|
if rawResp != nil {
|
|
var tokenResp client.AuthTokenResponse
|
|
if jsonErr := json.Unmarshal(rawResp, &tokenResp); jsonErr == nil {
|
|
data.Token = types.StringValue(tokenResp.Data.Token)
|
|
data.URL = types.StringValue(tokenResp.Data.URL)
|
|
} else {
|
|
data.Token = types.StringValue("")
|
|
data.URL = types.StringValue("")
|
|
}
|
|
} else {
|
|
data.Token = types.StringValue("")
|
|
data.URL = types.StringValue("")
|
|
}
|
|
|
|
data.ID = types.StringValue(fmt.Sprintf("%s-%d-%d", data.ExtRelationID.ValueString(), data.ServerID.ValueInt64(), time.Now().UnixNano()))
|
|
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
|
|
}
|
|
|
|
func (r *UserServerAuthTokenResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
|
var data UserServerAuthTokenResourceModel
|
|
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
// Return stored state as-is for trigger-style resources.
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
|
|
}
|
|
|
|
func (r *UserServerAuthTokenResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
|
var data UserServerAuthTokenResourceModel
|
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
|
|
}
|
|
|
|
func (r *UserServerAuthTokenResource) Delete(_ context.Context, _ resource.DeleteRequest, _ *resource.DeleteResponse) {
|
|
// No-op: server auth tokens cannot be revoked via this resource. Removing from state only.
|
|
}
|
|
|
|
// ValidateConfig validates the resource configuration.
|
|
func (r *UserServerAuthTokenResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
|
|
var data UserServerAuthTokenResourceModel
|
|
resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
// Validate server_id is positive.
|
|
if !data.ServerID.IsNull() && !data.ServerID.IsUnknown() && data.ServerID.ValueInt64() <= 0 {
|
|
resp.Diagnostics.AddAttributeError(
|
|
path.Root("server_id"),
|
|
"Invalid Server ID",
|
|
"server_id must be a positive integer.",
|
|
)
|
|
}
|
|
}
|