feat: refactor user and database resource import logic and identity handling

This commit is contained in:
Andre_Harms 2026-02-10 07:19:18 +01:00
parent 184e133a2a
commit c4b31d0ba8
9 changed files with 415 additions and 280 deletions

View file

@ -13,7 +13,6 @@ import (
"github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/identityschema" "github.com/hashicorp/terraform-plugin-framework/resource/identityschema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/oapierror" "github.com/stackitcloud/stackit-sdk-go/core/oapierror"
@ -128,33 +127,6 @@ var modifiersFileByte []byte
func (r *databaseResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { func (r *databaseResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
s := postgresflexalpha2.DatabaseResourceSchema(ctx) s := postgresflexalpha2.DatabaseResourceSchema(ctx)
s.Attributes["project_id"] = schema.StringAttribute{
Description: "STACKIT project ID to which the instance is associated.",
MarkdownDescription: "STACKIT project ID to which the instance is associated.",
Required: true,
}
s.Attributes["instance_id"] = schema.StringAttribute{
Description: "ID of the PostgresFlex instance.",
MarkdownDescription: "ID of the PostgresFlex instance.",
Required: true,
}
s.Attributes["region"] = schema.StringAttribute{
Description: "Region of the PostgresFlex instance.",
MarkdownDescription: "Region of the PostgresFlex instance.",
Optional: true,
Computed: true,
}
s.Attributes["database_id"] = schema.Int64Attribute{
Description: "The ID of the database.",
Computed: true,
}
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,
}
fields, err := postgresflexUtils.ReadModifiersConfig(modifiersFileByte) fields, err := postgresflexUtils.ReadModifiersConfig(modifiersFileByte)
if err != nil { if err != nil {
resp.Diagnostics.AddError("error during read modifiers config file", err.Error()) resp.Diagnostics.AddError("error during read modifiers config file", err.Error())
@ -283,14 +255,14 @@ func (r *databaseResource) Create(
return return
} }
// Write identity attributes to state // Set data returned by API in identity
identityData.ProjectID = types.StringValue(projectId) identity := DatabaseResourceIdentityModel{
identityData.Region = types.StringValue(region) ProjectID: types.StringValue(projectId),
identityData.InstanceID = types.StringValue(instanceId) Region: types.StringValue(region),
identityData.DatabaseID = types.Int64Value(databaseId) InstanceID: types.StringValue(instanceId),
DatabaseID: types.Int64Value(databaseId),
resp.Diagnostics.Append(resp.Identity.Set(ctx, &identityData)...) }
resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
@ -537,56 +509,71 @@ func (r *databaseResource) ImportState(
req resource.ImportStateRequest, req resource.ImportStateRequest,
resp *resource.ImportStateResponse, resp *resource.ImportStateResponse,
) { ) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
core.LogAndAddError(
ctx, &resp.Diagnostics,
"Error importing database",
fmt.Sprintf(
"Expected import identifier with format [project_id],[region],[instance_id],[database_id], got %q",
req.ID,
),
)
return
}
databaseId, err := strconv.ParseInt(idParts[3], 10, 64) ctx = core.InitProviderContext(ctx)
if err != nil {
core.LogAndAddError( if req.ID != "" {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
core.LogAndAddError(
ctx, &resp.Diagnostics,
"Error importing database",
fmt.Sprintf(
"Expected import identifier with format [project_id],[region],[instance_id],[database_id], got %q",
req.ID,
),
)
return
}
databaseId, err := strconv.ParseInt(idParts[3], 10, 64)
if err != nil {
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error importing database",
fmt.Sprintf("Invalid database_id format: %q. It must be a valid integer.", idParts[3]),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("database_id"), databaseId)...)
core.LogAndAddWarning(
ctx, ctx,
&resp.Diagnostics, &resp.Diagnostics,
"Error importing database", "Postgresflex database imported with empty password",
fmt.Sprintf("Invalid database_id format: %q. It must be a valid integer.", idParts[3]), "The database password is not imported as it is only available upon creation of a new database. The password field will be empty.",
) )
tflog.Info(ctx, "Postgres Flex database state imported")
return return
} }
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...) // If no ID is provided, attempt to read identity attributes from the import configuration
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("database_id"), databaseId)...)
core.LogAndAddWarning(
ctx,
&resp.Diagnostics,
"Postgresflex database imported with empty password",
"The database password is not imported as it is only available upon creation of a new database. The password field will be empty.",
)
var identityData DatabaseResourceIdentityModel var identityData DatabaseResourceIdentityModel
identityData.ProjectID = types.StringValue(idParts[0]) resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
identityData.Region = types.StringValue(idParts[1])
identityData.InstanceID = types.StringValue(idParts[2])
identityData.DatabaseID = types.Int64Value(databaseId)
resp.Diagnostics.Append(resp.Identity.Set(ctx, &identityData)...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
tflog.Info(ctx, "Postgres Flex instance state imported") projectId := identityData.ProjectID.ValueString()
region := identityData.Region.ValueString()
instanceId := identityData.InstanceID.ValueString()
databaseId := identityData.DatabaseID.ValueInt64()
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("database_id"), databaseId)...)
tflog.Info(ctx, "Postgres Flex database state imported")
} }
// extractIdentityData extracts essential identifiers from the resource model, falling back to the identity model. // extractIdentityData extracts essential identifiers from the resource model, falling back to the identity model.

