Files
tf_provider/provider/internal/resources_gen/90_postgres_resource.go
T

500 lines
33 KiB
Go

package resources_gen
import (
"context"
"fmt"
"strings"
"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/resource/schema/stringplanmodifier"
"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
}
// PostgresAccessConfigurationModel — вложенная модель для map-fixed параметра accessConfiguration.
type PostgresAccessConfigurationModel struct {
MasterIpSpace types.String `tfsdk:"master_ip_space" json:"masterIpSpace"`
MasterAccessList types.String `tfsdk:"master_access_list" json:"masterAccessList"`
SlaveIpSpace types.String `tfsdk:"slave_ip_space" json:"slaveIpSpace"`
SlaveAccessList types.String `tfsdk:"slave_access_list" json:"slaveAccessList"`
}
// PostgresAutoscaleConfigurationModel — вложенная модель для map-fixed параметра autoscaleConfiguration.
type PostgresAutoscaleConfigurationModel struct {
Percent types.Int64 `tfsdk:"percent" json:"percent"`
Enabled types.Bool `tfsdk:"enabled" json:"enabled"`
Schedule types.Int64 `tfsdk:"schedule" json:"schedule"`
Quota types.Int64 `tfsdk:"quota" json:"quota"`
}
// PostgresBackupConfigurationModel — вложенная модель для map-fixed параметра backupConfiguration.
type PostgresBackupConfigurationModel struct {
S3Uid types.String `tfsdk:"s3_uid" json:"s3Uid"`
Retain types.Int64 `tfsdk:"retain" json:"retain"`
Schedule types.String `tfsdk:"schedule" json:"schedule"`
}
// PostgresClusterConfigurationModel — вложенная модель для map-fixed параметра clusterConfiguration.
type PostgresClusterConfigurationModel struct {
Memory types.Int64 `tfsdk:"memory" json:"memory"`
Replicas types.Int64 `tfsdk:"replicas" json:"replicas"`
Disk types.Int64 `tfsdk:"disk" json:"disk"`
Cpu types.Int64 `tfsdk:"cpu" json:"cpu"`
}
// PostgresMtlsConfigurationModel — вложенная модель для map-fixed параметра mtlsConfiguration.
type PostgresMtlsConfigurationModel struct {
Type types.String `tfsdk:"type" json:"type"`
DurationCA types.Int64 `tfsdk:"duration_c_a" json:"durationCA"`
DurationServer types.Int64 `tfsdk:"duration_server" json:"durationServer"`
CertCA types.String `tfsdk:"cert_c_a" json:"certCA"`
CertServer types.String `tfsdk:"cert_server" json:"certServer"`
}
// PostgresPostgresConfigurationModel — вложенная модель для map-fixed параметра postgresConfiguration.
type PostgresPostgresConfigurationModel struct {
Version types.String `tfsdk:"version" json:"version"`
SslRequired types.Bool `tfsdk:"ssl_required" json:"sslRequired"`
PoolerMaster types.Bool `tfsdk:"pooler_master" json:"poolerMaster"`
PoolerSlave types.Bool `tfsdk:"pooler_slave" json:"poolerSlave"`
}
// PostgresStartupConfigurationModel — вложенная модель для map-fixed параметра startupConfiguration.
type PostgresStartupConfigurationModel struct {
ResourceRealm types.String `tfsdk:"resource_realm" json:"resourceRealm"`
}
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"`
AccessConfiguration *PostgresAccessConfigurationModel `tfsdk:"access_configuration"`
AutoscaleConfiguration *PostgresAutoscaleConfigurationModel `tfsdk:"autoscale_configuration"`
BackupConfiguration *PostgresBackupConfigurationModel `tfsdk:"backup_configuration"`
ClusterConfiguration *PostgresClusterConfigurationModel `tfsdk:"cluster_configuration"`
MtlsConfiguration *PostgresMtlsConfigurationModel `tfsdk:"mtls_configuration"`
PostgresConf types.String `tfsdk:"postgres_conf"`
PostgresConfiguration *PostgresPostgresConfigurationModel `tfsdk:"postgres_configuration"`
StartupConfiguration *PostgresStartupConfigurationModel `tfsdk:"startup_configuration"`
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, PlanModifiers: []planmodifier.String{stringplanmodifier.UseStateForUnknown()}},
"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."},
"access_configuration": schema.SingleNestedAttribute{Required: true,
Attributes: map[string]schema.Attribute{
"master_ip_space": schema.StringAttribute{Required: true, MarkdownDescription: "Из какого Ip-Space резервировать внешний IP<br/>Список предоставляется из Организации, в котором развёрнута ресурсная платформа"},
"master_access_list": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("[]"), MarkdownDescription: "Необходимо настраивать, когда зарезервирован внешний адрес<br/>Если передан пустой массив, доступ выделяется всем"},
"slave_ip_space": schema.StringAttribute{Required: true, MarkdownDescription: "Из какого Ip-Space резервировать внешний IP<br/>Список предоставляется из Организации, в котором развёрнута ресурсная платформа"},
"slave_access_list": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("[]"), MarkdownDescription: "Необходимо настраивать, когда зарезервирован внешний адрес<br/>Если передан пустой массив, доступ выделяется всем"},
}},
"autoscale_configuration": schema.SingleNestedAttribute{Required: true,
Attributes: map[string]schema.Attribute{
"percent": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(10), MarkdownDescription: "Требует включения autoScale. Позволяет указать в процентах расширение от текущего макс объема<br/>Минимальный размер на который расширяется - **1Gb**"},
"enabled": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Включает автоскейлинг PV. При включении параметра необходимо настроить autoScalePercentage и autoScaleTechWindow. Алерт при срабатывании вызывает modify у текущей услуги"},
"schedule": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(0), MarkdownDescription: "Требует включения autoScale. Окно обновления (пока не реализовано). Указывается час в виде Integer (0 / 5 / 12 / 23)"},
"quota": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(100), MarkdownDescription: "До какого размера возможно увеличивать диск, когда включен Autoscale"},
}},
"backup_configuration": schema.SingleNestedAttribute{Required: true,
Attributes: map[string]schema.Attribute{
"s3_uid": schema.StringAttribute{Required: true, MarkdownDescription: "Экземпляр S3 обязателен"},
"retain": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(7)},
"schedule": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("0 0 * * *")},
}},
"cluster_configuration": schema.SingleNestedAttribute{Required: true,
Attributes: map[string]schema.Attribute{
"memory": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(512), MarkdownDescription: "Указывается в Megabytes"},
"replicas": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(1)},
"disk": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(10), MarkdownDescription: "Указывается в GIGAbytes"},
"cpu": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(500), MarkdownDescription: "Указывается в Milicores<br/>`1000` Mili == `1` Ядро"},
}},
"mtls_configuration": schema.SingleNestedAttribute{Optional: true, Computed: true,
Attributes: map[string]schema.Attribute{
"type": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("off"), MarkdownDescription: "`off` - Настройка MTLS производиться не будет<br/>`manual` - После создания кластера в полях данных будет запрос на создание сертификата. **Вам необходимо будет выписать сертификат через вашу CA** и уже после включить через операцию **modify** режим MTLS<br/>`auto` - Сертификаты будут созданы через Cert-Manager<br/><br/>Режимы **auto** и **manual** требует включить настройку `Включить sslMode` - **true**<br/>MTLS в режиме **auto** будет работать сразу, в режиме **manual** только после того как будет предоставлен **CA** и **Сертификат сервера**"},
"duration_c_a": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(175200), MarkdownDescription: "Указывается в **часах**<br/>Необходимо настраивать, когда параметр `Режим настройки` - **auto**"},
"duration_server": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(87600), MarkdownDescription: "Указывается в **часах**<br/>Не может быть больше чем время жизни СА<br/>Обновляется **раз в год**, если выставлено значение **более 2 лет**<br/>Обновляется **раз в пол года**, если выставлено значение **менее 2 лет**<br/>Необходимо настраивать, когда параметр `Режим настройки` - **auto**"},
"cert_c_a": schema.StringAttribute{Optional: true},
"cert_server": schema.StringAttribute{Optional: true},
}},
"postgres_conf": schema.StringAttribute{Optional: true},
"postgres_configuration": schema.SingleNestedAttribute{Required: true,
Attributes: map[string]schema.Attribute{
"version": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("17")},
"ssl_required": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true), MarkdownDescription: "По умолчанию подключение обязательное (sslmode=require)"},
"pooler_master": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Включает pgPooler (на запись). Будет создан новый под<br/>Размер пода **200m/400Mi**"},
"pooler_slave": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Включает pgPooler (на чтение). Будет создан новый под<br/>Размер пода **200m/400Mi**"},
}},
"startup_configuration": schema.SingleNestedAttribute{Required: true,
Attributes: map[string]schema.Attribute{
"resource_realm": schema.StringAttribute{Required: true, MarkdownDescription: "Кластер Kubernetes, на котором будет развернут экземпляр"},
}},
"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
}
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
}
}
return
}
if config.ResourceName.IsNull() || config.ResourceName.IsUnknown() {
return
}
adoptExistingOnCreate := false
if !config.AdoptExistingOnCreate.IsNull() && !config.AdoptExistingOnCreate.IsUnknown() {
adoptExistingOnCreate = config.AdoptExistingOnCreate.ValueBool()
}
params := map[int]string{
788: resources_core.BuildJSON(map[string]string{"memory": fmt.Sprintf("%d", config.ClusterConfiguration.Memory.ValueInt64()), "replicas": fmt.Sprintf("%d", config.ClusterConfiguration.Replicas.ValueInt64()), "disk": fmt.Sprintf("%d", config.ClusterConfiguration.Disk.ValueInt64()), "cpu": fmt.Sprintf("%d", config.ClusterConfiguration.Cpu.ValueInt64())}),
789: resources_core.BuildJSON(map[string]string{"resourceRealm": fmt.Sprintf("\"%s\"", config.StartupConfiguration.ResourceRealm.ValueString())}),
790: resources_core.BuildJSON(map[string]string{"masterIpSpace": fmt.Sprintf("\"%s\"", config.AccessConfiguration.MasterIpSpace.ValueString()), "masterAccessList": config.AccessConfiguration.MasterAccessList.ValueString(), "slaveIpSpace": fmt.Sprintf("\"%s\"", config.AccessConfiguration.SlaveIpSpace.ValueString()), "slaveAccessList": config.AccessConfiguration.SlaveAccessList.ValueString()}),
791: resources_core.BuildJSON(map[string]string{"version": fmt.Sprintf("\"%s\"", config.PostgresConfiguration.Version.ValueString()), "sslRequired": fmt.Sprintf("%v", config.PostgresConfiguration.SslRequired.ValueBool()), "poolerMaster": fmt.Sprintf("%v", config.PostgresConfiguration.PoolerMaster.ValueBool()), "poolerSlave": fmt.Sprintf("%v", config.PostgresConfiguration.PoolerSlave.ValueBool())}),
792: resources_core.FormatString(config.PostgresConf),
793: resources_core.BuildJSON(map[string]string{"s3Uid": fmt.Sprintf("\"%s\"", config.BackupConfiguration.S3Uid.ValueString()), "retain": fmt.Sprintf("%d", config.BackupConfiguration.Retain.ValueInt64()), "schedule": fmt.Sprintf("\"%s\"", config.BackupConfiguration.Schedule.ValueString())}),
794: resources_core.BuildJSON(map[string]string{"percent": fmt.Sprintf("%d", config.AutoscaleConfiguration.Percent.ValueInt64()), "enabled": fmt.Sprintf("%v", config.AutoscaleConfiguration.Enabled.ValueBool()), "schedule": fmt.Sprintf("%d", config.AutoscaleConfiguration.Schedule.ValueInt64()), "quota": fmt.Sprintf("%d", config.AutoscaleConfiguration.Quota.ValueInt64())}),
1094: resources_core.BuildJSON(map[string]string{"type": fmt.Sprintf("\"%s\"", config.MtlsConfiguration.Type.ValueString()), "durationCA": fmt.Sprintf("%d", config.MtlsConfiguration.DurationCA.ValueInt64()), "durationServer": fmt.Sprintf("%d", config.MtlsConfiguration.DurationServer.ValueInt64()), "certCA": fmt.Sprintf("\"%s\"", config.MtlsConfiguration.CertCA.ValueString()), "certServer": fmt.Sprintf("\"%s\"", config.MtlsConfiguration.CertServer.ValueString())}),
}
desiredDomain := ""
domainServiceIDs := []int{81, 82, 88, 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
}
resourceName := data.ResourceName.ValueString()
desiredDomain := ""
domainServiceIDs := []int{81, 82, 88, 96, 97, 98, 99, 119, 149, 151, 153}
resp.Diagnostics.Append(resources_core.CreateExistingResourceDiagnosticsWithDomainAndServices(ctx, r.client, 90, resourceName, data.AdoptExistingOnCreate.ValueBool(), desiredDomain, domainServiceIDs)...)
// ⛔ Проверяем HasError ДО create — при hard-error (running без adopt, suspend без adopt,
// not created, конфликт) сайд-эффект create не должен выполняться.
if resp.Diagnostics.HasError() {
return
}
params := map[int]string{
788: resources_core.BuildJSON(map[string]string{"memory": fmt.Sprintf("%d", data.ClusterConfiguration.Memory.ValueInt64()), "replicas": fmt.Sprintf("%d", data.ClusterConfiguration.Replicas.ValueInt64()), "disk": fmt.Sprintf("%d", data.ClusterConfiguration.Disk.ValueInt64()), "cpu": fmt.Sprintf("%d", data.ClusterConfiguration.Cpu.ValueInt64())}),
789: resources_core.BuildJSON(map[string]string{"resourceRealm": fmt.Sprintf("\"%s\"", data.StartupConfiguration.ResourceRealm.ValueString())}),
790: resources_core.BuildJSON(map[string]string{"masterIpSpace": fmt.Sprintf("\"%s\"", data.AccessConfiguration.MasterIpSpace.ValueString()), "masterAccessList": data.AccessConfiguration.MasterAccessList.ValueString(), "slaveIpSpace": fmt.Sprintf("\"%s\"", data.AccessConfiguration.SlaveIpSpace.ValueString()), "slaveAccessList": data.AccessConfiguration.SlaveAccessList.ValueString()}),
791: resources_core.BuildJSON(map[string]string{"version": fmt.Sprintf("\"%s\"", data.PostgresConfiguration.Version.ValueString()), "sslRequired": fmt.Sprintf("%v", data.PostgresConfiguration.SslRequired.ValueBool()), "poolerMaster": fmt.Sprintf("%v", data.PostgresConfiguration.PoolerMaster.ValueBool()), "poolerSlave": fmt.Sprintf("%v", data.PostgresConfiguration.PoolerSlave.ValueBool())}),
792: resources_core.FormatString(data.PostgresConf),
793: resources_core.BuildJSON(map[string]string{"s3Uid": fmt.Sprintf("\"%s\"", data.BackupConfiguration.S3Uid.ValueString()), "retain": fmt.Sprintf("%d", data.BackupConfiguration.Retain.ValueInt64()), "schedule": fmt.Sprintf("\"%s\"", data.BackupConfiguration.Schedule.ValueString())}),
794: resources_core.BuildJSON(map[string]string{"percent": fmt.Sprintf("%d", data.AutoscaleConfiguration.Percent.ValueInt64()), "enabled": fmt.Sprintf("%v", data.AutoscaleConfiguration.Enabled.ValueBool()), "schedule": fmt.Sprintf("%d", data.AutoscaleConfiguration.Schedule.ValueInt64()), "quota": fmt.Sprintf("%d", data.AutoscaleConfiguration.Quota.ValueInt64())}),
1094: resources_core.BuildJSON(map[string]string{"type": fmt.Sprintf("\"%s\"", data.MtlsConfiguration.Type.ValueString()), "durationCA": fmt.Sprintf("%d", data.MtlsConfiguration.DurationCA.ValueInt64()), "durationServer": fmt.Sprintf("%d", data.MtlsConfiguration.DurationServer.ValueInt64()), "certCA": fmt.Sprintf("\"%s\"", data.MtlsConfiguration.CertCA.ValueString()), "certServer": fmt.Sprintf("\"%s\"", data.MtlsConfiguration.CertServer.ValueString())}),
}
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: "accessConfiguration", Field: "AccessConfiguration", Type: "map-fixed"},
{Code: "autoscaleConfiguration", Field: "AutoscaleConfiguration", Type: "map-fixed"},
{Code: "backupConfiguration", Field: "BackupConfiguration", Type: "map-fixed"},
{Code: "clusterConfiguration", Field: "ClusterConfiguration", Type: "map-fixed"},
{Code: "mtlsConfiguration", Field: "MtlsConfiguration", Type: "map-fixed"},
{Code: "postgresConf", Field: "PostgresConf", Type: "array-map-fixed"},
{Code: "postgresConfiguration", Field: "PostgresConfiguration", Type: "map-fixed"},
{Code: "startupConfiguration", Field: "StartupConfiguration", Type: "map-fixed"},
})
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: "accessConfiguration", Field: "AccessConfiguration", Type: "map-fixed"},
{Code: "autoscaleConfiguration", Field: "AutoscaleConfiguration", Type: "map-fixed"},
{Code: "backupConfiguration", Field: "BackupConfiguration", Type: "map-fixed"},
{Code: "clusterConfiguration", Field: "ClusterConfiguration", Type: "map-fixed"},
{Code: "mtlsConfiguration", Field: "MtlsConfiguration", Type: "map-fixed"},
{Code: "postgresConf", Field: "PostgresConf", Type: "array-map-fixed"},
{Code: "postgresConfiguration", Field: "PostgresConfiguration", Type: "map-fixed"},
{Code: "startupConfiguration", Field: "StartupConfiguration", Type: "map-fixed"},
})
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.PostgresConf.IsNull() != state.PostgresConf.IsNull() || plan.PostgresConf.IsUnknown() != state.PostgresConf.IsUnknown() {
hasServiceParamChanges = true
} else if !plan.PostgresConf.IsNull() && !plan.PostgresConf.IsUnknown() && !state.PostgresConf.IsNull() && !state.PostgresConf.IsUnknown() {
if !strings.EqualFold(plan.PostgresConf.ValueString(), state.PostgresConf.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
}
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())
}
params := map[int]string{
795: resources_core.BuildJSON(map[string]string{"replicas": fmt.Sprintf("%d", plan.ClusterConfiguration.Replicas.ValueInt64()), "disk": fmt.Sprintf("%d", plan.ClusterConfiguration.Disk.ValueInt64()), "cpu": fmt.Sprintf("%d", plan.ClusterConfiguration.Cpu.ValueInt64()), "memory": fmt.Sprintf("%d", plan.ClusterConfiguration.Memory.ValueInt64())}),
796: resources_core.BuildJSON(map[string]string{"masterIpSpace": fmt.Sprintf("\"%s\"", plan.AccessConfiguration.MasterIpSpace.ValueString()), "masterAccessList": plan.AccessConfiguration.MasterAccessList.ValueString(), "slaveIpSpace": fmt.Sprintf("\"%s\"", plan.AccessConfiguration.SlaveIpSpace.ValueString()), "slaveAccessList": plan.AccessConfiguration.SlaveAccessList.ValueString()}),
797: resources_core.BuildJSON(map[string]string{"poolerSlave": fmt.Sprintf("%v", plan.PostgresConfiguration.PoolerSlave.ValueBool()), "version": fmt.Sprintf("\"%s\"", plan.PostgresConfiguration.Version.ValueString()), "sslRequired": fmt.Sprintf("%v", plan.PostgresConfiguration.SslRequired.ValueBool()), "poolerMaster": fmt.Sprintf("%v", plan.PostgresConfiguration.PoolerMaster.ValueBool())}),
798: resources_core.FormatString(plan.PostgresConf),
799: resources_core.BuildJSON(map[string]string{"s3Uid": fmt.Sprintf("\"%s\"", plan.BackupConfiguration.S3Uid.ValueString()), "retain": fmt.Sprintf("%d", plan.BackupConfiguration.Retain.ValueInt64()), "schedule": fmt.Sprintf("\"%s\"", plan.BackupConfiguration.Schedule.ValueString())}),
800: resources_core.BuildJSON(map[string]string{"enabled": fmt.Sprintf("%v", plan.AutoscaleConfiguration.Enabled.ValueBool()), "schedule": fmt.Sprintf("%d", plan.AutoscaleConfiguration.Schedule.ValueInt64()), "quota": fmt.Sprintf("%d", plan.AutoscaleConfiguration.Quota.ValueInt64()), "percent": fmt.Sprintf("%d", plan.AutoscaleConfiguration.Percent.ValueInt64())}),
1095: resources_core.BuildJSON(map[string]string{"certServer": fmt.Sprintf("\"%s\"", plan.MtlsConfiguration.CertServer.ValueString()), "type": fmt.Sprintf("\"%s\"", plan.MtlsConfiguration.Type.ValueString()), "durationCA": fmt.Sprintf("%d", plan.MtlsConfiguration.DurationCA.ValueInt64()), "durationServer": fmt.Sprintf("%d", plan.MtlsConfiguration.DurationServer.ValueInt64()), "certCA": fmt.Sprintf("\"%s\"", plan.MtlsConfiguration.CertCA.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: "accessConfiguration", Field: "AccessConfiguration", Type: "map-fixed"},
{Code: "autoscaleConfiguration", Field: "AutoscaleConfiguration", Type: "map-fixed"},
{Code: "backupConfiguration", Field: "BackupConfiguration", Type: "map-fixed"},
{Code: "clusterConfiguration", Field: "ClusterConfiguration", Type: "map-fixed"},
{Code: "mtlsConfiguration", Field: "MtlsConfiguration", Type: "map-fixed"},
{Code: "postgresConf", Field: "PostgresConf", Type: "array-map-fixed"},
{Code: "postgresConfiguration", Field: "PostgresConfiguration", Type: "map-fixed"},
{Code: "startupConfiguration", Field: "StartupConfiguration", Type: "map-fixed"},
})
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
}