## Description
<!-- **Please link some issue here describing what you are trying to achieve.**
In case there is no issue present for your PR, please consider creating one.
At least please give us some description what you are trying to achieve and why your change is needed. -->
relates to #1234
## Checklist
- [ ] Issue was linked above
- [ ] Code format was applied: `make fmt`
- [ ] Examples were added / adjusted (see `examples/` directory)
- [x] Docs are up-to-date: `make generate-docs` (will be checked by CI)
- [ ] Unit tests got implemented or updated
- [ ] Acceptance tests got implemented or updated (see e.g. [here](f5f99d1709/stackit/internal/services/dns/dns_acc_test.go))
- [x] Unit tests are passing: `make test` (will be checked by CI)
- [x] No linter issues: `make lint` (will be checked by CI)
Reviewed-on: #60
649 lines
20 KiB
Go
649 lines
20 KiB
Go
package postgresflexalpha
|
|
|
|
import (
|
|
"context"
|
|
_ "embed"
|
|
"fmt"
|
|
"math"
|
|
"strconv"
|
|
"strings"
|
|
"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"
|
|
|
|
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
|
|
"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"
|
|
postgresflexalpha2 "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/database/resources_gen"
|
|
postgresflexUtils "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/utils"
|
|
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils"
|
|
postgresflexalpha3 "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/wait/postgresflexalpha"
|
|
)
|
|
|
|
var (
|
|
// Ensure the implementation satisfies the expected interfaces.
|
|
_ resource.Resource = &databaseResource{}
|
|
_ resource.ResourceWithConfigure = &databaseResource{}
|
|
_ resource.ResourceWithImportState = &databaseResource{}
|
|
_ resource.ResourceWithModifyPlan = &databaseResource{}
|
|
_ resource.ResourceWithIdentity = &databaseResource{}
|
|
|
|
// Error message constants
|
|
extractErrorSummary = "extracting failed"
|
|
extractErrorMessage = "Extracting identity data: %v"
|
|
)
|
|
|
|
// NewDatabaseResource is a helper function to simplify the provider implementation.
|
|
func NewDatabaseResource() resource.Resource {
|
|
return &databaseResource{}
|
|
}
|
|
|
|
// resourceModel describes the resource data model.
|
|
type resourceModel = postgresflexalpha2.DatabaseModel
|
|
|
|
// DatabaseResourceIdentityModel describes the resource's identity attributes.
|
|
type DatabaseResourceIdentityModel struct {
|
|
ProjectID types.String `tfsdk:"project_id"`
|
|
Region types.String `tfsdk:"region"`
|
|
InstanceID types.String `tfsdk:"instance_id"`
|
|
DatabaseID types.Int64 `tfsdk:"database_id"`
|
|
}
|
|
|
|
// databaseResource is the resource implementation.
|
|
type databaseResource struct {
|
|
client *postgresflexalpha.APIClient
|
|
providerData core.ProviderData
|
|
}
|
|
|
|
// ModifyPlan adjusts the plan to set the correct region.
|
|
func (r *databaseResource) ModifyPlan(
|
|
ctx context.Context,
|
|
req resource.ModifyPlanRequest,
|
|
resp *resource.ModifyPlanResponse,
|
|
) { // nolint:gocritic // function signature required by Terraform
|
|
var configModel resourceModel
|
|
// skip initial empty configuration to avoid follow-up errors
|
|
if req.Config.Raw.IsNull() {
|
|
return
|
|
}
|
|
resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
var planModel resourceModel
|
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
utils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.GetRegion(), resp)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
}
|
|
|
|
// Metadata returns the resource type name.
|
|
func (r *databaseResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
|
resp.TypeName = req.ProviderTypeName + "_postgresflexalpha_database"
|
|
}
|
|
|
|
// Configure adds the provider configured client to the resource.
|
|
func (r *databaseResource) Configure(
|
|
ctx context.Context,
|
|
req resource.ConfigureRequest,
|
|
resp *resource.ConfigureResponse,
|
|
) {
|
|
var ok bool
|
|
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
apiClient := postgresflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
r.client = apiClient
|
|
tflog.Info(ctx, "Postgres Flex database client configured")
|
|
}
|
|
|
|
//go:embed planModifiers.yaml
|
|
var modifiersFileByte []byte
|
|
|
|
// Schema defines the schema for the resource.
|
|
func (r *databaseResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
|
s := postgresflexalpha2.DatabaseResourceSchema(ctx)
|
|
|
|
fields, err := utils.ReadModifiersConfig(modifiersFileByte)
|
|
if err != nil {
|
|
resp.Diagnostics.AddError("error during read modifiers config file", err.Error())
|
|
return
|
|
}
|
|
|
|
err = utils.AddPlanModifiersToResourceSchema(fields, &s)
|
|
if err != nil {
|
|
resp.Diagnostics.AddError("error adding plan modifiers", err.Error())
|
|
return
|
|
}
|
|
resp.Schema = s
|
|
}
|
|
|
|
// IdentitySchema defines the schema for the resource's identity attributes.
|
|
func (r *databaseResource) IdentitySchema(
|
|
_ context.Context,
|
|
_ resource.IdentitySchemaRequest,
|
|
response *resource.IdentitySchemaResponse,
|
|
) {
|
|
response.IdentitySchema = identityschema.Schema{
|
|
Attributes: map[string]identityschema.Attribute{
|
|
"project_id": identityschema.StringAttribute{
|
|
RequiredForImport: true,
|
|
},
|
|
"region": identityschema.StringAttribute{
|
|
RequiredForImport: true,
|
|
},
|
|
"instance_id": identityschema.StringAttribute{
|
|
RequiredForImport: true,
|
|
},
|
|
"database_id": identityschema.Int64Attribute{
|
|
RequiredForImport: true,
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
// Create creates the resource and sets the initial Terraform state.
|
|
func (r *databaseResource) Create(
|
|
ctx context.Context,
|
|
req resource.CreateRequest,
|
|
resp *resource.CreateResponse,
|
|
) { // nolint:gocritic // function signature required by Terraform
|
|
const funcErrorSummary = "[database CREATE] error"
|
|
var model resourceModel
|
|
diags := req.Plan.Get(ctx, &model)
|
|
resp.Diagnostics.Append(diags...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
ctx = core.InitProviderContext(ctx)
|
|
|
|
projectId := model.ProjectId.ValueString()
|
|
region := model.InstanceId.ValueString()
|
|
instanceId := model.InstanceId.ValueString()
|
|
|
|
ctx = tflog.SetField(ctx, "project_id", projectId)
|
|
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
|
ctx = tflog.SetField(ctx, "region", region)
|
|
|
|
// Generate API request body from model
|
|
payload, err := toCreatePayload(&model)
|
|
if err != nil {
|
|
core.LogAndAddError(
|
|
ctx,
|
|
&resp.Diagnostics,
|
|
funcErrorSummary,
|
|
fmt.Sprintf("Creating API payload: %v", err),
|
|
)
|
|
return
|
|
}
|
|
// Create new database
|
|
databaseResp, err := r.client.CreateDatabaseRequest(
|
|
ctx,
|
|
projectId,
|
|
region,
|
|
instanceId,
|
|
).CreateDatabaseRequestPayload(*payload).Execute()
|
|
if err != nil {
|
|
core.LogAndAddError(ctx, &resp.Diagnostics, funcErrorSummary, fmt.Sprintf("Calling API: %v", err))
|
|
return
|
|
}
|
|
|
|
if databaseResp == nil || databaseResp.Id == nil {
|
|
core.LogAndAddError(
|
|
ctx,
|
|
&resp.Diagnostics,
|
|
funcErrorSummary,
|
|
"API didn't return database Id. A database might have been created",
|
|
)
|
|
return
|
|
}
|
|
databaseId := *databaseResp.Id
|
|
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
|
ctx = core.LogResponse(ctx)
|
|
|
|
// Save identity into Terraform state
|
|
identity := DatabaseResourceIdentityModel{
|
|
ProjectID: types.StringValue(projectId),
|
|
Region: types.StringValue(region),
|
|
InstanceID: types.StringValue(instanceId),
|
|
DatabaseID: types.Int64Value(databaseId),
|
|
}
|
|
resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
database, err := postgresflexalpha3.GetDatabaseByIdWaitHandler(ctx, r.client, projectId, instanceId, region, databaseId).
|
|
SetTimeout(15 * time.Minute).
|
|
SetSleepBeforeWait(15 * time.Second).
|
|
WaitWithContext(ctx)
|
|
if err != nil {
|
|
core.LogAndAddError(
|
|
ctx,
|
|
&resp.Diagnostics,
|
|
funcErrorSummary,
|
|
fmt.Sprintf("Getting database details after creation: %v", err),
|
|
)
|
|
return
|
|
}
|
|
|
|
// Map response body to schema
|
|
err = mapResourceFields(database, &model)
|
|
if err != nil {
|
|
core.LogAndAddError(
|
|
ctx,
|
|
&resp.Diagnostics,
|
|
funcErrorSummary,
|
|
fmt.Sprintf("map resource fields: %v", err),
|
|
)
|
|
return
|
|
}
|
|
|
|
// Set state to fully populated data
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, model)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
tflog.Info(ctx, "Postgres Flex database created")
|
|
}
|
|
|
|
// Read refreshes the Terraform state with the latest data.
|
|
func (r *databaseResource) Read(
|
|
ctx context.Context,
|
|
req resource.ReadRequest,
|
|
resp *resource.ReadResponse,
|
|
) { // nolint:gocritic // function signature required by Terraform
|
|
var model resourceModel
|
|
diags := req.State.Get(ctx, &model)
|
|
resp.Diagnostics.Append(diags...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
// Read identity data
|
|
var identityData DatabaseResourceIdentityModel
|
|
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
ctx = core.InitProviderContext(ctx)
|
|
|
|
projectId, region, instanceId, databaseId, errExt := r.extractIdentityData(model, identityData)
|
|
if errExt != nil {
|
|
core.LogAndAddError(
|
|
ctx,
|
|
&resp.Diagnostics,
|
|
extractErrorSummary,
|
|
fmt.Sprintf(extractErrorMessage, errExt),
|
|
)
|
|
}
|
|
|
|
ctx = tflog.SetField(ctx, "project_id", projectId)
|
|
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
|
ctx = tflog.SetField(ctx, "region", region)
|
|
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
|
|
|
databaseResp, err := postgresflexalpha3.GetDatabaseByIdWaitHandler(ctx, r.client, projectId, instanceId, region, databaseId).
|
|
SetTimeout(15 * time.Minute).
|
|
SetSleepBeforeWait(15 * time.Second).
|
|
WaitWithContext(ctx)
|
|
if err != nil {
|
|
core.LogAndAddError(
|
|
ctx,
|
|
&resp.Diagnostics,
|
|
"Error creating database",
|
|
fmt.Sprintf("Getting database details after creation: %v", err),
|
|
)
|
|
return
|
|
}
|
|
|
|
ctx = core.LogResponse(ctx)
|
|
|
|
// Map response body to schema
|
|
err = mapResourceFields(databaseResp, &model)
|
|
if err != nil {
|
|
core.LogAndAddError(
|
|
ctx,
|
|
&resp.Diagnostics,
|
|
"Error reading database",
|
|
fmt.Sprintf("Processing API payload: %v", err),
|
|
)
|
|
return
|
|
}
|
|
|
|
// Save identity into Terraform state
|
|
identity := DatabaseResourceIdentityModel{
|
|
ProjectID: types.StringValue(projectId),
|
|
Region: types.StringValue(region),
|
|
InstanceID: types.StringValue(instanceId),
|
|
DatabaseID: types.Int64Value(databaseId),
|
|
}
|
|
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...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
tflog.Info(ctx, "Postgres Flex database read")
|
|
}
|
|
|
|
// Update updates the resource and sets the updated Terraform state on success.
|
|
func (r *databaseResource) Update(
|
|
ctx context.Context,
|
|
req resource.UpdateRequest,
|
|
resp *resource.UpdateResponse,
|
|
) {
|
|
var model resourceModel
|
|
diags := req.Plan.Get(ctx, &model)
|
|
resp.Diagnostics.Append(diags...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
// Read identity data
|
|
var identityData DatabaseResourceIdentityModel
|
|
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
ctx = core.InitProviderContext(ctx)
|
|
|
|
projectId, region, instanceId, databaseId64, errExt := r.extractIdentityData(model, identityData)
|
|
if errExt != nil {
|
|
core.LogAndAddError(
|
|
ctx,
|
|
&resp.Diagnostics,
|
|
extractErrorSummary,
|
|
fmt.Sprintf(extractErrorMessage, errExt),
|
|
)
|
|
}
|
|
|
|
if databaseId64 > math.MaxInt32 {
|
|
core.LogAndAddError(ctx, &resp.Diagnostics, "Error in type conversion", "int value too large (databaseId)")
|
|
return
|
|
}
|
|
databaseId := int32(databaseId64) // nolint:gosec // check is performed above
|
|
|
|
ctx = tflog.SetField(ctx, "project_id", projectId)
|
|
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
|
ctx = tflog.SetField(ctx, "region", region)
|
|
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
|
|
|
// Retrieve values from state
|
|
var stateModel resourceModel
|
|
diags = req.State.Get(ctx, &stateModel)
|
|
resp.Diagnostics.Append(diags...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
modified := false
|
|
var payload postgresflexalpha.UpdateDatabasePartiallyRequestPayload
|
|
if stateModel.Name != model.Name {
|
|
payload.Name = model.Name.ValueStringPointer()
|
|
modified = true
|
|
}
|
|
|
|
if stateModel.Owner != model.Owner {
|
|
payload.Owner = model.Owner.ValueStringPointer()
|
|
modified = true
|
|
}
|
|
|
|
if !modified {
|
|
tflog.Info(ctx, "no modification detected")
|
|
return
|
|
}
|
|
|
|
// Update existing database
|
|
err := r.client.UpdateDatabasePartiallyRequest(
|
|
ctx,
|
|
projectId,
|
|
region,
|
|
instanceId,
|
|
databaseId,
|
|
).UpdateDatabasePartiallyRequestPayload(payload).Execute()
|
|
if err != nil {
|
|
core.LogAndAddError(ctx, &resp.Diagnostics, "error updating database", err.Error())
|
|
return
|
|
}
|
|
|
|
ctx = core.LogResponse(ctx)
|
|
|
|
databaseResp, err := postgresflexalpha3.GetDatabaseByIdWaitHandler(ctx, r.client, projectId, instanceId, region, databaseId64).
|
|
SetTimeout(15 * time.Minute).
|
|
SetSleepBeforeWait(15 * time.Second).
|
|
WaitWithContext(ctx)
|
|
if err != nil {
|
|
core.LogAndAddError(ctx, &resp.Diagnostics, "error updating database", err.Error())
|
|
return
|
|
}
|
|
|
|
ctx = core.LogResponse(ctx)
|
|
|
|
// Map response body to schema
|
|
err = mapResourceFields(databaseResp, &model)
|
|
if err != nil {
|
|
core.LogAndAddError(
|
|
ctx,
|
|
&resp.Diagnostics,
|
|
"Error reading database",
|
|
fmt.Sprintf("Processing API payload: %v", err),
|
|
)
|
|
return
|
|
}
|
|
|
|
// Save identity into Terraform state
|
|
identity := DatabaseResourceIdentityModel{
|
|
ProjectID: types.StringValue(projectId),
|
|
Region: types.StringValue(region),
|
|
InstanceID: types.StringValue(instanceId),
|
|
DatabaseID: types.Int64Value(databaseId64),
|
|
}
|
|
resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
// Set state to fully populated data
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &model)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
tflog.Info(ctx, "Postgres Flex database updated")
|
|
}
|
|
|
|
// Delete deletes the resource and removes the Terraform state on success.
|
|
func (r *databaseResource) Delete(
|
|
ctx context.Context,
|
|
req resource.DeleteRequest,
|
|
resp *resource.DeleteResponse,
|
|
) { // nolint:gocritic // function signature required by Terraform
|
|
var model resourceModel
|
|
diags := req.State.Get(ctx, &model)
|
|
resp.Diagnostics.Append(diags...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
// Read identity data
|
|
var identityData DatabaseResourceIdentityModel
|
|
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
ctx = core.InitProviderContext(ctx)
|
|
|
|
projectId, region, instanceId, databaseId64, errExt := r.extractIdentityData(model, identityData)
|
|
if errExt != nil {
|
|
core.LogAndAddError(
|
|
ctx,
|
|
&resp.Diagnostics,
|
|
extractErrorSummary,
|
|
fmt.Sprintf(extractErrorMessage, errExt),
|
|
)
|
|
}
|
|
|
|
if databaseId64 > math.MaxInt32 {
|
|
core.LogAndAddError(ctx, &resp.Diagnostics, "Error in type conversion", "int value too large (databaseId)")
|
|
return
|
|
}
|
|
databaseId := int32(databaseId64) // nolint:gosec // check is performed above
|
|
ctx = tflog.SetField(ctx, "project_id", projectId)
|
|
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
|
ctx = tflog.SetField(ctx, "region", region)
|
|
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
|
|
|
// Delete existing record set
|
|
err := r.client.DeleteDatabaseRequestExecute(ctx, projectId, region, instanceId, databaseId)
|
|
if err != nil {
|
|
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting database", fmt.Sprintf("Calling API: %v", err))
|
|
}
|
|
|
|
ctx = core.LogResponse(ctx)
|
|
|
|
tflog.Info(ctx, "Postgres Flex database deleted")
|
|
}
|
|
|
|
// 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 *databaseResource) 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 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,
|
|
&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.",
|
|
)
|
|
|
|
tflog.Info(ctx, "Postgres Flex database state imported")
|
|
|
|
return
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
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.
|
|
func (r *databaseResource) extractIdentityData(
|
|
model resourceModel,
|
|
identity DatabaseResourceIdentityModel,
|
|
) (projectId, region, instanceId string, databaseId int64, err error) {
|
|
if !model.DatabaseId.IsNull() && !model.DatabaseId.IsUnknown() {
|
|
databaseId = model.DatabaseId.ValueInt64()
|
|
} else {
|
|
if identity.DatabaseID.IsNull() || identity.DatabaseID.IsUnknown() {
|
|
return "", "", "", 0, fmt.Errorf("database_id not found in config")
|
|
}
|
|
databaseId = identity.DatabaseID.ValueInt64()
|
|
}
|
|
|
|
if !model.ProjectId.IsNull() && !model.ProjectId.IsUnknown() {
|
|
projectId = model.ProjectId.ValueString()
|
|
} else {
|
|
if identity.ProjectID.IsNull() || identity.ProjectID.IsUnknown() {
|
|
return "", "", "", 0, fmt.Errorf("project_id not found in config")
|
|
}
|
|
projectId = identity.ProjectID.ValueString()
|
|
}
|
|
|
|
if !model.Region.IsNull() && !model.Region.IsUnknown() {
|
|
region = r.providerData.GetRegionWithOverride(model.Region)
|
|
} else {
|
|
if identity.Region.IsNull() || identity.Region.IsUnknown() {
|
|
return "", "", "", 0, fmt.Errorf("region not found in config")
|
|
}
|
|
region = r.providerData.GetRegionWithOverride(identity.Region)
|
|
}
|
|
|
|
if !model.InstanceId.IsNull() && !model.InstanceId.IsUnknown() {
|
|
instanceId = model.InstanceId.ValueString()
|
|
} else {
|
|
if identity.InstanceID.IsNull() || identity.InstanceID.IsUnknown() {
|
|
return "", "", "", 0, fmt.Errorf("instance_id not found in config")
|
|
}
|
|
instanceId = identity.InstanceID.ValueString()
|
|
}
|
|
return projectId, region, instanceId, databaseId, nil
|
|
}
|