feat: refactor user data source and resource schemas to utilize shared models

This commit is contained in:
Andre_Harms 2026-02-05 16:24:06 +01:00
parent bac8ebe236
commit 5d92c9b460
6 changed files with 86 additions and 1663 deletions

View file

@ -2,36 +2,27 @@ package postgresflexalpha
import (
"context"
_ "embed"
"errors"
"fmt"
"math"
"net/http"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
postgresflex "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
postgresflexalpha "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/user/resources_gen"
postgresflexUtils "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/utils"
postgresflex "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
"github.com/hashicorp/terraform-plugin-framework-validators/setvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/conversion"
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/core"
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils"
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/validate"
"github.com/hashicorp/terraform-plugin-framework/attr"
"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"
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
)
// Ensure the implementation satisfies the expected interfaces.
@ -43,18 +34,8 @@ var (
)
type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
UserId types.Int64 `tfsdk:"user_id"`
InstanceId types.String `tfsdk:"instance_id"`
ProjectId types.String `tfsdk:"project_id"`
Username types.String `tfsdk:"username"`
Roles types.Set `tfsdk:"roles"`
Password types.String `tfsdk:"password"`
Host types.String `tfsdk:"host"`
Port types.Int64 `tfsdk:"port"`
Region types.String `tfsdk:"region"`
Status types.String `tfsdk:"status"`
ConnectionString types.String `tfsdk:"connection_string"`
postgresflexalpha.UserModel
TerraformID types.String `tfsdk:"id"`
}
// NewUserResource is a helper function to simplify the provider implementation.
@ -123,117 +104,30 @@ func (r *userResource) Configure(ctx context.Context, req resource.ConfigureRequ
tflog.Info(ctx, "Postgres Flex user client configured")
}
//go:embed planModifiers.yaml
var modifiersFileByte []byte
// Schema defines the schema for the resource.
func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
rolesOptions := []string{"login", "createdb", "createrole"}
descriptions := map[string]string{
"main": "Postgres Flex user resource schema. Must have a `region` specified in the provider configuration.",
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`instance_id`,`user_id`\".",
"user_id": "User ID.",
"instance_id": "ID of the PostgresFlex instance.",
"project_id": "STACKIT project ID to which the instance is associated.",
"username": "The name of the user.",
"roles": "Database access levels for the user. " + utils.FormatPossibleValues(rolesOptions...),
"region": "The resource region. If not defined, the provider region is used.",
"status": "The current status of the user.",
"password": "The password for the user. This is only set upon creation.",
"host": "The host of the Postgres Flex instance.",
"port": "The port of the Postgres Flex instance.",
"connection_string": "The connection string for the user to the instance.",
func (r *userResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
s := postgresflexalpha.UserResourceSchema(ctx)
s.Attributes["id"] = schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \\\"`project_id`,`region`,`instance_id`,`database_id`\\\".\",",
Optional: true,
Computed: true,
}
resp.Schema = schema.Schema{
Description: descriptions["main"],
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: descriptions["id"],
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"user_id": schema.Int64Attribute{
Description: descriptions["user_id"],
Computed: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
Validators: []validator.Int64{},
},
"instance_id": schema.StringAttribute{
Description: descriptions["instance_id"],
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"project_id": schema.StringAttribute{
Description: descriptions["project_id"],
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"username": schema.StringAttribute{
Description: descriptions["username"],
Required: true,
PlanModifiers: []planmodifier.String{
// stringplanmodifier.RequiresReplace(),
},
},
"roles": schema.SetAttribute{
Description: descriptions["roles"],
ElementType: types.StringType,
Required: true,
Validators: []validator.Set{
setvalidator.ValueStringsAre(
stringvalidator.OneOf(rolesOptions...),
),
},
},
"password": schema.StringAttribute{
Description: descriptions["password"],
Computed: true,
Sensitive: true,
},
"host": schema.StringAttribute{
Description: descriptions["host"],
Computed: true,
},
"port": schema.Int64Attribute{
Description: descriptions["port"],
Computed: true,
},
"region": schema.StringAttribute{
Optional: true,
// must be computed to allow for storing the override value from the provider
Computed: true,
Description: descriptions["region"],
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"status": schema.StringAttribute{
Description: descriptions["status"],
Computed: true,
},
"connection_string": schema.StringAttribute{
Description: descriptions["connection_string"],
Computed: true,
},
},
fields, err := postgresflexUtils.ReadModifiersConfig(modifiersFileByte)
if err != nil {
resp.Diagnostics.AddError("error during read modifiers config file", err.Error())
return
}
err = postgresflexUtils.AddPlanModifiersToResourceSchema(fields, &s)
if err != nil {
resp.Diagnostics.AddError("error adding plan modifiers", err.Error())
return
}
resp.Schema = s
}
// Create creates the resource and sets the initial Terraform state.
@ -277,8 +171,6 @@ func (r *userResource) Create(
return
}
ctx = core.LogResponse(ctx)
if userResp.Id == nil || *userResp.Id == 0 {
core.LogAndAddError(
ctx,
@ -288,11 +180,14 @@ func (r *userResource) Create(
)
return
}
model.Id = types.Int64PointerValue(userResp.Id)
model.UserId = types.Int64PointerValue(userResp.Id)
model.Password = types.StringPointerValue(userResp.Password)
ctx = tflog.SetField(ctx, "user_id", *userResp.Id)
ctx = core.LogResponse(ctx)
exists, err := r.getUserResource(ctx, &model)
if err != nil {
@ -585,7 +480,7 @@ func (r *userResource) getUserResource(ctx context.Context, model *Model) (bool,
return false, fmt.Errorf("error fetching user resource: %w", err)
}
if err := mapFields(userResp, model, arg.region); err != nil {
if err := mapResourceFields(userResp, model, arg.region); err != nil {
return false, fmt.Errorf("error mapping user resource: %w", err)
}
@ -615,13 +510,13 @@ func (r *userResource) setTFLogFields(ctx context.Context, model *Model) context
ctx = tflog.SetField(ctx, "project_id", usrCtx.projectId)
ctx = tflog.SetField(ctx, "instance_id", usrCtx.instanceId)
ctx = tflog.SetField(ctx, "user_id", usrCtx.userId)
ctx = tflog.SetField(ctx, "region", usrCtx.region)
ctx = tflog.SetField(ctx, "user_id", usrCtx.userId)
return ctx
}
func (r *userResource) expandRoles(ctx context.Context, rolesSet types.Set, diags *diag.Diagnostics) []string {
func (r *userResource) expandRoles(ctx context.Context, rolesSet types.List, diags *diag.Diagnostics) []string {
if rolesSet.IsNull() || rolesSet.IsUnknown() {
return nil
}
@ -629,42 +524,3 @@ func (r *userResource) expandRoles(ctx context.Context, rolesSet types.Set, diag
diags.Append(rolesSet.ElementsAs(ctx, &roles, false)...)
return roles
}
func toCreatePayload(model *Model, roles *[]string) (*postgresflex.CreateUserRequestPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
if roles == nil {
return nil, fmt.Errorf("nil roles")
}
return &postgresflex.CreateUserRequestPayload{
Roles: toPayloadRoles(roles),
Name: conversion.StringValueToPointer(model.Username),
}, nil
}
func toPayloadRoles(roles *[]string) *[]postgresflex.UserRole {
var userRoles = make([]postgresflex.UserRole, 0, len(*roles))
for _, role := range *roles {
userRoles = append(userRoles, postgresflex.UserRole(role))
}
return &userRoles
}
func toUpdatePayload(model *Model, roles *[]string) (
*postgresflex.UpdateUserRequestPayload,
error,
) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
if roles == nil {
return nil, fmt.Errorf("nil roles")
}
return &postgresflex.UpdateUserRequestPayload{
Name: conversion.StringValueToPointer(model.Username),
Roles: toPayloadRoles(roles),
}, nil
}