View file

@ -82,7 +82,7 @@ func (r *instanceResource) ModifyPlan(
req resource.ModifyPlanRequest, req resource.ModifyPlanRequest,
resp *resource.ModifyPlanResponse, resp *resource.ModifyPlanResponse,
) { // nolint:gocritic // function signature required by Terraform ) { // nolint:gocritic // function signature required by Terraform
var configModel postgresflexalpha.InstanceModel var configModel resourceModel
// skip initial empty configuration to avoid follow-up errors // skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() { if req.Config.Raw.IsNull() {
return return
@ -92,7 +92,7 @@ func (r *instanceResource) ModifyPlan(
return return
} }
var planModel postgresflexalpha.InstanceModel var planModel resourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...) resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
@ -630,38 +630,20 @@ func (r *instanceResource) ImportState(
return return
} }
// If no ID is provided, attempt to read identity attributes from the import configuration
var identityData InstanceResourceIdentityModel var identityData InstanceResourceIdentityModel
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...) resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
resp.Diagnostics.Append( projectId := identityData.ProjectID.ValueString()
resp.State.SetAttribute( region := identityData.Region.ValueString()
ctx, instanceId := identityData.InstanceID.ValueString()
path.Root("id"),
utils.BuildInternalTerraformId( resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
identityData.ProjectID.ValueString(), resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
identityData.Region.ValueString(), resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
identityData.InstanceID.ValueString(),
),
)...,
)
resp.Diagnostics.Append(
resp.State.SetAttribute(
ctx,
path.Root("project_id"),
identityData.ProjectID.ValueString(),
)...,
)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), identityData.Region.ValueString())...)
resp.Diagnostics.Append(
resp.State.SetAttribute(
ctx,
path.Root("instance_id"),
identityData.InstanceID.ValueString(),
)...,
)
tflog.Info(ctx, "Postgres Flex instance state imported") tflog.Info(ctx, "Postgres Flex instance state imported")
} }

View file

