// Copyright (c) EZSCALE. // SPDX-License-Identifier: MPL-2.0 package provider import ( "context" "encoding/json" "errors" "fmt" "net/url" "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/planmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" "github.com/hashicorp/terraform-plugin-framework/types" ) var ( _ resource.Resource = &UserResource{} _ resource.ResourceWithConfigure = &UserResource{} _ resource.ResourceWithImportState = &UserResource{} ) // NewUserResource returns a new resource for managing VirtFusion users. func NewUserResource() resource.Resource { return &UserResource{} } // UserResource defines the resource implementation. type UserResource struct { client *client.Client } // UserResourceModel describes the resource data model. type UserResourceModel struct { ID types.Int64 `tfsdk:"id"` Name types.String `tfsdk:"name"` Email types.String `tfsdk:"email"` ExtRelationID types.String `tfsdk:"ext_relation_id"` Enabled types.Bool `tfsdk:"enabled"` } func (r *UserResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { resp.TypeName = req.ProviderTypeName + "_user" } func (r *UserResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { resp.Schema = schema.Schema{ MarkdownDescription: "Manages a VirtFusion user.", Attributes: map[string]schema.Attribute{ "id": schema.Int64Attribute{ MarkdownDescription: "The numeric ID of the user.", Computed: true, }, "name": schema.StringAttribute{ MarkdownDescription: "The name of the user.", Required: true, }, "email": schema.StringAttribute{ MarkdownDescription: "The email address of the user.", Required: true, }, "ext_relation_id": schema.StringAttribute{ MarkdownDescription: "The external relation ID used to look up the user. Changing this forces a new resource to be created.", Required: true, PlanModifiers: []planmodifier.String{ stringplanmodifier.RequiresReplace(), }, }, "enabled": schema.BoolAttribute{ MarkdownDescription: "Whether the user is enabled.", Computed: true, }, }, } } func (r *UserResource) 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.", req.ProviderData), ) return } r.client = c } func (r *UserResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { var data UserResourceModel resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } body := client.UserCreateRequest{ Name: data.Name.ValueString(), Email: data.Email.ValueString(), ExtRelationID: data.ExtRelationID.ValueString(), } result, err := r.client.Post(ctx, "/users", body) if err != nil { resp.Diagnostics.AddError("Error creating user", err.Error()) return } var userResp client.UserResponse if err := json.Unmarshal(result, &userResp); err != nil { resp.Diagnostics.AddError("Error parsing user response", err.Error()) return } data.ID = types.Int64Value(userResp.Data.ID) data.Name = types.StringValue(userResp.Data.Name) data.Email = types.StringValue(userResp.Data.Email) data.ExtRelationID = types.StringValue(userResp.Data.ExtRelationID) data.Enabled = types.BoolValue(userResp.Data.Enabled) resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) } func (r *UserResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { var data UserResourceModel resp.Diagnostics.Append(req.State.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } result, err := r.client.Get(ctx, fmt.Sprintf("/users/%s/byExtRelation", url.PathEscape(data.ExtRelationID.ValueString()))) if err != nil { var apiErr *client.APIError if errors.As(err, &apiErr) && apiErr.IsNotFound() { resp.State.RemoveResource(ctx) return } resp.Diagnostics.AddError("Error reading user", err.Error()) return } var userResp client.UserResponse if err := json.Unmarshal(result, &userResp); err != nil { resp.Diagnostics.AddError("Error parsing user response", err.Error()) return } data.ID = types.Int64Value(userResp.Data.ID) data.Name = types.StringValue(userResp.Data.Name) data.Email = types.StringValue(userResp.Data.Email) data.ExtRelationID = types.StringValue(userResp.Data.ExtRelationID) data.Enabled = types.BoolValue(userResp.Data.Enabled) resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) } func (r *UserResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { var data UserResourceModel resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } body := client.UserModifyRequest{ Name: data.Name.ValueString(), Email: data.Email.ValueString(), } result, err := r.client.Put(ctx, fmt.Sprintf("/users/%s/byExtRelation", url.PathEscape(data.ExtRelationID.ValueString())), body) if err != nil { resp.Diagnostics.AddError("Error updating user", err.Error()) return } var userResp client.UserResponse if err := json.Unmarshal(result, &userResp); err != nil { resp.Diagnostics.AddError("Error parsing user response", err.Error()) return } data.ID = types.Int64Value(userResp.Data.ID) data.Name = types.StringValue(userResp.Data.Name) data.Email = types.StringValue(userResp.Data.Email) data.ExtRelationID = types.StringValue(userResp.Data.ExtRelationID) data.Enabled = types.BoolValue(userResp.Data.Enabled) resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) } func (r *UserResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { var data UserResourceModel resp.Diagnostics.Append(req.State.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } _, err := r.client.Delete(ctx, fmt.Sprintf("/users/%s/byExtRelation", url.PathEscape(data.ExtRelationID.ValueString()))) if err != nil { var apiErr *client.APIError if errors.As(err, &apiErr) && apiErr.IsNotFound() { return } resp.Diagnostics.AddError("Error deleting user", err.Error()) } } func (r *UserResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { resource.ImportStatePassthroughID(ctx, path.Root("ext_relation_id"), req, resp) }