// Copyright (c) EZSCALE. // SPDX-License-Identifier: MPL-2.0 package provider import ( "context" "errors" "fmt" "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/booldefault" "github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/listplanmodifier" "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 = &ServerBuildResource{} _ resource.ResourceWithConfigure = &ServerBuildResource{} ) // NewServerBuildResource creates a new server build resource. func NewServerBuildResource() resource.Resource { return &ServerBuildResource{} } // ServerBuildResource defines the resource implementation. type ServerBuildResource struct { client *client.Client } // ServerBuildResourceModel describes the resource data model. type ServerBuildResourceModel struct { ID types.String `tfsdk:"id"` ServerID types.Int64 `tfsdk:"server_id"` Name types.String `tfsdk:"name"` Hostname types.String `tfsdk:"hostname"` OSID types.Int64 `tfsdk:"osid"` VNC types.Bool `tfsdk:"vnc"` Ipv6 types.Bool `tfsdk:"ipv6"` SSHKeys types.List `tfsdk:"ssh_keys"` Email types.Bool `tfsdk:"email"` } func (r *ServerBuildResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { resp.TypeName = req.ProviderTypeName + "_server_build" } func (r *ServerBuildResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { resp.Schema = schema.Schema{ MarkdownDescription: "Builds a VirtFusion server with an operating system. This is a one-time operation — once a server is built, it stays built.", Attributes: map[string]schema.Attribute{ "id": schema.StringAttribute{ MarkdownDescription: "The identifier of the server build (same as server_id).", Computed: true, PlanModifiers: []planmodifier.String{ stringplanmodifier.UseStateForUnknown(), }, }, "server_id": schema.Int64Attribute{ MarkdownDescription: "The ID of the server to build.", Required: true, PlanModifiers: []planmodifier.Int64{ int64planmodifier.RequiresReplace(), }, }, "name": schema.StringAttribute{ MarkdownDescription: "The name for the server build.", Required: true, PlanModifiers: []planmodifier.String{ stringplanmodifier.RequiresReplace(), }, }, "osid": schema.Int64Attribute{ MarkdownDescription: "The operating system ID to install.", Required: true, PlanModifiers: []planmodifier.Int64{ int64planmodifier.RequiresReplace(), }, }, "hostname": schema.StringAttribute{ MarkdownDescription: "The hostname for the server.", Optional: true, PlanModifiers: []planmodifier.String{ stringplanmodifier.RequiresReplace(), }, }, "vnc": schema.BoolAttribute{ MarkdownDescription: "Whether to enable VNC access.", Optional: true, Computed: true, Default: booldefault.StaticBool(false), PlanModifiers: []planmodifier.Bool{ boolplanmodifier.RequiresReplace(), }, }, "ipv6": schema.BoolAttribute{ MarkdownDescription: "Whether to enable IPv6.", Optional: true, Computed: true, Default: booldefault.StaticBool(false), PlanModifiers: []planmodifier.Bool{ boolplanmodifier.RequiresReplace(), }, }, "ssh_keys": schema.ListAttribute{ MarkdownDescription: "List of SSH key IDs to add to the server.", Optional: true, ElementType: types.Int64Type, PlanModifiers: []planmodifier.List{ listplanmodifier.RequiresReplace(), }, }, "email": schema.BoolAttribute{ MarkdownDescription: "Whether to send a notification email after build.", Optional: true, Computed: true, Default: booldefault.StaticBool(false), PlanModifiers: []planmodifier.Bool{ boolplanmodifier.RequiresReplace(), }, }, }, } } func (r *ServerBuildResource) 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 *ServerBuildResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { var data ServerBuildResourceModel resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } // Build the API request body. buildReq := client.ServerBuildRequest{ Name: data.Name.ValueString(), OperatingSystemID: data.OSID.ValueInt64(), VNC: data.VNC.ValueBool(), Ipv6: data.Ipv6.ValueBool(), Email: data.Email.ValueBool(), } if !data.Hostname.IsNull() && !data.Hostname.IsUnknown() { buildReq.Hostname = data.Hostname.ValueString() } // Convert ssh_keys from types.List to []int64. if !data.SSHKeys.IsNull() && !data.SSHKeys.IsUnknown() { var sshKeys []int64 resp.Diagnostics.Append(data.SSHKeys.ElementsAs(ctx, &sshKeys, false)...) if resp.Diagnostics.HasError() { return } buildReq.SSHKeys = sshKeys } apiPath := fmt.Sprintf("/servers/%d/build", data.ServerID.ValueInt64()) _, err := r.client.Post(ctx, apiPath, buildReq) if err != nil { resp.Diagnostics.AddError( "Error Building Server", fmt.Sprintf("Could not build server %d: %s", data.ServerID.ValueInt64(), err), ) return } // Set the ID to the server_id. data.ID = types.StringValue(fmt.Sprintf("%d", data.ServerID.ValueInt64())) resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) } func (r *ServerBuildResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { var data ServerBuildResourceModel resp.Diagnostics.Append(req.State.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } // Verify the server still exists. apiPath := fmt.Sprintf("/servers/%d", data.ServerID.ValueInt64()) _, err := r.client.Get(ctx, apiPath) if err != nil { var apiErr *client.APIError if errors.As(err, &apiErr) && apiErr.IsNotFound() { // Server no longer exists, remove from state. resp.State.RemoveResource(ctx) return } resp.Diagnostics.AddError( "Error Reading Server", fmt.Sprintf("Could not read server %d: %s", data.ServerID.ValueInt64(), err), ) return } resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) } func (r *ServerBuildResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { var data ServerBuildResourceModel resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) } func (r *ServerBuildResource) Delete(_ context.Context, _ resource.DeleteRequest, _ *resource.DeleteResponse) { // No-op: building a server is not reversible. Removing from state only. } // ValidateConfig validates the resource configuration. func (r *ServerBuildResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) { var data ServerBuildResourceModel 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.", ) } // Validate osid is positive. if !data.OSID.IsNull() && !data.OSID.IsUnknown() && data.OSID.ValueInt64() <= 0 { resp.Diagnostics.AddAttributeError( path.Root("osid"), "Invalid OS ID", "osid must be a positive integer.", ) } }