@ -219,6 +219,18 @@ func (r *userResource) Create(
ctx = core.LogResponse(ctx) ctx = core.LogResponse(ctx)
// Set data returned by API in identity
identity := UserResourceIdentityModel{
ProjectID: types.StringValue(arg.projectId),
Region: types.StringValue(arg.region),
InstanceID: types.StringValue(arg.instanceId),
UserID: types.Int64PointerValue(userResp.Id),
}
resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...)
if resp.Diagnostics.HasError() {
return
}
// Verify creation // Verify creation
exists, err := r.getUserResource(ctx, &model, arg) exists, err := r.getUserResource(ctx, &model, arg)
@ -497,65 +509,6 @@ func (r *userResource) IdentitySchema(
} }
} }
// ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: project_id,zone_id,record_set_id
func (r *userResource) ImportState(
ctx context.Context,
req resource.ImportStateRequest,
resp *resource.ImportStateResponse,
) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
core.LogAndAddError(
ctx, &resp.Diagnostics,
"Error importing user",
fmt.Sprintf(
"Expected import identifier with format [project_id],[region],[instance_id],[user_id], got %q",
req.ID,
),
)
return
}
userId, err := strconv.ParseInt(idParts[3], 10, 64)
if err != nil {
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error importing user",
fmt.Sprintf("Invalid userId format: %q. It must be a valid integer.", idParts[3]),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
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)...)
core.LogAndAddWarning(
ctx,
&resp.Diagnostics,
"postgresflexalpha user imported with empty password and empty uri",
"The user password and uri are not imported as they are only available upon creation of a new user. The password and uri fields will be empty.",
)
var identityData UserResourceIdentityModel
identityData.ProjectID = types.StringValue(idParts[0])
identityData.Region = types.StringValue(idParts[1])
identityData.InstanceID = types.StringValue(idParts[2])
identityData.UserID = types.Int64Value(userId)
resp.Diagnostics.Append(resp.Identity.Set(ctx, &identityData)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Postgres Flex instance state imported")
tflog.Info(ctx, "postgresflexalpha user state imported")
}
func mapFields(userResp *postgresflex.GetUserResponse, model *resourceModel, region string) error { func mapFields(userResp *postgresflex.GetUserResponse, model *resourceModel, region string) error {
if userResp == nil { if userResp == nil {
return fmt.Errorf("response is nil") return fmt.Errorf("response is nil")
@ -631,6 +584,73 @@ type clientArg struct {
userId int64 userId int64
} }
// ImportState imports a resource into the Terraform state on success.
// The expected import identifier format is: [project_id],[region],[instance_id],[database_id]
func (r *userResource) ImportState(
ctx context.Context,
req resource.ImportStateRequest,
resp *resource.ImportStateResponse,
) {
ctx = core.InitProviderContext(ctx)
if req.ID != "" {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
core.LogAndAddError(
ctx, &resp.Diagnostics,
"Error importing user",
fmt.Sprintf(
"Expected import identifier with format [project_id],[region],[instance_id],[user_id], got %q",
req.ID,
),
)
return
}
userId, err := strconv.ParseInt(idParts[3], 10, 64)
if err != nil {
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error importing user",
fmt.Sprintf("Invalid user_id format: %q. It must be a valid integer.", idParts[3]),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
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")
return
}
// If no ID is provided, attempt to read identity attributes from the import configuration
var identityData UserResourceIdentityModel
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
if resp.Diagnostics.HasError() {
return
}
projectId := identityData.ProjectID.ValueString()
region := identityData.Region.ValueString()
instanceId := identityData.InstanceID.ValueString()
userId := identityData.UserID.ValueInt64()
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), userId)...)
tflog.Info(ctx, "Postgres Flex user state imported")
}
// extractIdentityData extracts essential identifiers from the resource model, falling back to the identity model. // extractIdentityData extracts essential identifiers from the resource model, falling back to the identity model.
func (r *userResource) extractIdentityData( func (r *userResource) extractIdentityData(
model resourceModel, model resourceModel,

View file

@ -3,10 +3,13 @@ package sqlserverflexalpha
import ( import (
"context" "context"
"fmt" "fmt"
"strconv"
"strings" "strings"
"github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource" "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/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/config" "github.com/stackitcloud/stackit-sdk-go/core/config"
"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/pkg_gen/sqlserverflexalpha"
@ -23,13 +26,22 @@ var (
_ resource.ResourceWithConfigure = &databaseResource{} _ resource.ResourceWithConfigure = &databaseResource{}
_ resource.ResourceWithImportState = &databaseResource{} _ resource.ResourceWithImportState = &databaseResource{}
_ resource.ResourceWithModifyPlan = &databaseResource{} _ resource.ResourceWithModifyPlan = &databaseResource{}
_ resource.ResourceWithIdentity = &databaseResource{}
) )
func NewDatabaseResource() resource.Resource {
return &databaseResource{}
}
// resourceModel describes the resource data model. // resourceModel describes the resource data model.
type resourceModel = sqlserverflexalphaGen.DatabaseModel type resourceModel = sqlserverflexalphaGen.DatabaseModel
func NewDatabaseResource() resource.Resource { // DatabaseResourceIdentityModel describes the resource's identity attributes.
return &databaseResource{} type DatabaseResourceIdentityModel struct {
ProjectID types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
InstanceID types.String `tfsdk:"instance_id"`
DatabaseName types.String `tfsdk:"database_name"`
} }
type databaseResource struct { type databaseResource struct {
@ -45,6 +57,29 @@ func (r *databaseResource) Schema(ctx context.Context, _ resource.SchemaRequest,
resp.Schema = sqlserverflexalphaGen.DatabaseResourceSchema(ctx) resp.Schema = sqlserverflexalphaGen.DatabaseResourceSchema(ctx)
} }
func (r *databaseResource) IdentitySchema(
_ context.Context,
_ resource.IdentitySchemaRequest,
resp *resource.IdentitySchemaResponse,
) {
resp.IdentitySchema = identityschema.Schema{
Attributes: map[string]identityschema.Attribute{
"project_id": identityschema.StringAttribute{
RequiredForImport: true, // must be set during import by the practitioner
},
"region": identityschema.StringAttribute{
RequiredForImport: true, // can be defaulted by the provider configuration
},
"instance_id": identityschema.StringAttribute{
RequiredForImport: true, // can be defaulted by the provider configuration
},
"database_name": identityschema.StringAttribute{
RequiredForImport: true, // can be defaulted by the provider configuration
},
},
}
}
// Configure adds the provider configured client to the resource. // Configure adds the provider configured client to the resource.
func (r *databaseResource) Configure( func (r *databaseResource) Configure(
ctx context.Context, ctx context.Context,
@ -191,36 +226,72 @@ func (r *databaseResource) ModifyPlan(
} }
// ImportState imports a resource into the Terraform state on success. // ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: project_id,zone_id,record_set_id // The expected import identifier format is: [project_id],[region],[instance_id],[database_id]
func (r *databaseResource) ImportState( func (r *databaseResource) ImportState(
ctx context.Context, ctx context.Context,
req resource.ImportStateRequest, req resource.ImportStateRequest,
resp *resource.ImportStateResponse, resp *resource.ImportStateResponse,
) { ) {
idParts := strings.Split(req.ID, core.Separator)
// Todo: Import logic ctx = core.InitProviderContext(ctx)
if len(idParts) < 2 || idParts[0] == "" || idParts[1] == "" {
core.LogAndAddError( if req.ID != "" {
ctx, &resp.Diagnostics,
"Error importing database", idParts := strings.Split(req.ID, core.Separator)
fmt.Sprintf(
"Expected import identifier with format [project_id],[region],..., got %q", if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
req.ID, core.LogAndAddError(
), ctx, &resp.Diagnostics,
"Error importing database",
fmt.Sprintf(
"Expected import identifier with format [project_id],[region],[instance_id],[database_name], got %q",
req.ID,
),
)
return
}
databaseId, err := strconv.ParseInt(idParts[3], 10, 64)
if err != nil {
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error importing database",
fmt.Sprintf("Invalid database_id format: %q. It must be a valid integer.", idParts[3]),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("database_name"), databaseId)...)
core.LogAndAddWarning(
ctx,
&resp.Diagnostics,
"Sqlserverflexalpha database imported with empty password",
"The database password is not imported as it is only available upon creation of a new database. The password field will be empty.",
) )
tflog.Info(ctx, "Sqlserverflexalpha database state imported")
}
// If no ID is provided, attempt to read identity attributes from the import configuration
var identityData DatabaseResourceIdentityModel
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
if resp.Diagnostics.HasError() {
return return
} }
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...) projectId := identityData.ProjectID.ValueString()
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...) region := identityData.Region.ValueString()
// ... more ... instanceId := identityData.InstanceID.ValueString()
databaseName := identityData.DatabaseName.ValueString()
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("database_name"), databaseName)...)
core.LogAndAddWarning(
ctx,
&resp.Diagnostics,
"Sqlserverflexalpha database imported with empty password",
"The database password is not imported as it is only available upon creation of a new database. The password field will be empty.",
)
tflog.Info(ctx, "Sqlserverflexalpha database state imported") tflog.Info(ctx, "Sqlserverflexalpha database state imported")
} }

