package resources_gen import ( "context" "terraform-provider-nubes/internal/core" "terraform-provider-nubes/internal/resources_core" "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource/schema" "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default" "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" "github.com/hashicorp/terraform-plugin-framework/types" ) // Code generated by tools/gen_v2. DO NOT EDIT. // Service: postgres // Service ID: 90 var _ resource.Resource = &PostgresResource{} var _ resource.ResourceWithModifyPlan = &PostgresResource{} var _ resource.ResourceWithImportState = &PostgresResource{} type PostgresResource struct { client *core.UniversalClient } type PostgresModel struct { ID types.String `tfsdk:"id"` ResourceName types.String `tfsdk:"resource_name"` OperationTimeout types.String `tfsdk:"operation_timeout"` LogLevel types.String `tfsdk:"log_level"` AllowNoSSL types.Bool `tfsdk:"allow_no_s_s_l"` AppVersion types.String `tfsdk:"app_version"` AutoScale types.Bool `tfsdk:"auto_scale"` AutoScalePercentage types.Int64 `tfsdk:"auto_scale_percentage"` AutoScaleQuotaGb types.String `tfsdk:"auto_scale_quota_gb"` AutoScaleTechWindow types.Int64 `tfsdk:"auto_scale_tech_window"` EnablePgPoolerMaster types.Bool `tfsdk:"enable_pg_pooler_master"` EnablePgPoolerSlave types.Bool `tfsdk:"enable_pg_pooler_slave"` ExtBACKUPNUMTORETAIN types.Int64 `tfsdk:"ext__b_a_c_k_u_p__n_u_m__t_o__r_e_t_a_i_n"` ExtBACKUPSCHEDULE types.String `tfsdk:"ext__b_a_c_k_u_p__s_c_h_e_d_u_l_e"` IpSpaceNameMaster types.String `tfsdk:"ip_space_name_master"` IpSpaceNameSlave types.String `tfsdk:"ip_space_name_slave"` JsonParameters types.String `tfsdk:"json_parameters"` NeedExternalAddressMaster types.Bool `tfsdk:"need_external_address_master"` NeedExternalAddressSlave types.Bool `tfsdk:"need_external_address_slave"` ResourceCPU types.Int64 `tfsdk:"resource_c_p_u"` ResourceDisk types.String `tfsdk:"resource_disk"` ResourceInstances types.Int64 `tfsdk:"resource_instances"` ResourceMemory types.Int64 `tfsdk:"resource_memory"` ResourceRealm types.String `tfsdk:"resource_realm"` S3Uid types.String `tfsdk:"s3_uid"` SuspendOnDestroy types.Bool `tfsdk:"suspend_on_destroy"` AdoptExistingOnCreate types.Bool `tfsdk:"adopt_existing_on_create"` StateParams types.Map `tfsdk:"state_params"` StateOut types.Map `tfsdk:"state_out"` StateParamsFlat types.Map `tfsdk:"state_params_flat"` StateOutFlat types.Map `tfsdk:"state_out_flat"` VaultSecrets types.Map `tfsdk:"vault_secrets"` VaultUrl types.String `tfsdk:"vault_url"` VaultUserPath types.String `tfsdk:"vault_user_path"` VaultFields types.List `tfsdk:"vault_fields"` } func NewPostgresResource() resource.Resource { return &PostgresResource{} } func (r *PostgresResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { resp.TypeName = req.ProviderTypeName + "_postgres" } func (r *PostgresResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { attrs := map[string]schema.Attribute{ "id": schema.StringAttribute{Computed: true}, "resource_name": schema.StringAttribute{Required: true}, "operation_timeout": schema.StringAttribute{Optional: true}, "log_level": schema.StringAttribute{Optional: true, MarkdownDescription: "Operation stages log level: none (default), info, debug. Overrides provider-level log_level."}, "allow_no_s_s_l": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "По умолчанию подключение обязательное (sslmode=require). Выставление в true отключит этот параметр"}, "app_version": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("17"), MarkdownDescription: "Версия PostgreSQL"}, "auto_scale": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Включает автоскейлинг PV. При включении параметра необходимо настроить autoScalePercentage и autoScaleTechWindow. Алерт при срабатывании вызывает modify у текущей услуги Не изменяется после создания."}, "auto_scale_percentage": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(10), MarkdownDescription: "Требует включения autoScale. Позволяет указать в процентах расширение от текущего макс объема Не изменяется после создания."}, "auto_scale_quota_gb": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("1"), MarkdownDescription: "Квота для autoScale Не изменяется после создания."}, "auto_scale_tech_window": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(0), MarkdownDescription: "Требует включения autoScale. Окно обновления (пока не реализовано). Указывается час в виде Integer (0 / 5 / 12 / 23) Не изменяется после создания."}, "enable_pg_pooler_master": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Включает pgPooler (на запись). Будет создан новый под"}, "enable_pg_pooler_slave": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Включает pgPooler (на чтение). Будет создан новый под"}, "ext__b_a_c_k_u_p__n_u_m__t_o__r_e_t_a_i_n": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(7), MarkdownDescription: "Не обязательный. Количество сохраняемых бекапов"}, "ext__b_a_c_k_u_p__s_c_h_e_d_u_l_e": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("0 0 * * *"), MarkdownDescription: "Не обязательный. Время запуска бекапа"}, "ip_space_name_master": schema.StringAttribute{Optional: true, MarkdownDescription: "Имя ipSpace для публикации VIP master. Не может быть пустым, если включен needExternalAddressMaster. Пример: `internet-no-antiddos-v1`"}, "ip_space_name_slave": schema.StringAttribute{Optional: true, MarkdownDescription: "Имя ipSpace для публикации VIP slave. Не может быть пустым, если включен needExternalAddressSlave"}, "json_parameters": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("{ \"log_connections\": \"off\", \"log_disconnections\": \"off\" }"), MarkdownDescription: "Массив переменных, более подробнее про настройку можно посмотреть https://www.postgresql.org/docs/current/runtime-config.html", PlanModifiers: []planmodifier.String{resources_core.JsonNormalize()}}, "need_external_address_master": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Выделяет внешний (белый) IP для доступа к master"}, "need_external_address_slave": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Выделяет внешний (белый) IP для доступа к slave. Будет работать, если slave в принципе есть"}, "resource_c_p_u": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(500), MarkdownDescription: "Квота ядра пода (milicores)"}, "resource_disk": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("10"), MarkdownDescription: "Квота диска (Указывается в GIGAbytes)"}, "resource_instances": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(1), MarkdownDescription: "Количество узлов"}, "resource_memory": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(512), MarkdownDescription: "Квота памяти пода (MBytes)"}, "resource_realm": schema.StringAttribute{Required: true, MarkdownDescription: "Платформа для развертывания Не изменяется после создания."}, "s3_uid": schema.StringAttribute{Required: true, MarkdownDescription: "Экземпляр (учетная запись) S3 для резервного копирования. Резервное копирование обязательно Не изменяется после создания."}, "suspend_on_destroy": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true)}, "adopt_existing_on_create": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false)}, "state_params": schema.MapAttribute{Computed: true, ElementType: types.StringType}, "state_out": schema.MapAttribute{Computed: true, ElementType: types.StringType}, "state_params_flat": schema.MapAttribute{Computed: true, ElementType: types.StringType}, "state_out_flat": schema.MapAttribute{Computed: true, ElementType: types.StringType}, "vault_secrets": schema.MapAttribute{Computed: true, ElementType: types.StringType, Sensitive: true}, "vault_url": schema.StringAttribute{Computed: true}, "vault_user_path": schema.StringAttribute{Computed: true}, "vault_fields": schema.ListAttribute{Computed: true, ElementType: types.StringType}, } resp.Schema = schema.Schema{Attributes: attrs} } func (r *PostgresResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { if r.client == nil { return } var config *PostgresModel resp.Diagnostics.Append(req.Config.Get(ctx, &config)...) if resp.Diagnostics.HasError() { return } if config == nil { return } var state *PostgresModel resp.Diagnostics.Append(req.State.Get(ctx, &state)...) if resp.Diagnostics.HasError() { return } if req.State.Raw.IsNull() && req.Plan.Raw.IsNull() { return } if state != nil && !state.ID.IsNull() && !state.ID.IsUnknown() { var plan PostgresModel resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) if resp.Diagnostics.HasError() { return } planChanged := false if !plan.S3Uid.IsNull() && !plan.S3Uid.IsUnknown() { resolvedS3Uid, err := r.client.ResolveRefSvcParamValue(ctx, 12, plan.S3Uid.ValueString()) if err != nil { resp.Diagnostics.AddWarning("Failed to resolve s3_uid", err.Error()) } else if resolvedS3Uid != "" && resolvedS3Uid != plan.S3Uid.ValueString() { plan.S3Uid = types.StringValue(resolvedS3Uid) planChanged = true } } if planChanged { resp.Diagnostics.Append(resp.Plan.Set(ctx, &plan)...) if resp.Diagnostics.HasError() { return } } if !plan.ResourceName.IsNull() && !plan.ResourceName.IsUnknown() && !state.ResourceName.IsNull() && !state.ResourceName.IsUnknown() { if plan.ResourceName.ValueString() != state.ResourceName.ValueString() { resp.Diagnostics.AddError("Нельзя изменить resource_name", "Параметр resource_name задается при создании и не может быть изменен. Создайте новый ресурс с другим именем.") return } } if !plan.AutoScale.IsNull() && !plan.AutoScale.IsUnknown() && !state.AutoScale.IsNull() && !state.AutoScale.IsUnknown() { if plan.AutoScale.ValueBool() != state.AutoScale.ValueBool() { resp.Diagnostics.AddError("Нельзя изменить auto_scale", "Параметр задается при создании и не может быть изменен.") return } } if !plan.AutoScalePercentage.IsNull() && !plan.AutoScalePercentage.IsUnknown() && !state.AutoScalePercentage.IsNull() && !state.AutoScalePercentage.IsUnknown() { if plan.AutoScalePercentage.ValueInt64() != state.AutoScalePercentage.ValueInt64() { resp.Diagnostics.AddError("Нельзя изменить auto_scale_percentage", "Параметр задается при создании и не может быть изменен.") return } } if !plan.AutoScaleQuotaGb.IsNull() && !plan.AutoScaleQuotaGb.IsUnknown() && !state.AutoScaleQuotaGb.IsNull() && !state.AutoScaleQuotaGb.IsUnknown() { if plan.AutoScaleQuotaGb.ValueString() != state.AutoScaleQuotaGb.ValueString() { resp.Diagnostics.AddError("Нельзя изменить auto_scale_quota_gb", "Параметр задается при создании и не может быть изменен.") return } } if !plan.AutoScaleTechWindow.IsNull() && !plan.AutoScaleTechWindow.IsUnknown() && !state.AutoScaleTechWindow.IsNull() && !state.AutoScaleTechWindow.IsUnknown() { if plan.AutoScaleTechWindow.ValueInt64() != state.AutoScaleTechWindow.ValueInt64() { resp.Diagnostics.AddError("Нельзя изменить auto_scale_tech_window", "Параметр задается при создании и не может быть изменен.") return } } if !plan.ResourceRealm.IsNull() && !plan.ResourceRealm.IsUnknown() && !state.ResourceRealm.IsNull() && !state.ResourceRealm.IsUnknown() { if plan.ResourceRealm.ValueString() != state.ResourceRealm.ValueString() { resp.Diagnostics.AddError("Нельзя изменить resource_realm", "Параметр задается при создании и не может быть изменен.") return } } if !plan.S3Uid.IsNull() && !plan.S3Uid.IsUnknown() && !state.S3Uid.IsNull() && !state.S3Uid.IsUnknown() { if plan.S3Uid.ValueString() != state.S3Uid.ValueString() { resp.Diagnostics.AddError("Нельзя изменить s3_uid", "Параметр задается при создании и не может быть изменен.") return } } return } if config.ResourceRealm.IsNull() || config.ResourceRealm.IsUnknown() { resp.Diagnostics.AddError("Missing required attribute", "resource_realm is required.") return } if config.S3Uid.IsNull() || config.S3Uid.IsUnknown() { resp.Diagnostics.AddError("Missing required attribute", "s3_uid is required.") return } if config.ResourceName.IsNull() || config.ResourceName.IsUnknown() { return } adoptExistingOnCreate := false if !config.AdoptExistingOnCreate.IsNull() && !config.AdoptExistingOnCreate.IsUnknown() { adoptExistingOnCreate = config.AdoptExistingOnCreate.ValueBool() } if !config.S3Uid.IsNull() && !config.S3Uid.IsUnknown() { resolvedS3Uid, err := r.client.ResolveRefSvcParamValue(ctx, 12, config.S3Uid.ValueString()) if err != nil { resp.Diagnostics.AddWarning("Failed to resolve s3_uid", err.Error()) } else if resolvedS3Uid != "" && resolvedS3Uid != config.S3Uid.ValueString() { config.S3Uid = types.StringValue(resolvedS3Uid) } } params := map[int]string{ 23: resources_core.FormatString(config.S3Uid), 80: resources_core.FormatInt64(config.ResourceInstances), 81: resources_core.FormatInt64(config.ResourceMemory), 82: resources_core.FormatInt64(config.ResourceCPU), 83: resources_core.FormatString(config.ResourceDisk), 102: resources_core.FormatString(config.ResourceRealm), 145: resources_core.FormatBool(config.NeedExternalAddressMaster), 146: resources_core.FormatBool(config.NeedExternalAddressSlave), 265: resources_core.FormatString(config.ExtBACKUPSCHEDULE), 266: resources_core.FormatInt64(config.ExtBACKUPNUMTORETAIN), 310: resources_core.FormatString(config.AppVersion), 311: resources_core.FormatString(config.JsonParameters), 312: resources_core.FormatBool(config.EnablePgPoolerMaster), 313: resources_core.FormatBool(config.EnablePgPoolerSlave), 314: resources_core.FormatBool(config.AllowNoSSL), 329: resources_core.FormatBool(config.AutoScale), 330: resources_core.FormatInt64(config.AutoScalePercentage), 331: resources_core.FormatInt64(config.AutoScaleTechWindow), 337: resources_core.FormatString(config.IpSpaceNameMaster), 338: resources_core.FormatString(config.IpSpaceNameSlave), 339: resources_core.FormatString(config.AutoScaleQuotaGb), } desiredDomain := "" domainServiceIDs := []int{2, 50, 81, 82, 88, 89, 94, 95, 96, 97, 98, 99, 119, 149, 151, 153} resp.Diagnostics.Append(resources_core.PlanExistingResourceDiagnosticsWithParamsAndDomainAndServices(ctx, r.client, 90, config.ResourceName.ValueString(), adoptExistingOnCreate, params, desiredDomain, domainServiceIDs)...) } func (r *PostgresResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { var data PostgresModel resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } if data.ResourceRealm.IsNull() || data.ResourceRealm.IsUnknown() { resp.Diagnostics.AddError("Missing required attribute", "resource_realm is required.") return } if data.S3Uid.IsNull() || data.S3Uid.IsUnknown() { resp.Diagnostics.AddError("Missing required attribute", "s3_uid is required.") return } resourceName := data.ResourceName.ValueString() desiredDomain := "" domainServiceIDs := []int{2, 50, 81, 82, 88, 89, 94, 95, 96, 97, 98, 99, 119, 149, 151, 153} resp.Diagnostics.Append(resources_core.CreateExistingResourceDiagnosticsWithDomainAndServices(ctx, r.client, 90, resourceName, data.AdoptExistingOnCreate.ValueBool(), desiredDomain, domainServiceIDs)...) params := map[int]string{ 23: resources_core.FormatString(data.S3Uid), 80: resources_core.FormatInt64(data.ResourceInstances), 81: resources_core.FormatInt64(data.ResourceMemory), 82: resources_core.FormatInt64(data.ResourceCPU), 83: resources_core.FormatString(data.ResourceDisk), 102: resources_core.FormatString(data.ResourceRealm), 145: resources_core.FormatBool(data.NeedExternalAddressMaster), 146: resources_core.FormatBool(data.NeedExternalAddressSlave), 265: resources_core.FormatString(data.ExtBACKUPSCHEDULE), 266: resources_core.FormatInt64(data.ExtBACKUPNUMTORETAIN), 310: resources_core.FormatString(data.AppVersion), 311: resources_core.FormatString(data.JsonParameters), 312: resources_core.FormatBool(data.EnablePgPoolerMaster), 313: resources_core.FormatBool(data.EnablePgPoolerSlave), 314: resources_core.FormatBool(data.AllowNoSSL), 329: resources_core.FormatBool(data.AutoScale), 330: resources_core.FormatInt64(data.AutoScalePercentage), 331: resources_core.FormatInt64(data.AutoScaleTechWindow), 337: resources_core.FormatString(data.IpSpaceNameMaster), 338: resources_core.FormatString(data.IpSpaceNameSlave), 339: resources_core.FormatString(data.AutoScaleQuotaGb), } operationTimeout := "" if !data.OperationTimeout.IsNull() && !data.OperationTimeout.IsUnknown() { operationTimeout = data.OperationTimeout.ValueString() } if !data.LogLevel.IsNull() && !data.LogLevel.IsUnknown() { ctx = core.CtxWithLogLevel(ctx, data.LogLevel.ValueString()) } id, err := resources_core.CreateResourceWithTimeout(ctx, r.client, 90, resourceName, data.AdoptExistingOnCreate.ValueBool(), params, operationTimeout) if err != nil { resp.Diagnostics.AddError("Ошибка клиента", err.Error()) return } data.ID = types.StringValue(id) state, diags := resources_core.RefreshResourceState(ctx, r.client, id, 90, data, []resources_core.StateField{ {Code: "state_params"}, {Code: "state_out"}, {Code: "state_params_flat"}, {Code: "state_out_flat"}, {Code: "vault_secrets"}, {Code: "vault_url"}, {Code: "vault_user_path"}, {Code: "vault_fields"}, }, []resources_core.InputField{ {Code: "allowNoSSL", Field: "AllowNoSSL", Type: "bool"}, {Code: "appVersion", Field: "AppVersion", Type: "string"}, {Code: "autoScale", Field: "AutoScale", Type: "bool"}, {Code: "autoScalePercentage", Field: "AutoScalePercentage", Type: "int64"}, {Code: "autoScaleQuotaGb", Field: "AutoScaleQuotaGb", Type: "string"}, {Code: "autoScaleTechWindow", Field: "AutoScaleTechWindow", Type: "int64"}, {Code: "enablePgPoolerMaster", Field: "EnablePgPoolerMaster", Type: "bool"}, {Code: "enablePgPoolerSlave", Field: "EnablePgPoolerSlave", Type: "bool"}, {Code: "ext_BACKUP_NUM_TO_RETAIN", Field: "ExtBACKUPNUMTORETAIN", Type: "int64"}, {Code: "ext_BACKUP_SCHEDULE", Field: "ExtBACKUPSCHEDULE", Type: "string"}, {Code: "ipSpaceNameMaster", Field: "IpSpaceNameMaster", Type: "string"}, {Code: "ipSpaceNameSlave", Field: "IpSpaceNameSlave", Type: "string"}, {Code: "jsonParameters", Field: "JsonParameters", Type: "string"}, {Code: "needExternalAddressMaster", Field: "NeedExternalAddressMaster", Type: "bool"}, {Code: "needExternalAddressSlave", Field: "NeedExternalAddressSlave", Type: "bool"}, {Code: "resourceCPU", Field: "ResourceCPU", Type: "int64"}, {Code: "resourceDisk", Field: "ResourceDisk", Type: "string"}, {Code: "resourceInstances", Field: "ResourceInstances", Type: "int64"}, {Code: "resourceMemory", Field: "ResourceMemory", Type: "int64"}, {Code: "resourceRealm", Field: "ResourceRealm", Type: "string"}, }) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { return } resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) } func (r *PostgresResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { var state PostgresModel resp.Diagnostics.Append(req.State.Get(ctx, &state)...) if resp.Diagnostics.HasError() { return } if state.ID.IsNull() || state.ID.IsUnknown() { return } if r.client != nil { remove, err := resources_core.ShouldRemoveFromState(ctx, r.client, state.ID.ValueString()) if err != nil { resp.Diagnostics.AddError("Ошибка клиента", err.Error()) return } if remove { resp.State.RemoveResource(ctx) return } } newState, diags := resources_core.RefreshResourceState(ctx, r.client, state.ID.ValueString(), 90, state, []resources_core.StateField{ {Code: "state_params"}, {Code: "state_out"}, {Code: "state_params_flat"}, {Code: "state_out_flat"}, {Code: "vault_secrets"}, {Code: "vault_url"}, {Code: "vault_user_path"}, {Code: "vault_fields"}, }, []resources_core.InputField{ {Code: "allowNoSSL", Field: "AllowNoSSL", Type: "bool"}, {Code: "appVersion", Field: "AppVersion", Type: "string"}, {Code: "autoScale", Field: "AutoScale", Type: "bool"}, {Code: "autoScalePercentage", Field: "AutoScalePercentage", Type: "int64"}, {Code: "autoScaleQuotaGb", Field: "AutoScaleQuotaGb", Type: "string"}, {Code: "autoScaleTechWindow", Field: "AutoScaleTechWindow", Type: "int64"}, {Code: "enablePgPoolerMaster", Field: "EnablePgPoolerMaster", Type: "bool"}, {Code: "enablePgPoolerSlave", Field: "EnablePgPoolerSlave", Type: "bool"}, {Code: "ext_BACKUP_NUM_TO_RETAIN", Field: "ExtBACKUPNUMTORETAIN", Type: "int64"}, {Code: "ext_BACKUP_SCHEDULE", Field: "ExtBACKUPSCHEDULE", Type: "string"}, {Code: "ipSpaceNameMaster", Field: "IpSpaceNameMaster", Type: "string"}, {Code: "ipSpaceNameSlave", Field: "IpSpaceNameSlave", Type: "string"}, {Code: "jsonParameters", Field: "JsonParameters", Type: "string"}, {Code: "needExternalAddressMaster", Field: "NeedExternalAddressMaster", Type: "bool"}, {Code: "needExternalAddressSlave", Field: "NeedExternalAddressSlave", Type: "bool"}, {Code: "resourceCPU", Field: "ResourceCPU", Type: "int64"}, {Code: "resourceDisk", Field: "ResourceDisk", Type: "string"}, {Code: "resourceInstances", Field: "ResourceInstances", Type: "int64"}, {Code: "resourceMemory", Field: "ResourceMemory", Type: "int64"}, {Code: "resourceRealm", Field: "ResourceRealm", Type: "string"}, }) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { return } resp.Diagnostics.Append(resp.State.Set(ctx, &newState)...) } func (r *PostgresResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { var plan PostgresModel var state PostgresModel resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) resp.Diagnostics.Append(req.State.Get(ctx, &state)...) if resp.Diagnostics.HasError() { return } instanceID := state.ID if instanceID.IsNull() || instanceID.IsUnknown() { instanceID = plan.ID } if instanceID.IsNull() || instanceID.IsUnknown() { resp.Diagnostics.AddError("Ошибка клиента", "отсутствует идентификатор экземпляра для modify") return } hasServiceParamChanges := false if !hasServiceParamChanges { if plan.ResourceInstances.IsNull() != state.ResourceInstances.IsNull() || plan.ResourceInstances.IsUnknown() != state.ResourceInstances.IsUnknown() { hasServiceParamChanges = true } else if !plan.ResourceInstances.IsNull() && !plan.ResourceInstances.IsUnknown() && !state.ResourceInstances.IsNull() && !state.ResourceInstances.IsUnknown() { if plan.ResourceInstances.ValueInt64() != state.ResourceInstances.ValueInt64() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.ResourceMemory.IsNull() != state.ResourceMemory.IsNull() || plan.ResourceMemory.IsUnknown() != state.ResourceMemory.IsUnknown() { hasServiceParamChanges = true } else if !plan.ResourceMemory.IsNull() && !plan.ResourceMemory.IsUnknown() && !state.ResourceMemory.IsNull() && !state.ResourceMemory.IsUnknown() { if plan.ResourceMemory.ValueInt64() != state.ResourceMemory.ValueInt64() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.ResourceCPU.IsNull() != state.ResourceCPU.IsNull() || plan.ResourceCPU.IsUnknown() != state.ResourceCPU.IsUnknown() { hasServiceParamChanges = true } else if !plan.ResourceCPU.IsNull() && !plan.ResourceCPU.IsUnknown() && !state.ResourceCPU.IsNull() && !state.ResourceCPU.IsUnknown() { if plan.ResourceCPU.ValueInt64() != state.ResourceCPU.ValueInt64() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.ResourceDisk.IsNull() != state.ResourceDisk.IsNull() || plan.ResourceDisk.IsUnknown() != state.ResourceDisk.IsUnknown() { hasServiceParamChanges = true } else if !plan.ResourceDisk.IsNull() && !plan.ResourceDisk.IsUnknown() && !state.ResourceDisk.IsNull() && !state.ResourceDisk.IsUnknown() { if plan.ResourceDisk.ValueString() != state.ResourceDisk.ValueString() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.NeedExternalAddressMaster.IsNull() != state.NeedExternalAddressMaster.IsNull() || plan.NeedExternalAddressMaster.IsUnknown() != state.NeedExternalAddressMaster.IsUnknown() { hasServiceParamChanges = true } else if !plan.NeedExternalAddressMaster.IsNull() && !plan.NeedExternalAddressMaster.IsUnknown() && !state.NeedExternalAddressMaster.IsNull() && !state.NeedExternalAddressMaster.IsUnknown() { if plan.NeedExternalAddressMaster.ValueBool() != state.NeedExternalAddressMaster.ValueBool() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.NeedExternalAddressSlave.IsNull() != state.NeedExternalAddressSlave.IsNull() || plan.NeedExternalAddressSlave.IsUnknown() != state.NeedExternalAddressSlave.IsUnknown() { hasServiceParamChanges = true } else if !plan.NeedExternalAddressSlave.IsNull() && !plan.NeedExternalAddressSlave.IsUnknown() && !state.NeedExternalAddressSlave.IsNull() && !state.NeedExternalAddressSlave.IsUnknown() { if plan.NeedExternalAddressSlave.ValueBool() != state.NeedExternalAddressSlave.ValueBool() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.ExtBACKUPSCHEDULE.IsNull() != state.ExtBACKUPSCHEDULE.IsNull() || plan.ExtBACKUPSCHEDULE.IsUnknown() != state.ExtBACKUPSCHEDULE.IsUnknown() { hasServiceParamChanges = true } else if !plan.ExtBACKUPSCHEDULE.IsNull() && !plan.ExtBACKUPSCHEDULE.IsUnknown() && !state.ExtBACKUPSCHEDULE.IsNull() && !state.ExtBACKUPSCHEDULE.IsUnknown() { if plan.ExtBACKUPSCHEDULE.ValueString() != state.ExtBACKUPSCHEDULE.ValueString() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.ExtBACKUPNUMTORETAIN.IsNull() != state.ExtBACKUPNUMTORETAIN.IsNull() || plan.ExtBACKUPNUMTORETAIN.IsUnknown() != state.ExtBACKUPNUMTORETAIN.IsUnknown() { hasServiceParamChanges = true } else if !plan.ExtBACKUPNUMTORETAIN.IsNull() && !plan.ExtBACKUPNUMTORETAIN.IsUnknown() && !state.ExtBACKUPNUMTORETAIN.IsNull() && !state.ExtBACKUPNUMTORETAIN.IsUnknown() { if plan.ExtBACKUPNUMTORETAIN.ValueInt64() != state.ExtBACKUPNUMTORETAIN.ValueInt64() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.AppVersion.IsNull() != state.AppVersion.IsNull() || plan.AppVersion.IsUnknown() != state.AppVersion.IsUnknown() { hasServiceParamChanges = true } else if !plan.AppVersion.IsNull() && !plan.AppVersion.IsUnknown() && !state.AppVersion.IsNull() && !state.AppVersion.IsUnknown() { if plan.AppVersion.ValueString() != state.AppVersion.ValueString() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.JsonParameters.IsNull() != state.JsonParameters.IsNull() || plan.JsonParameters.IsUnknown() != state.JsonParameters.IsUnknown() { hasServiceParamChanges = true } else if !plan.JsonParameters.IsNull() && !plan.JsonParameters.IsUnknown() && !state.JsonParameters.IsNull() && !state.JsonParameters.IsUnknown() { if plan.JsonParameters.ValueString() != state.JsonParameters.ValueString() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.EnablePgPoolerMaster.IsNull() != state.EnablePgPoolerMaster.IsNull() || plan.EnablePgPoolerMaster.IsUnknown() != state.EnablePgPoolerMaster.IsUnknown() { hasServiceParamChanges = true } else if !plan.EnablePgPoolerMaster.IsNull() && !plan.EnablePgPoolerMaster.IsUnknown() && !state.EnablePgPoolerMaster.IsNull() && !state.EnablePgPoolerMaster.IsUnknown() { if plan.EnablePgPoolerMaster.ValueBool() != state.EnablePgPoolerMaster.ValueBool() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.EnablePgPoolerSlave.IsNull() != state.EnablePgPoolerSlave.IsNull() || plan.EnablePgPoolerSlave.IsUnknown() != state.EnablePgPoolerSlave.IsUnknown() { hasServiceParamChanges = true } else if !plan.EnablePgPoolerSlave.IsNull() && !plan.EnablePgPoolerSlave.IsUnknown() && !state.EnablePgPoolerSlave.IsNull() && !state.EnablePgPoolerSlave.IsUnknown() { if plan.EnablePgPoolerSlave.ValueBool() != state.EnablePgPoolerSlave.ValueBool() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.AllowNoSSL.IsNull() != state.AllowNoSSL.IsNull() || plan.AllowNoSSL.IsUnknown() != state.AllowNoSSL.IsUnknown() { hasServiceParamChanges = true } else if !plan.AllowNoSSL.IsNull() && !plan.AllowNoSSL.IsUnknown() && !state.AllowNoSSL.IsNull() && !state.AllowNoSSL.IsUnknown() { if plan.AllowNoSSL.ValueBool() != state.AllowNoSSL.ValueBool() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.IpSpaceNameMaster.IsNull() != state.IpSpaceNameMaster.IsNull() || plan.IpSpaceNameMaster.IsUnknown() != state.IpSpaceNameMaster.IsUnknown() { hasServiceParamChanges = true } else if !plan.IpSpaceNameMaster.IsNull() && !plan.IpSpaceNameMaster.IsUnknown() && !state.IpSpaceNameMaster.IsNull() && !state.IpSpaceNameMaster.IsUnknown() { if plan.IpSpaceNameMaster.ValueString() != state.IpSpaceNameMaster.ValueString() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.IpSpaceNameSlave.IsNull() != state.IpSpaceNameSlave.IsNull() || plan.IpSpaceNameSlave.IsUnknown() != state.IpSpaceNameSlave.IsUnknown() { hasServiceParamChanges = true } else if !plan.IpSpaceNameSlave.IsNull() && !plan.IpSpaceNameSlave.IsUnknown() && !state.IpSpaceNameSlave.IsNull() && !state.IpSpaceNameSlave.IsUnknown() { if plan.IpSpaceNameSlave.ValueString() != state.IpSpaceNameSlave.ValueString() { hasServiceParamChanges = true } } } if !hasServiceParamChanges { plan.ID = instanceID plan.StateParams = state.StateParams plan.StateOut = state.StateOut plan.StateParamsFlat = state.StateParamsFlat plan.StateOutFlat = state.StateOutFlat plan.VaultSecrets = state.VaultSecrets plan.VaultUrl = state.VaultUrl plan.VaultUserPath = state.VaultUserPath plan.VaultFields = state.VaultFields resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) return } params := map[int]string{ 91: resources_core.FormatInt64(plan.ResourceInstances), 92: resources_core.FormatInt64(plan.ResourceMemory), 93: resources_core.FormatInt64(plan.ResourceCPU), 94: resources_core.FormatString(plan.ResourceDisk), 147: resources_core.FormatBool(plan.NeedExternalAddressMaster), 148: resources_core.FormatBool(plan.NeedExternalAddressSlave), 267: resources_core.FormatString(plan.ExtBACKUPSCHEDULE), 268: resources_core.FormatInt64(plan.ExtBACKUPNUMTORETAIN), 315: resources_core.FormatString(plan.AppVersion), 316: resources_core.FormatString(plan.JsonParameters), 317: resources_core.FormatBool(plan.EnablePgPoolerMaster), 318: resources_core.FormatBool(plan.EnablePgPoolerSlave), 319: resources_core.FormatBool(plan.AllowNoSSL), 541: resources_core.FormatString(plan.IpSpaceNameMaster), 542: resources_core.FormatString(plan.IpSpaceNameSlave), } operationTimeout := "" if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { operationTimeout = plan.OperationTimeout.ValueString() } if !plan.LogLevel.IsNull() && !plan.LogLevel.IsUnknown() { ctx = core.CtxWithLogLevel(ctx, plan.LogLevel.ValueString()) } if err := resources_core.UpdateResourceWithTimeout(ctx, r.client, instanceID.ValueString(), params, operationTimeout); err != nil { resp.Diagnostics.AddError("Ошибка клиента", err.Error()) return } plan.ID = instanceID state, diags := resources_core.RefreshResourceState(ctx, r.client, instanceID.ValueString(), 90, plan, []resources_core.StateField{ {Code: "state_params"}, {Code: "state_out"}, {Code: "state_params_flat"}, {Code: "state_out_flat"}, {Code: "vault_secrets"}, {Code: "vault_url"}, {Code: "vault_user_path"}, {Code: "vault_fields"}, }, []resources_core.InputField{ {Code: "allowNoSSL", Field: "AllowNoSSL", Type: "bool"}, {Code: "appVersion", Field: "AppVersion", Type: "string"}, {Code: "autoScale", Field: "AutoScale", Type: "bool"}, {Code: "autoScalePercentage", Field: "AutoScalePercentage", Type: "int64"}, {Code: "autoScaleQuotaGb", Field: "AutoScaleQuotaGb", Type: "string"}, {Code: "autoScaleTechWindow", Field: "AutoScaleTechWindow", Type: "int64"}, {Code: "enablePgPoolerMaster", Field: "EnablePgPoolerMaster", Type: "bool"}, {Code: "enablePgPoolerSlave", Field: "EnablePgPoolerSlave", Type: "bool"}, {Code: "ext_BACKUP_NUM_TO_RETAIN", Field: "ExtBACKUPNUMTORETAIN", Type: "int64"}, {Code: "ext_BACKUP_SCHEDULE", Field: "ExtBACKUPSCHEDULE", Type: "string"}, {Code: "ipSpaceNameMaster", Field: "IpSpaceNameMaster", Type: "string"}, {Code: "ipSpaceNameSlave", Field: "IpSpaceNameSlave", Type: "string"}, {Code: "jsonParameters", Field: "JsonParameters", Type: "string"}, {Code: "needExternalAddressMaster", Field: "NeedExternalAddressMaster", Type: "bool"}, {Code: "needExternalAddressSlave", Field: "NeedExternalAddressSlave", Type: "bool"}, {Code: "resourceCPU", Field: "ResourceCPU", Type: "int64"}, {Code: "resourceDisk", Field: "ResourceDisk", Type: "string"}, {Code: "resourceInstances", Field: "ResourceInstances", Type: "int64"}, {Code: "resourceMemory", Field: "ResourceMemory", Type: "int64"}, {Code: "resourceRealm", Field: "ResourceRealm", Type: "string"}, }) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { return } resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) } func (r *PostgresResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { var state PostgresModel resp.Diagnostics.Append(req.State.Get(ctx, &state)...) if resp.Diagnostics.HasError() { return } if state.ID.IsNull() || state.ID.IsUnknown() { return } deleteMode := "state_only" if !state.SuspendOnDestroy.IsNull() && !state.SuspendOnDestroy.IsUnknown() && state.SuspendOnDestroy.ValueBool() { deleteMode = "suspend" } operationTimeout := "" if !state.OperationTimeout.IsNull() && !state.OperationTimeout.IsUnknown() { operationTimeout = state.OperationTimeout.ValueString() } if !state.LogLevel.IsNull() && !state.LogLevel.IsUnknown() { ctx = core.CtxWithLogLevel(ctx, state.LogLevel.ValueString()) } if err := resources_core.DeleteResourceWithTimeout(ctx, r.client, state.ID.ValueString(), deleteMode, operationTimeout); err != nil { resp.Diagnostics.AddError("Ошибка клиента", err.Error()) return } } func (r *PostgresResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) } func (r *PostgresResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { if req.ProviderData == nil { return } client, ok := req.ProviderData.(*core.UniversalClient) if !ok { resp.Diagnostics.AddError("Error", "Invalid client type") return } r.client = client }