package account import ( "context" "strconv" "time" "github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts" "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/types" "github.com/hashicorp/terraform-plugin-log/tflog" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" "repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client" "repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants" "repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/account/flattens" "repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/account/models" "repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/account/schemas" "repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/account/utilities" ) // Ensure the implementation satisfies the expected interfaces. var ( _ resource.Resource = &resourceAccount{} _ resource.ResourceWithImportState = &resourceAccount{} ) // NewResourceAccount is a helper function to simplify the provider implementation. func NewResourceAccount() resource.Resource { return &resourceAccount{} } // resourceAccount is the resource implementation. type resourceAccount struct { client *client.Client } // Create creates the resource and sets the initial Terraform state. func (r *resourceAccount) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { resp.Diagnostics.AddError( "Only users with admin privileges are able to create accounts. Contact your platform administrator or import existing account.", "Use 'terraform import dynamix_account. ' command to import existing account configuration", ) return } // Read refreshes the Terraform state with the latest data. func (r *resourceAccount) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // Get current state var state models.ResourceAccountModel resp.Diagnostics.Append(req.State.Get(ctx, &state)...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Read resourceAccount: Error get state") return } tflog.Info(ctx, "Read resourceAccount: got state successfully", map[string]any{"account_id": state.Id.ValueString()}) // Set timeouts readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout300s) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Read resourceAccount: Error set timeout") return } tflog.Info(ctx, "Read resourceAccount: set timeouts successfully", map[string]any{ "account_id": state.Id.ValueString(), "readTimeout": readTimeout}) ctx, cancel := context.WithTimeout(ctx, readTimeout) defer cancel() // read status resp.Diagnostics.Append(utilities.AccountReadStatus(ctx, &state, r.client)...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Read resourceAccount: Error reading status") return } // Overwrite items with refreshed state resp.Diagnostics.Append(flattens.AccountResource(ctx, &state, r.client)...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Read resourceAccount: Error flatten") return } // Set refreshed state resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Read resourceAccount: Error set state") return } tflog.Info(ctx, "End read resourceAccount") } // Update updates the resource and sets the updated Terraform state on success. func (r *resourceAccount) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // Retrieve values from plan var plan models.ResourceAccountModel resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Update resourceAccount: Error receiving the plan") return } logMap := map[string]any{"account_id": plan.Id.ValueString()} tflog.Info(ctx, "Update resourceAccount: got plan successfully", logMap) // Retrieve values from state var state models.ResourceAccountModel resp.Diagnostics.Append(req.State.Get(ctx, &state)...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Update resourceAccount: Error receiving the state") return } tflog.Info(ctx, "Update resourceAccount: got state successfully", logMap) // Set timeouts updateTimeout, diags := plan.Timeouts.Update(ctx, constants.Timeout300s) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Update resourceAccount: Error set timeout") return } tflog.Info(ctx, "Update resourceAccount: set timeouts successfully", map[string]any{ "account_id": state.Id.ValueString(), "updateTimeout": updateTimeout}) ctx, cancel := context.WithTimeout(ctx, updateTimeout) defer cancel() accountId, err := strconv.Atoi(state.Id.ValueString()) if err != nil { resp.Diagnostics.AddError("Update resourceAccount: Cannot parse ID from state", err.Error()) return } // enable/disable account if !plan.Enable.Equal(state.Enable) && !plan.Enable.IsNull() { resp.Diagnostics.Append(utilities.EnableDisableAccount(ctx, uint64(accountId), plan.Enable.ValueBool(), r.client)...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Update resourceAccount: Error enabling/disabling account") return } } // general update account resp.Diagnostics.Append(utilities.UpdateAccount(ctx, uint64(accountId), &plan, &state, r.client)...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Update resourceAccount: Error with general account update") return } // add/delete users if !plan.Users.Equal(state.Users) { resp.Diagnostics.Append(utilities.AddDeleteUsersAccount(ctx, uint64(accountId), &plan, &state, r.client)...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Update resourceAccount: Error adding/deleting users to/from account") return } } tflog.Info(ctx, "Update resourceAccount: account update is completed", logMap) // Map response body to schema and populate Computed attribute values resp.Diagnostics.Append(flattens.AccountResource(ctx, &plan, r.client)...) if resp.Diagnostics.HasError() { return } // Set data last update plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850)) // Set state to fully populated data resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) if resp.Diagnostics.HasError() { return } } // Delete deletes the resource and removes the Terraform state on success. func (r *resourceAccount) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // Get current state var state models.ResourceAccountModel resp.Diagnostics.Append(req.State.Get(ctx, &state)...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Delete resourceAccount: Error get state") return } tflog.Info(ctx, "Delete resourceAccount: got state successfully", map[string]any{"account_id": state.Id.ValueString()}) // Set timeouts deleteTimeout, diags := state.Timeouts.Delete(ctx, constants.Timeout300s) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { tflog.Error(ctx, "Delete resourceAccount: Error set timeout") return } tflog.Info(ctx, "Delete resourceAccount: set timeouts successfully", map[string]any{ "account_id": state.Id.ValueString(), "deleteTimeout": deleteTimeout}) ctx, cancel := context.WithTimeout(ctx, deleteTimeout) defer cancel() permanently := state.Permanently.ValueBool() if state.Permanently.IsNull() { permanently = true } // default true // Delete existing resource group delReq := account.DeleteRequest{ AccountID: uint64(state.AccountID.ValueInt64()), Permanently: permanently, } tflog.Info(ctx, "Delete resourceAccount: before call CloudAPI().Account().Delete", map[string]any{"req": delReq}) _, err := r.client.CloudAPI().Account().Delete(ctx, delReq) if err != nil { resp.Diagnostics.AddError("Delete resourceAccount: Error deleting account with error: ", err.Error()) return } tflog.Info(ctx, "End delete resourceAccount", map[string]any{"account_id": state.Id.ValueString()}) } // Schema defines the schema for the resource. func (r *resourceAccount) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { resp.Schema = schema.Schema{ Attributes: schemas.MakeSchemaResourceAccount(), Blocks: map[string]schema.Block{ "timeouts": timeouts.Block(ctx, timeouts.Opts{Create: true, Read: true, Update: true, Delete: true}), }, } } // Metadata returns the resource type name. func (r *resourceAccount) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { resp.TypeName = req.ProviderTypeName + "_account" } // Configure adds the provider configured client to the resource. func (r *resourceAccount) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { tflog.Info(ctx, "Get Configure resourceAccount") r.client = client.Resource(ctx, &req, resp) tflog.Info(ctx, "Getting Configure resourceAccount successfully") } func (r *resourceAccount) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { // Retrieve import ID and save to id attribute resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) }