View file

@ -515,20 +515,41 @@ func (r *instanceResource) ImportState(
req resource.ImportStateRequest, req resource.ImportStateRequest,
resp *resource.ImportStateResponse, resp *resource.ImportStateResponse,
) { ) {
// TODO if req.ID != "" {
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError( core.LogAndAddError(
ctx, &resp.Diagnostics, ctx, &resp.Diagnostics,
"Error importing instance", "Error importing instance",
fmt.Sprintf("Expected import identifier with format: [project_id],[region],[instance_id] Got: %q", req.ID), fmt.Sprintf(
) "Expected import identifier with format: [project_id],[region],[instance_id] Got: %q",
req.ID,
),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
return return
} }
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...) // If no ID is provided, attempt to read identity attributes from the import configuration
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...) var identityData InstanceResourceIdentityModel
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...) resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
if resp.Diagnostics.HasError() {
return
}
projectId := identityData.ProjectID.ValueString()
region := identityData.Region.ValueString()
instanceId := identityData.InstanceID.ValueString()
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
tflog.Info(ctx, "SQLServer Flex instance state imported") tflog.Info(ctx, "SQLServer Flex instance state imported")
} }

View file

@ -5,6 +5,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
"strconv"
"strings" "strings"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
@ -47,6 +48,14 @@ func NewUserResource() resource.Resource {
// resourceModel describes the resource data model. // resourceModel describes the resource data model.
type resourceModel = sqlserverflexalphagen.UserModel type resourceModel = sqlserverflexalphagen.UserModel
// UserResourceIdentityModel describes the resource's identity attributes.
type UserResourceIdentityModel struct {
ProjectID types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
InstanceID types.String `tfsdk:"instance_id"`
UserID types.Int64 `tfsdk:"user_id"`
}
// userResource is the resource implementation. // userResource is the resource implementation.
type userResource struct { type userResource struct {
client *sqlserverflexalpha.APIClient client *sqlserverflexalpha.APIClient
@ -417,23 +426,63 @@ func (r *userResource) ImportState(
req resource.ImportStateRequest, req resource.ImportStateRequest,
resp *resource.ImportStateResponse, resp *resource.ImportStateResponse,
) { ) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" { ctx = core.InitProviderContext(ctx)
core.LogAndAddError(
ctx, &resp.Diagnostics, if req.ID != "" {
"Error importing user",
fmt.Sprintf( idParts := strings.Split(req.ID, core.Separator)
"Expected import identifier with format [project_id],[region],[instance_id],[user_id], got %q",
req.ID, if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
), core.LogAndAddError(
) ctx, &resp.Diagnostics,
"Error importing user",
fmt.Sprintf(
"Expected import identifier with format [project_id],[region],[instance_id],[user_id], got %q",
req.ID,
),
)
return
}
userId, err := strconv.ParseInt(idParts[3], 10, 64)
if err != nil {
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error importing user",
fmt.Sprintf("Invalid user_id format: %q. It must be a valid integer.", idParts[3]),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
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")
return return
} }
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...) // If no ID is provided, attempt to read identity attributes from the import configuration
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...) var identityData UserResourceIdentityModel
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...) resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), idParts[3])...) if resp.Diagnostics.HasError() {
return
}
projectId := identityData.ProjectID.ValueString()
region := identityData.Region.ValueString()
instanceId := identityData.InstanceID.ValueString()
userId := identityData.UserID.ValueInt64()
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), userId)...)
core.LogAndAddWarning( core.LogAndAddWarning(
ctx, ctx,
&resp.Diagnostics, &resp.Diagnostics,

View file

@ -467,39 +467,22 @@ func (r *databaseResource) ImportState(
return return
} }
// If no ID is provided, attempt to read identity attributes from the import configuration
var identityData DatabaseResourceIdentityModel var identityData DatabaseResourceIdentityModel
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...) resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
resp.Diagnostics.Append( projectId := identityData.ProjectID.ValueString()
resp.State.SetAttribute( region := identityData.Region.ValueString()
ctx, instanceId := identityData.InstanceID.ValueString()
path.Root("project_id"), databaseName := identityData.DatabaseName.ValueString()
identityData.ProjectID.ValueString(),
)...,
)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), identityData.Region.ValueString())...)
resp.Diagnostics.Append(
resp.State.SetAttribute(
ctx,
path.Root("instance_id"),
identityData.InstanceID.ValueString(),
)...,
)
resp.Diagnostics.Append(
resp.State.SetAttribute(
ctx,
path.Root("database_name"),
identityData.DatabaseName.ValueString(),
)...,
)
resp.Diagnostics.Append(resp.Identity.Set(ctx, &identityData)...) resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
if resp.Diagnostics.HasError() { resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
return resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
} resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("database_name"), databaseName)...)
tflog.Info(ctx, "Sqlserverflexbeta database state imported") tflog.Info(ctx, "Sqlserverflexbeta database state imported")
} }

