fix: fix sqlserverflexalpha
Some checks failed
CI Workflow / Check GoReleaser config (pull_request) Successful in 5s
CI Workflow / Test readiness for publishing provider (pull_request) Has been cancelled
CI Workflow / Code coverage report (pull_request) Has been cancelled
CI Workflow / CI run tests (pull_request) Has been cancelled
CI Workflow / CI run build and linting (pull_request) Has been cancelled

This commit is contained in:
Marcel S. Henselin 2026-02-13 17:23:10 +01:00
parent d90236b02e
commit 6b581aed5c
25 changed files with 1973 additions and 2504 deletions

View file

@ -5,54 +5,47 @@ import (
"fmt"
"net/http"
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/sqlserverflexalpha"
"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"
sqlserverflexUtils "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/utils"
"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"
sqlserverflexalphaPkg "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/sqlserverflexalpha"
sqlserverflexalphaGen "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/user/datasources_gen"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &userDataSource{}
)
var _ datasource.DataSource = (*userDataSource)(nil)
const errorPrefix = "[sqlserverflexalpha - User]"
// NewUserDataSource is a helper function to simplify the provider implementation.
func NewUserDataSource() datasource.DataSource {
return &userDataSource{}
}
type dataSourceModel struct {
//TODO: check generated data source for the correct types and pointers
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"`
Host types.String `tfsdk:"host"`
Port types.Int64 `tfsdk:"port"`
Region types.String `tfsdk:"region"`
Status types.String `tfsdk:"status"`
DefaultDatabase types.String `tfsdk:"default_database"`
Host types.String `tfsdk:"host"`
Id types.String `tfsdk:"id"`
InstanceId types.String `tfsdk:"instance_id"`
Port types.Int64 `tfsdk:"port"`
ProjectId types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
Roles types.List `tfsdk:"roles"`
Status types.String `tfsdk:"status"`
UserId types.Int64 `tfsdk:"user_id"`
Username types.String `tfsdk:"username"`
}
// userDataSource is the data source implementation.
type userDataSource struct {
client *sqlserverflexalpha.APIClient
client *sqlserverflexalphaPkg.APIClient
providerData core.ProviderData
}
// Metadata returns the data source type name.
func (r *userDataSource) Metadata(
func (d *userDataSource) Metadata(
_ context.Context,
req datasource.MetadataRequest,
resp *datasource.MetadataResponse,
@ -60,108 +53,31 @@ func (r *userDataSource) Metadata(
resp.TypeName = req.ProviderTypeName + "_sqlserverflexalpha_user"
}
func (d *userDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = sqlserverflexalphaGen.UserDataSourceSchema(ctx)
}
// Configure adds the provider configured client to the data source.
func (r *userDataSource) Configure(
func (d *userDataSource) Configure(
ctx context.Context,
req datasource.ConfigureRequest,
resp *datasource.ConfigureResponse,
) {
var ok bool
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
d.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
apiClient := sqlserverflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
apiClient := sqlserverflexUtils.ConfigureClient(ctx, &d.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.client = apiClient
tflog.Info(ctx, "SQLServer Flex beta user client configured")
d.client = apiClient
tflog.Info(ctx, "SQL SERVER Flex alpha database client configured")
}
// Schema defines the schema for the data source.
func (r *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
descriptions := map[string]string{
"main": "SQLServer Flex user data source schema. Must have a `region` specified in the provider configuration.",
"id": "Terraform's internal data source. ID. It is structured as \"`project_id`,`region`,`instance_id`,`user_id`\".",
"user_id": "User ID.",
"instance_id": "ID of the SQLServer Flex instance.",
"project_id": "STACKIT project ID to which the instance is associated.",
"username": "Username of the SQLServer Flex instance.",
"roles": "Database access levels for the user.",
"password": "Password of the user account.",
"region": "The resource region. If not defined, the provider region is used.",
"status": "Status of the user.",
"default_database": "Default database of the user.",
}
resp.Schema = schema.Schema{
Description: descriptions["main"],
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: descriptions["id"],
Computed: true,
},
"user_id": schema.Int64Attribute{
Description: descriptions["user_id"],
Required: true,
Validators: []validator.Int64{
int64validator.AtLeast(1),
},
},
"instance_id": schema.StringAttribute{
Description: descriptions["instance_id"],
Required: true,
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"project_id": schema.StringAttribute{
Description: descriptions["project_id"],
Required: true,
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"username": schema.StringAttribute{
Description: descriptions["username"],
Computed: true,
},
"roles": schema.SetAttribute{
Description: descriptions["roles"],
ElementType: types.StringType,
Computed: true,
},
"host": schema.StringAttribute{
Computed: true,
},
"port": schema.Int64Attribute{
Computed: true,
},
"region": schema.StringAttribute{
// the region cannot be found automatically, so it has to be passed
Optional: true,
Description: descriptions["region"],
},
"status": schema.StringAttribute{
Computed: true,
},
"default_database": schema.StringAttribute{
Computed: true,
},
},
}
}
// Read refreshes the Terraform state with the latest data.
func (r *userDataSource) Read(
ctx context.Context,
req datasource.ReadRequest,
resp *datasource.ReadResponse,
) { // nolint:gocritic // function signature required by Terraform
func (d *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var model dataSourceModel
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
@ -174,13 +90,13 @@ func (r *userDataSource) Read(
projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString()
userId := model.UserId.ValueInt64()
region := r.providerData.GetRegionWithOverride(model.Region)
region := d.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
ctx = tflog.SetField(ctx, "user_id", userId)
ctx = tflog.SetField(ctx, "region", region)
recordSetResp, err := r.client.GetUserRequest(ctx, projectId, region, instanceId, userId).Execute()
recordSetResp, err := d.client.GetUserRequest(ctx, projectId, region, instanceId, userId).Execute()
if err != nil {
utils.LogError(
ctx,
@ -221,5 +137,5 @@ func (r *userDataSource) Read(
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "SQLServer Flex alpha instance read")
tflog.Info(ctx, "SQLServer Flex beta instance read")
}

View file

@ -42,7 +42,7 @@ func mapDataSourceFields(userResp *sqlserverflexalpha.GetUserResponse, model *da
// Map roles
if user.Roles == nil {
model.Roles = types.SetNull(types.StringType)
model.Roles = types.List(types.SetNull(types.StringType))
} else {
var roles []attr.Value
for _, role := range *user.Roles {
@ -52,7 +52,7 @@ func mapDataSourceFields(userResp *sqlserverflexalpha.GetUserResponse, model *da
if diags.HasError() {
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
}
model.Roles = rolesSet
model.Roles = types.List(rolesSet)
}
// Set remaining attributes
@ -141,7 +141,7 @@ func mapFieldsCreate(userResp *sqlserverflexalpha.CreateUserResponse, model *res
if user.Roles != nil {
var roles []attr.Value
for _, role := range *user.Roles {
roles = append(roles, types.StringValue(role))
roles = append(roles, types.StringValue(string(role)))
}
rolesSet, diags := types.SetValue(types.StringType, roles)
if diags.HasError() {
@ -154,6 +154,9 @@ func mapFieldsCreate(userResp *sqlserverflexalpha.CreateUserResponse, model *res
model.Roles = types.List(types.SetNull(types.StringType))
}
model.Password = types.StringPointerValue(user.Password)
model.Uri = types.StringPointerValue(user.Uri)
model.Host = types.StringPointerValue(user.Host)
model.Port = types.Int64PointerValue(user.Port)
model.Region = types.StringValue(region)

View file

@ -30,7 +30,7 @@ func TestMapDataSourceFields(t *testing.T) {
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringNull(),
Roles: types.SetNull(types.StringType),
Roles: types.List(types.SetNull(types.StringType)),
Host: types.StringNull(),
Port: types.Int64Null(),
Region: types.StringValue(testRegion),
@ -60,12 +60,14 @@ func TestMapDataSourceFields(t *testing.T) {
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringValue("username"),
Roles: types.SetValueMust(
types.StringType, []attr.Value{
types.StringValue("role_1"),
types.StringValue("role_2"),
types.StringValue(""),
},
Roles: types.List(
types.SetValueMust(
types.StringType, []attr.Value{
types.StringValue("role_1"),
types.StringValue("role_2"),
types.StringValue(""),
},
),
),
Host: types.StringValue("host"),
Port: types.Int64Value(1234),
@ -91,7 +93,7 @@ func TestMapDataSourceFields(t *testing.T) {
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringNull(),
Roles: types.SetValueMust(types.StringType, []attr.Value{}),
Roles: types.List(types.SetValueMust(types.StringType, []attr.Value{})),
Host: types.StringNull(),
Port: types.Int64Value(2123456789),
Region: types.StringValue(testRegion),

View file

@ -3,49 +3,40 @@ fields:
modifiers:
- 'UseStateForUnknown'
- name: 'user_id'
modifiers:
- 'UseStateForUnknown'
- name: 'instance_id'
validators:
- validate.NoSeparator
- validate.UUID
modifiers:
- 'UseStateForUnknown'
- 'RequiresReplace'
- name: 'project_id'
validators:
- validate.NoSeparator
- validate.UUID
modifiers:
- 'RequiresReplace'
- name: 'username'
modifiers:
- 'RequiresReplace'
- name: 'roles'
modifiers:
- 'RequiresReplace'
- name: 'password'
modifiers:
- 'UseStateForUnknown'
- name: 'host'
modifiers:
- 'UseStateForUnknown'
- name: 'port'
modifiers:
- 'UseStateForUnknown'
- 'RequiresReplace'
- name: 'region'
modifiers:
- 'RequiresReplace'
- name: 'status'
- name: 'user_id'
modifiers:
- 'UseStateForUnknown'
- 'RequiresReplace'
- name: 'username'
modifiers:
- 'UseStateForUnknown'
- name: 'roles'
modifiers:
- 'UseStateForUnknown'
- name: 'password'
modifiers:
- 'UseStateForUnknown'
@ -53,6 +44,6 @@ fields:
modifiers:
- 'UseStateForUnknown'
- name: 'default_database'
- name: 'status'
modifiers:
- 'UseStateForUnknown'

View file

@ -8,26 +8,27 @@ import (
"net/http"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-framework/resource/identityschema"
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/sqlserverflexalpha"
sqlserverflexalphagen "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/user/resources_gen"
sqlserverflexalphaUtils "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/utils"
sqlserverflexalphaWait "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/wait/sqlserverflexalpha"
"time"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/identityschema"
"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/pkg_gen/sqlserverflexalpha"
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/conversion"
sqlserverflexalphagen "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/user/resources_gen"
sqlserverflexalphaUtils "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/utils"
sqlserverflexalphaWait "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/wait/sqlserverflexalpha"
"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"
sqlserverflexalphaResGen "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/user/resources_gen"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &userResource{}
_ resource.ResourceWithConfigure = &userResource{}
@ -36,13 +37,12 @@ var (
_ resource.ResourceWithIdentity = &userResource{}
)
// NewUserResource is a helper function to simplify the provider implementation.
func NewUserResource() resource.Resource {
return &userResource{}
}
// resourceModel describes the resource data model.
type resourceModel = sqlserverflexalphagen.UserModel
type resourceModel = sqlserverflexalphaResGen.UserModel
// UserResourceIdentityModel describes the resource's identity attributes.
type UserResourceIdentityModel struct {
@ -52,14 +52,12 @@ type UserResourceIdentityModel struct {
UserID types.Int64 `tfsdk:"user_id"`
}
// userResource is the resource implementation.
type userResource struct {
client *sqlserverflexalpha.APIClient
providerData core.ProviderData
}
// Metadata returns the resource type name.
func (r *userResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
func (r *userResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_sqlserverflexalpha_user"
}
@ -76,7 +74,7 @@ func (r *userResource) Configure(ctx context.Context, req resource.ConfigureRequ
return
}
r.client = apiClient
tflog.Info(ctx, "SQLServer Alpha Flex user client configured")
tflog.Info(ctx, "SQLServer Beta Flex user client configured")
}
// ModifyPlan implements resource.ResourceWithModifyPlan.
@ -219,6 +217,7 @@ func (r *userResource) Create(
)
return
}
userId := *userResp.Id
ctx = tflog.SetField(ctx, "user_id", userId)
@ -227,14 +226,13 @@ func (r *userResource) Create(
ProjectID: types.StringValue(projectId),
Region: types.StringValue(region),
InstanceID: types.StringValue(instanceId),
UserID: types.Int64Value(userResp.GetId()),
UserID: types.Int64Value(userId),
}
resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...)
if resp.Diagnostics.HasError() {
return
}
// Map response body to schema
err = mapFieldsCreate(userResp, &model, region)
if err != nil {
core.LogAndAddError(
@ -245,6 +243,51 @@ func (r *userResource) Create(
)
return
}
waitResp, err := sqlserverflexalphaWait.CreateUserWaitHandler(
ctx,
r.client,
projectId,
instanceId,
region,
userId,
).SetSleepBeforeWait(
90 * time.Second,
).SetTimeout(
90 * time.Minute,
).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"create user",
fmt.Sprintf("Instance creation waiting: %v", err),
)
return
}
if waitResp.Id == nil {
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"create user",
"Instance creation waiting: returned id is nil",
)
return
}
// Map response body to schema
err = mapFields(waitResp, &model, region)
if err != nil {
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error creating user",
fmt.Sprintf("Processing API payload: %v", err),
)
return
}
// Set state to fully populated data
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
@ -296,18 +339,6 @@ func (r *userResource) Read(
ctx = core.LogResponse(ctx)
// Set data returned by API in identity
identity := UserResourceIdentityModel{
ProjectID: types.StringValue(projectId),
Region: types.StringValue(region),
InstanceID: types.StringValue(instanceId),
UserID: types.Int64Value(userId),
}
resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...)
if resp.Diagnostics.HasError() {
return
}
// Map response body to schema
err = mapFields(recordSetResp, &model, region)
if err != nil {
@ -320,6 +351,18 @@ func (r *userResource) Read(
return
}
// Set data returned by API in identity
identity := UserResourceIdentityModel{
ProjectID: types.StringValue(projectId),
Region: types.StringValue(region),
InstanceID: types.StringValue(instanceId),
UserID: types.Int64Value(userId),
}
resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...)
if resp.Diagnostics.HasError() {
return
}
// Set refreshed state
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
@ -366,9 +409,29 @@ func (r *userResource) Delete(
// Delete existing record set
// err := r.client.DeleteUserRequest(ctx, projectId, region, instanceId, userId).Execute()
err := r.client.DeleteUserRequestExecute(ctx, projectId, region, instanceId, userId)
if err != nil {
var oapiErr *oapierror.GenericOpenAPIError
ok := errors.As(err, &oapiErr)
if !ok {
// TODO err handling
return
}
switch oapiErr.StatusCode {
case http.StatusNotFound:
resp.State.RemoveResource(ctx)
return
// case http.StatusInternalServerError:
// tflog.Warn(ctx, "[delete user] Wait handler got error 500")
// return false, nil, nil
default:
// TODO err handling
return
}
}
// Delete existing record set
_, err := sqlserverflexalphaWait.DeleteUserWaitHandler(ctx, r.client, projectId, region, instanceId, userId).
_, err = sqlserverflexalphaWait.DeleteUserWaitHandler(ctx, r.client, projectId, region, instanceId, userId).
WaitWithContext(ctx)
// err := r.client.DeleteUserRequest(ctx, arg.projectId, arg.region, arg.instanceId, userId).Execute()
if err != nil {
@ -377,6 +440,7 @@ func (r *userResource) Delete(
}
ctx = core.LogResponse(ctx)
resp.State.RemoveResource(ctx)
tflog.Info(ctx, "SQLServer Flex user deleted")
@ -422,7 +486,7 @@ func (r *userResource) ImportState(
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), userId)...)
tflog.Info(ctx, "Postgres Flex user state imported")
tflog.Info(ctx, "SQLServer Flex user state imported")
return
}