From 8d7323bbc18ea6ef88193caf2ab1041dbfaedd06 Mon Sep 17 00:00:00 2001 From: "Marcel S. Henselin" Date: Tue, 3 Feb 2026 19:00:44 +0100 Subject: [PATCH] fix: refactor to use identity and different model mapping --- cmd/cmd/build/build.go | 34 +-- cmd/main.go | 3 - sample/sqlserver/sqlserver.tf | 6 +- .../postgres-flex/alpha/database_config.yml | 5 + .../sqlserverflexalpha/instance/datasource.go | 2 +- .../sqlserverflexalpha/instance/functions.go | 246 ++++++------------ .../instance/planModifiers.yaml | 6 +- .../sqlserverflexalpha/instance/resource.go | 73 +++++- .../internal/wait/sqlserverflexalpha/wait.go | 28 +- 9 files changed, 191 insertions(+), 212 deletions(-) diff --git a/cmd/cmd/build/build.go b/cmd/cmd/build/build.go index 83e403e7..df038609 100644 --- a/cmd/cmd/build/build.go +++ b/cmd/cmd/build/build.go @@ -75,14 +75,14 @@ func (b *Builder) Build() error { slog.Info("Creating generator dir", "dir", fmt.Sprintf("%s/%s", *root, GEN_REPO_NAME)) genDir := path.Join(*root, GEN_REPO_NAME) if !b.SkipClone { - err = createGeneratorDir(GEN_REPO, genDir) + err = createGeneratorDir(GEN_REPO, genDir, b.SkipClone) if err != nil { return err } } - slog.Info("Creating oas dir", "dir", fmt.Sprintf("%s/%s", *root, OAS_REPO_NAME)) - repoDir, err := createRepoDir(genDir, OAS_REPO, OAS_REPO_NAME, !b.SkipClone) + slog.Info("Creating oas repo dir", "dir", fmt.Sprintf("%s/%s", *root, OAS_REPO_NAME)) + repoDir, err := createRepoDir(genDir, OAS_REPO, OAS_REPO_NAME, b.SkipClone) if err != nil { return fmt.Errorf("%s", err.Error()) } @@ -128,14 +128,6 @@ func (b *Builder) Build() error { } } - if !b.SkipCleanup { - slog.Info("Cleaning up", "dir", repoDir) - err = os.RemoveAll(filepath.Dir(repoDir)) - if err != nil { - return fmt.Errorf("%s", err.Error()) - } - } - slog.Info("Changing dir", "dir", genDir) err = os.Chdir(genDir) if err != nil { @@ -249,6 +241,12 @@ func (b *Builder) Build() error { slog.Error("RemoveAll", "dir", path.Join(*root, GEN_REPO_NAME), "err", err) return err } + + slog.Info("Cleaning up", "dir", repoDir) + err = os.RemoveAll(filepath.Dir(repoDir)) + if err != nil { + return fmt.Errorf("%s", err.Error()) + } } slog.Info("Done") @@ -738,9 +736,9 @@ func handleVersion(service string, match []string) (*string, *version, error) { return &resStr, &version{verString: verString, major: majVer, minor: minVer}, nil } -func createRepoDir(root, repoUrl, repoName string, doClone bool) (string, error) { +func createRepoDir(root, repoUrl, repoName string, skipClone bool) (string, error) { targetDir := path.Join(root, repoName) - if doClone { + if !skipClone { if fileExists(targetDir) { slog.Warn("target dir exists - skipping", "targetDir", targetDir) return targetDir, nil @@ -756,8 +754,14 @@ func createRepoDir(root, repoUrl, repoName string, doClone bool) (string, error) return targetDir, nil } -func createGeneratorDir(repoUrl, targetDir string) error { - if !fileExists(targetDir) { +func createGeneratorDir(repoUrl, targetDir string, skipClone bool) error { + if !skipClone { + if fileExists(targetDir) { + remErr := os.RemoveAll(targetDir) + if remErr != nil { + return remErr + } + } _, cloneErr := git.Clone( clone.Repository(repoUrl), clone.Directory(targetDir), diff --git a/cmd/main.go b/cmd/main.go index 03feed00..52753a18 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -14,9 +14,6 @@ func main() { slog.SetDefault(slog.New(slogcolor.NewHandler(os.Stderr, slogcolor.DefaultOptions))) rootCmd := cmd.NewRootCmd() - //rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - //rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") - //rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") cc.Init(&cc.Config{ RootCmd: rootCmd, diff --git a/sample/sqlserver/sqlserver.tf b/sample/sqlserver/sqlserver.tf index 365a2005..847678bb 100644 --- a/sample/sqlserver/sqlserver.tf +++ b/sample/sqlserver/sqlserver.tf @@ -34,10 +34,10 @@ resource "stackitprivatepreview_sqlserverflexalpha_instance" "msh-sna-001" { #keyring_id = stackit_kms_keyring.keyring.keyring_id #key_version = 1 # key with scope public - key_id = "fe039bcf-8d7b-431a-801d-9e81371a6b7b" + kek_key_id = "fe039bcf-8d7b-431a-801d-9e81371a6b7b" # key_id = var.key_id - keyring_id = var.keyring_id - key_version = var.key_version + kek_key_ring_id = var.keyring_id + kek_key_version = var.key_version service_account = var.sa_email } network = { diff --git a/service_specs/postgres-flex/alpha/database_config.yml b/service_specs/postgres-flex/alpha/database_config.yml index 8211b1a7..7af8d47b 100644 --- a/service_specs/postgres-flex/alpha/database_config.yml +++ b/service_specs/postgres-flex/alpha/database_config.yml @@ -18,6 +18,11 @@ resources: method: DELETE data_sources: + database: + read: + path: /v3alpha1/projects/{projectId}/regions/{region}/instances/{instanceId}/databases/{databaseId} + method: GET + databases: read: path: /v3alpha1/projects/{projectId}/regions/{region}/instances/{instanceId}/databases diff --git a/stackit/internal/services/sqlserverflexalpha/instance/datasource.go b/stackit/internal/services/sqlserverflexalpha/instance/datasource.go index 12388d57..9765d99a 100644 --- a/stackit/internal/services/sqlserverflexalpha/instance/datasource.go +++ b/stackit/internal/services/sqlserverflexalpha/instance/datasource.go @@ -278,7 +278,7 @@ func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadReques // } //} - err = mapDataSourceResponseToModel(ctx, instanceResp, &model, resp) + err = mapResponseToModel(ctx, instanceResp, &model, resp.Diagnostics) //err = mapFields(ctx, instanceResp, &model, storage, encryption, network, region) if err != nil { core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err)) diff --git a/stackit/internal/services/sqlserverflexalpha/instance/functions.go b/stackit/internal/services/sqlserverflexalpha/instance/functions.go index b351ac8a..ee75cd21 100644 --- a/stackit/internal/services/sqlserverflexalpha/instance/functions.go +++ b/stackit/internal/services/sqlserverflexalpha/instance/functions.go @@ -6,7 +6,7 @@ import ( "math" "github.com/hashicorp/terraform-plugin-framework/attr" - "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/types" sqlserverflex "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/sqlserverflexalpha" @@ -14,200 +14,103 @@ import ( sqlserverflexResGen "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/instance/resources_gen" ) -func mapCreateResponseToModel( +func mapResponseToModel( ctx context.Context, resp *sqlserverflex.GetInstanceResponse, m *sqlserverflexResGen.InstanceModel, - tfResp *resource.CreateResponse, + tfDiags diag.Diagnostics, ) error { m.BackupSchedule = types.StringValue(resp.GetBackupSchedule()) - - if resp.HasEncryption() { - m.Encryption = sqlserverflexResGen.NewEncryptionValueMust( - m.Encryption.AttributeTypes(ctx), - map[string]attr.Value{ - "kek_key_id": types.StringValue(resp.Encryption.GetKekKeyId()), - "kek_key_ring_id": types.StringValue(resp.Encryption.GetKekKeyRingId()), - "kek_key_version": types.StringValue(resp.Encryption.GetKekKeyVersion()), - "service_account": types.StringValue(resp.Encryption.GetServiceAccount()), - }, - ) - } - + m.Edition = types.StringValue(string(resp.GetEdition())) + m.Encryption = handleEncryption(m, resp) m.FlavorId = types.StringValue(resp.GetFlavorId()) m.Id = types.StringValue(resp.GetId()) m.InstanceId = types.StringValue(resp.GetId()) + m.IsDeletable = types.BoolValue(resp.GetIsDeletable()) m.Name = types.StringValue(resp.GetName()) - netAcl, diags := types.ListValueFrom(ctx, types.StringType, resp.Network.GetAcl()) - tfResp.Diagnostics.Append(diags...) + tfDiags.Append(diags...) if diags.HasError() { - return fmt.Errorf("error converting api response value") + return fmt.Errorf( + "error converting network acl response value", + ) } - - m.Network = sqlserverflexResGen.NetworkValue{ - AccessScope: types.StringValue(string(resp.Network.GetAccessScope())), - Acl: netAcl, - InstanceAddress: types.StringValue(resp.Network.GetInstanceAddress()), - RouterAddress: types.StringValue(resp.Network.GetRouterAddress()), + net, diags := sqlserverflexResGen.NewNetworkValue( + sqlserverflexResGen.NetworkValue{}.AttributeTypes(ctx), + map[string]attr.Value{ + "access_scope": types.StringValue(string(resp.Network.GetAccessScope())), + "acl": netAcl, + "instance_address": types.StringValue(resp.Network.GetInstanceAddress()), + "router_address": types.StringValue(resp.Network.GetRouterAddress()), + }, + ) + tfDiags.Append(diags...) + if diags.HasError() { + return fmt.Errorf( + "error converting network response value", + "access_scope", + types.StringValue(string(resp.Network.GetAccessScope())), + "acl", + netAcl, + "instance_address", + types.StringValue(resp.Network.GetInstanceAddress()), + "router_address", + types.StringValue(resp.Network.GetRouterAddress()), + ) } - + m.Network = net + m.Replicas = types.Int64Value(int64(resp.GetReplicas())) m.RetentionDays = types.Int64Value(resp.GetRetentionDays()) - m.Storage = sqlserverflexResGen.StorageValue{ - Class: types.StringValue(resp.Storage.GetClass()), - Size: types.Int64Value(resp.Storage.GetSize()), - } m.Status = types.StringValue(string(resp.GetStatus())) - m.Version = types.StringValue(string(resp.GetVersion())) + stor, diags := sqlserverflexResGen.NewStorageValue( + sqlserverflexResGen.StorageValue{}.AttributeTypes(ctx), + map[string]attr.Value{ + "class": types.StringValue(resp.Storage.GetClass()), + "size": types.Int64Value(resp.Storage.GetSize()), + }, + ) + tfDiags.Append(diags...) + if diags.HasError() { + return fmt.Errorf("error converting storage response value") + } + m.Storage = stor + + m.Version = types.StringValue(string(resp.GetVersion())) return nil } -func mapReadResponseToModel( - ctx context.Context, - resp *sqlserverflex.GetInstanceResponse, +func handleEncryption( m *sqlserverflexResGen.InstanceModel, - tfResp *resource.ReadResponse, -) error { - m.BackupSchedule = types.StringValue(resp.GetBackupSchedule()) - - if resp.HasEncryption() { - m.Encryption = sqlserverflexResGen.NewEncryptionValueMust( - m.Encryption.AttributeTypes(ctx), - map[string]attr.Value{ - "kek_key_id": types.StringValue(resp.Encryption.GetKekKeyId()), - "kek_key_ring_id": types.StringValue(resp.Encryption.GetKekKeyRingId()), - "kek_key_version": types.StringValue(resp.Encryption.GetKekKeyVersion()), - "service_account": types.StringValue(resp.Encryption.GetServiceAccount()), - }, - ) - } - - m.FlavorId = types.StringValue(resp.GetFlavorId()) - m.Id = types.StringValue(resp.GetId()) - m.InstanceId = types.StringValue(resp.GetId()) - m.Name = types.StringValue(resp.GetName()) - - netAcl, diags := types.ListValueFrom(ctx, types.StringType, resp.Network.GetAcl()) - tfResp.Diagnostics.Append(diags...) - if diags.HasError() { - return fmt.Errorf("error converting api response value") - } - - m.Network = sqlserverflexResGen.NetworkValue{ - AccessScope: types.StringValue(string(resp.Network.GetAccessScope())), - Acl: netAcl, - InstanceAddress: types.StringValue(resp.Network.GetInstanceAddress()), - RouterAddress: types.StringValue(resp.Network.GetRouterAddress()), - } - - m.RetentionDays = types.Int64Value(resp.GetRetentionDays()) - m.Storage = sqlserverflexResGen.StorageValue{ - Class: types.StringValue(resp.Storage.GetClass()), - Size: types.Int64Value(resp.Storage.GetSize()), - } - m.Status = types.StringValue(string(resp.GetStatus())) - m.Version = types.StringValue(string(resp.GetVersion())) - - return nil -} - -func mapUpdateResponseToModel( - ctx context.Context, resp *sqlserverflex.GetInstanceResponse, - m *sqlserverflexResGen.InstanceModel, - tfResp *resource.UpdateResponse, -) error { - m.BackupSchedule = types.StringValue(resp.GetBackupSchedule()) +) sqlserverflexResGen.EncryptionValue { + if !resp.HasEncryption() || + resp.Encryption == nil || + resp.Encryption.KekKeyId == nil || + resp.Encryption.KekKeyRingId == nil || + resp.Encryption.KekKeyVersion == nil || + resp.Encryption.ServiceAccount == nil { - if resp.HasEncryption() { - m.Encryption = sqlserverflexResGen.NewEncryptionValueMust( - m.Encryption.AttributeTypes(ctx), - map[string]attr.Value{ - "kek_key_id": types.StringValue(resp.Encryption.GetKekKeyId()), - "kek_key_ring_id": types.StringValue(resp.Encryption.GetKekKeyRingId()), - "kek_key_version": types.StringValue(resp.Encryption.GetKekKeyVersion()), - "service_account": types.StringValue(resp.Encryption.GetServiceAccount()), - }, - ) + if m.Encryption.IsNull() || m.Encryption.IsUnknown() { + return sqlserverflexResGen.NewEncryptionValueNull() + } + return m.Encryption } - m.FlavorId = types.StringValue(resp.GetFlavorId()) - m.Id = types.StringValue(resp.GetId()) - m.InstanceId = types.StringValue(resp.GetId()) - m.Name = types.StringValue(resp.GetName()) - - netAcl, diags := types.ListValueFrom(ctx, types.StringType, resp.Network.GetAcl()) - tfResp.Diagnostics.Append(diags...) - if diags.HasError() { - return fmt.Errorf("error converting api response value") + enc := sqlserverflexResGen.NewEncryptionValueNull() + if kVal, ok := resp.Encryption.GetKekKeyIdOk(); ok { + enc.KekKeyId = types.StringValue(kVal) } - - m.Network = sqlserverflexResGen.NetworkValue{ - AccessScope: types.StringValue(string(resp.Network.GetAccessScope())), - Acl: netAcl, - InstanceAddress: types.StringValue(resp.Network.GetInstanceAddress()), - RouterAddress: types.StringValue(resp.Network.GetRouterAddress()), + if kkVal, ok := resp.Encryption.GetKekKeyRingIdOk(); ok { + enc.KekKeyRingId = types.StringValue(kkVal) } - - m.RetentionDays = types.Int64Value(resp.GetRetentionDays()) - m.Storage = sqlserverflexResGen.StorageValue{ - Class: types.StringValue(resp.Storage.GetClass()), - Size: types.Int64Value(resp.Storage.GetSize()), + if kkvVal, ok := resp.Encryption.GetKekKeyVersionOk(); ok { + enc.KekKeyVersion = types.StringValue(kkvVal) } - m.Status = types.StringValue(string(resp.GetStatus())) - m.Version = types.StringValue(string(resp.GetVersion())) - - return nil -} - -func mapDataSourceResponseToModel( - ctx context.Context, - resp *sqlserverflex.GetInstanceResponse, - m *sqlserverflexResGen.InstanceModel, - tfResp *datasource.ReadResponse, -) error { - m.BackupSchedule = types.StringValue(resp.GetBackupSchedule()) - - if resp.HasEncryption() { - m.Encryption = sqlserverflexResGen.NewEncryptionValueMust( - m.Encryption.AttributeTypes(ctx), - map[string]attr.Value{ - "kek_key_id": types.StringValue(resp.Encryption.GetKekKeyId()), - "kek_key_ring_id": types.StringValue(resp.Encryption.GetKekKeyRingId()), - "kek_key_version": types.StringValue(resp.Encryption.GetKekKeyVersion()), - "service_account": types.StringValue(resp.Encryption.GetServiceAccount()), - }, - ) + if sa, ok := resp.Encryption.GetServiceAccountOk(); ok { + enc.ServiceAccount = types.StringValue(sa) } - - m.FlavorId = types.StringValue(resp.GetFlavorId()) - m.Id = types.StringValue(resp.GetId()) - m.InstanceId = types.StringValue(resp.GetId()) - m.Name = types.StringValue(resp.GetName()) - - netAcl, diags := types.ListValueFrom(ctx, types.StringType, resp.Network.GetAcl()) - tfResp.Diagnostics.Append(diags...) - if diags.HasError() { - return fmt.Errorf("error converting api response value") - } - - m.Network = sqlserverflexResGen.NetworkValue{ - AccessScope: types.StringValue(string(resp.Network.GetAccessScope())), - Acl: netAcl, - InstanceAddress: types.StringValue(resp.Network.GetInstanceAddress()), - RouterAddress: types.StringValue(resp.Network.GetRouterAddress()), - } - - m.RetentionDays = types.Int64Value(resp.GetRetentionDays()) - m.Storage = sqlserverflexResGen.StorageValue{ - Class: types.StringValue(resp.Storage.GetClass()), - Size: types.Int64Value(resp.Storage.GetSize()), - } - m.Status = types.StringValue(string(resp.GetStatus())) - m.Version = types.StringValue(string(resp.GetVersion())) - - return nil + return enc } //func mapFields( @@ -357,6 +260,7 @@ func mapDataSourceResponseToModel( //} func toCreatePayload( + ctx context.Context, model *sqlserverflexResGen.InstanceModel, ) (*sqlserverflex.CreateInstanceRequestPayload, error) { if model == nil { @@ -390,11 +294,9 @@ func toCreatePayload( ) var resList []string - aclList := model.Network.Acl.Elements() - for _, aclItem := range aclList { - if !aclItem.IsNull() && !aclItem.IsUnknown() { - resList = append(resList, aclItem.String()) - } + diags := model.Network.Acl.ElementsAs(ctx, &resList, false) + if diags.HasError() { + return nil, fmt.Errorf("error converting network acl list") } networkPayload.Acl = &resList } diff --git a/stackit/internal/services/sqlserverflexalpha/instance/planModifiers.yaml b/stackit/internal/services/sqlserverflexalpha/instance/planModifiers.yaml index 2e72ba16..71d4cbe4 100644 --- a/stackit/internal/services/sqlserverflexalpha/instance/planModifiers.yaml +++ b/stackit/internal/services/sqlserverflexalpha/instance/planModifiers.yaml @@ -21,7 +21,6 @@ fields: - name: 'name' modifiers: - 'UseStateForUnknown' - - 'RequiresReplace' - name: 'backup_schedule' modifiers: @@ -31,24 +30,28 @@ fields: validators: - validate.NoSeparator modifiers: + - 'UseStateForUnknown' - 'RequiresReplace' - name: 'encryption.kek_key_version' validators: - validate.NoSeparator modifiers: + - 'UseStateForUnknown' - 'RequiresReplace' - name: 'encryption.kek_key_ring_id' validators: - validate.NoSeparator modifiers: + - 'UseStateForUnknown' - 'RequiresReplace' - name: 'encryption.service_account' validators: - validate.NoSeparator modifiers: + - 'UseStateForUnknown' - 'RequiresReplace' - name: 'network.access_scope' @@ -76,6 +79,7 @@ fields: - name: 'region' modifiers: + - 'UseStateForUnknown' - 'RequiresReplace' - name: 'retention_days' diff --git a/stackit/internal/services/sqlserverflexalpha/instance/resource.go b/stackit/internal/services/sqlserverflexalpha/instance/resource.go index 23fd9634..66436cac 100644 --- a/stackit/internal/services/sqlserverflexalpha/instance/resource.go +++ b/stackit/internal/services/sqlserverflexalpha/instance/resource.go @@ -92,16 +92,20 @@ func (r *instanceResource) ModifyPlan( req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse, ) { // nolint:gocritic // function signature required by Terraform - var configModel sqlserverflexalpha2.InstanceModel + // skip initial empty configuration to avoid follow-up errors if req.Config.Raw.IsNull() { return } + var configModel sqlserverflexalpha2.InstanceModel resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...) if resp.Diagnostics.HasError() { return } + if req.Plan.Raw.IsNull() { + return + } var planModel sqlserverflexalpha2.InstanceModel resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...) if resp.Diagnostics.HasError() { @@ -113,6 +117,18 @@ func (r *instanceResource) ModifyPlan( return } + var identityModel InstanceResourceIdentityModel + identityModel.ProjectID = planModel.ProjectId + identityModel.Region = planModel.Region + if !planModel.InstanceId.IsNull() && !planModel.InstanceId.IsUnknown() { + identityModel.InstanceID = planModel.InstanceId + } + + resp.Diagnostics.Append(resp.Identity.Set(ctx, identityModel)...) + if resp.Diagnostics.HasError() { + return + } + resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...) if resp.Diagnostics.HasError() { return @@ -416,15 +432,22 @@ func (r *instanceResource) Create( return } + // Read identity data + var identityData InstanceResourceIdentityModel + resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...) + if resp.Diagnostics.HasError() { + return + } + ctx = core.InitProviderContext(ctx) - projectId := model.ProjectId.ValueString() - region := model.Region.ValueString() + projectId := identityData.ProjectID.ValueString() + region := identityData.Region.ValueString() ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "region", region) // Generate API request body from model - payload, err := toCreatePayload(&model) + payload, err := toCreatePayload(ctx, &model) if err != nil { core.LogAndAddError( ctx, @@ -448,6 +471,18 @@ func (r *instanceResource) Create( ctx = core.LogResponse(ctx) instanceId := *createResp.Id + + // Set data returned by API in identity + identity := InstanceResourceIdentityModel{ + ProjectID: types.StringValue(projectId), + Region: types.StringValue(region), + InstanceID: types.StringValue(instanceId), + } + resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...) + if resp.Diagnostics.HasError() { + return + } + utils.SetAndLogStateFields( ctx, &resp.Diagnostics, &resp.State, map[string]any{ "id": utils.BuildInternalTerraformId(projectId, region, instanceId), @@ -466,7 +501,11 @@ func (r *instanceResource) Create( projectId, instanceId, region, - ).SetSleepBeforeWait(30 * time.Second).WaitWithContext(ctx) + ).SetSleepBeforeWait( + 30 * time.Second, + ).SetTimeout( + 90 * time.Minute, + ).WaitWithContext(ctx) if err != nil { core.LogAndAddError( ctx, @@ -489,7 +528,7 @@ func (r *instanceResource) Create( // Map response body to schema // err = mapFields(ctx, waitResp, &model, storage, encryption, network, region) - err = mapCreateResponseToModel(ctx, waitResp, &model, resp) + err = mapResponseToModel(ctx, waitResp, &model, resp.Diagnostics) if err != nil { core.LogAndAddError( ctx, @@ -522,6 +561,13 @@ func (r *instanceResource) Read( return } + // Read identity data + var identityData InstanceResourceIdentityModel + resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...) + if resp.Diagnostics.HasError() { + return + } + ctx = core.InitProviderContext(ctx) projectId := model.ProjectId.ValueString() @@ -547,7 +593,7 @@ func (r *instanceResource) Read( // Map response body to schema // err = mapFields(ctx, instanceResp, &model, storage, encryption, network, region) - err = mapReadResponseToModel(ctx, instanceResp, &model, resp) + err = mapResponseToModel(ctx, instanceResp, &model, resp.Diagnostics) if err != nil { core.LogAndAddError( ctx, @@ -563,6 +609,17 @@ func (r *instanceResource) Read( if resp.Diagnostics.HasError() { return } + + // Set data returned by API in identity + identity := InstanceResourceIdentityModel{ + ProjectID: types.StringValue(projectId), + Region: types.StringValue(region), + InstanceID: types.StringValue(instanceId), + } + resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...) + if resp.Diagnostics.HasError() { + return + } tflog.Info(ctx, "SQLServer Flex instance read") } @@ -627,7 +684,7 @@ func (r *instanceResource) Update( } // Map response body to schema - err = mapUpdateResponseToModel(ctx, waitResp, &model, resp) + err = mapResponseToModel(ctx, waitResp, &model, resp.Diagnostics) // err = mapFields(ctx, waitResp, &model, storage, encryption, network, region) if err != nil { core.LogAndAddError( diff --git a/stackit/internal/wait/sqlserverflexalpha/wait.go b/stackit/internal/wait/sqlserverflexalpha/wait.go index 7484cbe9..21bb8f70 100644 --- a/stackit/internal/wait/sqlserverflexalpha/wait.go +++ b/stackit/internal/wait/sqlserverflexalpha/wait.go @@ -44,17 +44,24 @@ func CreateInstanceWaitHandler(ctx context.Context, a APIClientInstanceInterface } switch strings.ToLower(string(*s.Status)) { case strings.ToLower(InstanceStateSuccess): - if s.Network.InstanceAddress == nil { - tflog.Info(ctx, "Waiting for instance_address") - return false, nil, nil - } - if s.Network.RouterAddress == nil { - tflog.Info(ctx, "Waiting for router_address") - return false, nil, nil + if *s.Network.AccessScope == "SNA" { + if s.Network.InstanceAddress == nil { + tflog.Info(ctx, "Waiting for instance_address") + return false, nil, nil + } + if s.Network.RouterAddress == nil { + tflog.Info(ctx, "Waiting for router_address") + return false, nil, nil + } } return true, s, nil case strings.ToLower(InstanceStateUnknown), strings.ToLower(InstanceStateFailed): return true, s, fmt.Errorf("create failed for instance with id %s", instanceId) + case strings.ToLower(InstanceStatePending), strings.ToLower(InstanceStateProcessing): + tflog.Info(ctx, "request is being handled", map[string]interface{}{ + "status": *s.Status, + }) + return false, nil, nil default: tflog.Info(ctx, "Wait (create) received unknown status", map[string]interface{}{ "instanceId": instanceId, @@ -63,8 +70,6 @@ func CreateInstanceWaitHandler(ctx context.Context, a APIClientInstanceInterface return false, s, nil } }) - handler.SetTimeout(45 * time.Minute) - handler.SetSleepBeforeWait(15 * time.Second) return handler } @@ -83,6 +88,11 @@ func UpdateInstanceWaitHandler(ctx context.Context, a APIClientInstanceInterface return true, s, nil case strings.ToLower(InstanceStateUnknown), strings.ToLower(InstanceStateFailed): return true, s, fmt.Errorf("update failed for instance with id %s", instanceId) + case strings.ToLower(InstanceStatePending), strings.ToLower(InstanceStateProcessing): + tflog.Info(ctx, "request is being handled", map[string]interface{}{ + "status": *s.Status, + }) + return false, nil, nil default: tflog.Info(ctx, "Wait (update) received unknown status", map[string]interface{}{ "instanceId": instanceId,