View file

@ -515,38 +515,20 @@ func (r *instanceResource) ImportState(
return return
} }
// If no ID is provided, attempt to read identity attributes from the import configuration
var identityData InstanceResourceIdentityModel var identityData InstanceResourceIdentityModel
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...) resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
resp.Diagnostics.Append( projectId := identityData.ProjectID.ValueString()
resp.State.SetAttribute( region := identityData.Region.ValueString()
ctx, instanceId := identityData.InstanceID.ValueString()
path.Root("id"),
utils.BuildInternalTerraformId( resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
identityData.ProjectID.ValueString(), resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
identityData.Region.ValueString(), resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
identityData.InstanceID.ValueString(),
),
)...,
)
resp.Diagnostics.Append(
resp.State.SetAttribute(
ctx,
path.Root("project_id"),
identityData.ProjectID.ValueString(),
)...,
)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), identityData.Region.ValueString())...)
resp.Diagnostics.Append(
resp.State.SetAttribute(
ctx,
path.Root("instance_id"),
identityData.InstanceID.ValueString(),
)...,
)
tflog.Info(ctx, "Sqlserverflexbeta instance state imported") tflog.Info(ctx, "Sqlserverflexbeta instance state imported")
} }

View file

@ -3,6 +3,7 @@ package sqlserverflexbeta
import ( import (
"context" "context"
"fmt" "fmt"
"strconv"
"strings" "strings"
"github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/path"
@ -36,18 +37,19 @@ func NewUserResource() resource.Resource {
// resourceModel describes the resource data model. // resourceModel describes the resource data model.
type resourceModel = sqlserverflexbetaResGen.UserModel type resourceModel = sqlserverflexbetaResGen.UserModel
// UserResourceIdentityModel describes the resource's identity attributes.
type UserResourceIdentityModel struct {
ProjectID types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
InstanceID types.String `tfsdk:"instance_id"`
UserID types.Int64 `tfsdk:"database_id"`
}
type userResource struct { type userResource struct {
client *sqlserverflexbeta.APIClient client *sqlserverflexbeta.APIClient
providerData core.ProviderData providerData core.ProviderData
} }
type UserResourceIdentityModel struct {
ProjectID types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
UserID types.String `tfsdk:"instance_id"`
// TODO: implement further needed parts
}
func (r *userResource) Metadata(ctx 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 + "_sqlserverflexbeta_user" resp.TypeName = req.ProviderTypeName + "_sqlserverflexbeta_user"
} }
@ -392,24 +394,61 @@ func (r *userResource) ImportState(
req resource.ImportStateRequest, req resource.ImportStateRequest,
resp *resource.ImportStateResponse, resp *resource.ImportStateResponse,
) { ) {
idParts := strings.Split(req.ID, core.Separator) ctx = core.InitProviderContext(ctx)
if req.ID != "" {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
core.LogAndAddError(
ctx, &resp.Diagnostics,
"Error importing user",
fmt.Sprintf(
"Expected import identifier with format [project_id],[region],[instance_id],[user_id], got %q",
req.ID,
),
)
return
}
userId, err := strconv.ParseInt(idParts[3], 10, 64)
if err != nil {
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error importing user",
fmt.Sprintf("Invalid user_id format: %q. It must be a valid integer.", idParts[3]),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
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, "Sqlserverflexbeta user state imported")
// Todo: Import logic
if len(idParts) < 2 || idParts[0] == "" || idParts[1] == "" {
core.LogAndAddError(
ctx, &resp.Diagnostics,
"Error importing database",
fmt.Sprintf(
"Expected import identifier with format [project_id],[region],..., got %q",
req.ID,
),
)
return return
} }
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...) // If no ID is provided, attempt to read identity attributes from the import configuration
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...) var identityData UserResourceIdentityModel
// ... more ... resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
if resp.Diagnostics.HasError() {
return
}
projectId := identityData.ProjectID.ValueString()
region := identityData.Region.ValueString()
instanceId := identityData.InstanceID.ValueString()
userId := identityData.UserID.ValueInt64()
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), userId)...)
core.LogAndAddWarning( core.LogAndAddWarning(
ctx, ctx,
@ -418,4 +457,5 @@ func (r *userResource) ImportState(
"The database password is not imported as it is only available upon creation of a new database. The password field will be empty.", "The database password is not imported as it is only available upon creation of a new database. The password field will be empty.",
) )
tflog.Info(ctx, "Sqlserverflexbeta user state imported") tflog.Info(ctx, "Sqlserverflexbeta user state imported")
} }