package resources_gen import ( "context" "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: gitea // Service ID: 99 var _ resource.Resource = &GiteaResource{} var _ resource.ResourceWithModifyPlan = &GiteaResource{} var _ resource.ResourceWithImportState = &GiteaResource{} type GiteaResource struct { client *core.UniversalClient } type GiteaModel struct { ID types.String `tfsdk:"id"` ResourceName types.String `tfsdk:"resource_name"` OperationTimeout types.String `tfsdk:"operation_timeout"` LogLevel types.String `tfsdk:"log_level"` Domain types.String `tfsdk:"domain"` IngressExtraAnnotations types.String `tfsdk:"ingress_extra_annotations"` IniServerParams types.String `tfsdk:"ini_server_params"` PsqlUid types.String `tfsdk:"psql_uid"` ResourceCPU types.Int64 `tfsdk:"resource_c_p_u"` ResourceDisk types.Int64 `tfsdk:"resource_disk"` ResourceInstances types.Int64 `tfsdk:"resource_instances"` ResourceMemory types.Int64 `tfsdk:"resource_memory"` 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 NewGiteaResource() resource.Resource { return &GiteaResource{} } func (r *GiteaResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { resp.TypeName = req.ProviderTypeName + "_gitea" } func (r *GiteaResource) 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."}, "domain": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("gitea-1"), MarkdownDescription: "Если будет указан FQDN, то происходят проверки DNS на валидность А-записи, или будет добавлено в зону resourceRealm Не изменяется после создания."}, "ingress_extra_annotations": schema.StringAttribute{Optional: true}, "ini_server_params": schema.StringAttribute{Optional: true}, "psql_uid": schema.StringAttribute{Optional: true, Computed: true, MarkdownDescription: "UUID Услуги k8sPgsql. Пользователя techGitea, базу данных gitea создаёт автоматически Не изменяется после создания."}, "resource_c_p_u": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(500), MarkdownDescription: "Квота ядра пода (Указывается в mili). 1000Mili = 1 Ядро"}, "resource_disk": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(1), 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: "Квота памяти пода (Указывается в Megabytes)"}, "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 *GiteaResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { if r.client == nil { return } var config *GiteaModel resp.Diagnostics.Append(req.Config.Get(ctx, &config)...) if resp.Diagnostics.HasError() { return } if config == nil { return } var state *GiteaModel 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 GiteaModel resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) if resp.Diagnostics.HasError() { return } // FIX(uuid-case): resolve ref_svc params НЕ делаем в ModifyPlan. // Terraform правило: plan ОБЯЗАН равняться config для user-provided атрибутов. // Resolve (displayName → UUID или uppercase → lowercase) нужен только для // API-вызова в Create/Update. Делать его здесь = менять plan = ошибка // "Provider produced invalid plan: planned value does not match config value". 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.Domain.IsNull() && !plan.Domain.IsUnknown() && !state.Domain.IsNull() && !state.Domain.IsUnknown() { // FIX(uuid-case): сравниваем без учёта регистра — API возвращает UUID // в lowercase, пользователь мог написать upper/mixed. Это одно и то же // значение, менять его нельзя только если оно реально другое. if !strings.EqualFold(plan.Domain.ValueString(), state.Domain.ValueString()) { resp.Diagnostics.AddError("Нельзя изменить domain", "Параметр задается при создании и не может быть изменен.") return } } if !plan.PsqlUid.IsNull() && !plan.PsqlUid.IsUnknown() && !state.PsqlUid.IsNull() && !state.PsqlUid.IsUnknown() { // FIX(uuid-case): сравниваем без учёта регистра — API возвращает UUID // в lowercase, пользователь мог написать upper/mixed. Это одно и то же // значение, менять его нельзя только если оно реально другое. if !strings.EqualFold(plan.PsqlUid.ValueString(), state.PsqlUid.ValueString()) { resp.Diagnostics.AddError("Нельзя изменить psql_uid", "Параметр задается при создании и не может быть изменен.") return } } return } if config.PsqlUid.IsNull() { resp.Diagnostics.AddError("Missing required attribute", "psql_uid is required.") return } if config.PsqlUid.IsUnknown() { return } if config.ResourceName.IsNull() || config.ResourceName.IsUnknown() { return } adoptExistingOnCreate := false if !config.AdoptExistingOnCreate.IsNull() && !config.AdoptExistingOnCreate.IsUnknown() { adoptExistingOnCreate = config.AdoptExistingOnCreate.ValueBool() } if !config.PsqlUid.IsNull() && !config.PsqlUid.IsUnknown() { resolvedPsqlUid, err := r.client.ResolveRefSvcParamValue(ctx, 90, config.PsqlUid.ValueString()) if err != nil { resp.Diagnostics.AddWarning("Failed to resolve psql_uid", err.Error()) } else if resolvedPsqlUid != "" && resolvedPsqlUid != config.PsqlUid.ValueString() { config.PsqlUid = types.StringValue(resolvedPsqlUid) } } params := map[int]string{ 232: resources_core.FormatInt64(config.ResourceCPU), 233: resources_core.FormatInt64(config.ResourceMemory), 234: resources_core.FormatInt64(config.ResourceDisk), 235: resources_core.FormatInt64(config.ResourceInstances), 237: resources_core.FormatString(config.Domain), 238: resources_core.FormatString(config.PsqlUid), 818: resources_core.FormatString(config.IngressExtraAnnotations), 821: resources_core.FormatString(config.IniServerParams), } desiredDomain := "" if !config.Domain.IsNull() && !config.Domain.IsUnknown() { desiredDomain = config.Domain.ValueString() } domainServiceIDs := []int{81, 82, 88, 96, 97, 98, 99, 119, 149, 151, 153} resp.Diagnostics.Append(resources_core.PlanExistingResourceDiagnosticsWithParamsAndDomainAndServices(ctx, r.client, 99, config.ResourceName.ValueString(), adoptExistingOnCreate, params, desiredDomain, domainServiceIDs)...) } func (r *GiteaResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { var data GiteaModel resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } if data.PsqlUid.IsNull() || data.PsqlUid.IsUnknown() { resp.Diagnostics.AddError("Missing required attribute", "psql_uid is required.") return } // ══════════════════════════════════════════════════════════════════════════ // ПРАВИЛО TERRAFORM (официальная документация): // «If an attribute value is configured, it is NEVER valid to change that // value in the plan.» — то есть plan ОБЯЗАН равняться config (= тому что // написал пользователь). Менять plan запрещено на уровне фреймворка. // // ПРОБЛЕМА: API нашего облака возвращает UUID в нижнем регистре. // Пользователь пишет: vapp_uid = "6214BA32-..." (верхний или смешанный). // После apply API вернул: "6214ba32-..." → state != plan → Terraform кричит: // «Provider produced inconsistent result after apply». // // РЕШЕНИЕ: корректировать STATE под PLAN, а не наоборот. // Шаг 1 (здесь): сохраняем оригинальное значение из plan ДО того как // ResolveRefSvcParamValue переведёт UUID в нижний регистр (нужен для API). // Шаг 2 (ниже, после RefreshResourceState): восстанавливаем оригинальный // регистр в state через strings.EqualFold (сравниваем без учёта регистра). // ══════════════════════════════════════════════════════════════════════════ originalPsqlUid := data.PsqlUid if !data.PsqlUid.IsNull() && !data.PsqlUid.IsUnknown() { resolvedPsqlUid, err := r.client.ResolveRefSvcParamValue(ctx, 90, data.PsqlUid.ValueString()) if err != nil { resp.Diagnostics.AddError("Ошибка клиента", err.Error()) return } if resolvedPsqlUid != "" && resolvedPsqlUid != data.PsqlUid.ValueString() { data.PsqlUid = types.StringValue(resolvedPsqlUid) } } resourceName := data.ResourceName.ValueString() desiredDomain := "" if !data.Domain.IsNull() && !data.Domain.IsUnknown() { desiredDomain = data.Domain.ValueString() } domainServiceIDs := []int{81, 82, 88, 96, 97, 98, 99, 119, 149, 151, 153} resp.Diagnostics.Append(resources_core.CreateExistingResourceDiagnosticsWithDomainAndServices(ctx, r.client, 99, 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{ 232: resources_core.FormatInt64(data.ResourceCPU), 233: resources_core.FormatInt64(data.ResourceMemory), 234: resources_core.FormatInt64(data.ResourceDisk), 235: resources_core.FormatInt64(data.ResourceInstances), 237: resources_core.FormatString(data.Domain), 238: resources_core.FormatString(data.PsqlUid), 818: resources_core.FormatString(data.IngressExtraAnnotations), 821: resources_core.FormatString(data.IniServerParams), } 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, 99, 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, 99, 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: "domain", Field: "Domain", Type: "string"}, {Code: "ingressExtraAnnotations", Field: "IngressExtraAnnotations", Type: "string"}, {Code: "iniServerParams", Field: "IniServerParams", Type: "string"}, {Code: "psqlUid", Field: "PsqlUid", Type: "string"}, {Code: "resourceCPU", Field: "ResourceCPU", Type: "int64"}, {Code: "resourceDisk", Field: "ResourceDisk", Type: "int64"}, {Code: "resourceInstances", Field: "ResourceInstances", Type: "int64"}, {Code: "resourceMemory", Field: "ResourceMemory", Type: "int64"}, }) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { return } if !state.PsqlUid.IsNull() && !state.PsqlUid.IsUnknown() { resolvedPsqlUid, err := r.client.ResolveRefSvcParamValue(ctx, 90, state.PsqlUid.ValueString()) if err != nil { resp.Diagnostics.AddWarning("Failed to resolve psql_uid", err.Error()) } else if resolvedPsqlUid != "" && resolvedPsqlUid != state.PsqlUid.ValueString() { state.PsqlUid = types.StringValue(resolvedPsqlUid) } } // Restore user-provided casing в state (Create). // EqualFold = «совпадают ли значения без учёта регистра?» // Если да — значит API вернул «туже» строку, только в другом регистре. // Заменяем state на original (то что было в plan/config пользователя). // Итог: plan=="6214BA32-..." и state=="6214BA32-..." → нет diff → нет taint. if !originalPsqlUid.IsNull() && !originalPsqlUid.IsUnknown() && !state.PsqlUid.IsNull() && !state.PsqlUid.IsUnknown() { if strings.EqualFold(state.PsqlUid.ValueString(), originalPsqlUid.ValueString()) { state.PsqlUid = originalPsqlUid } } resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) } func (r *GiteaResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { var state GiteaModel 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(), 99, 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: "domain", Field: "Domain", Type: "string"}, {Code: "ingressExtraAnnotations", Field: "IngressExtraAnnotations", Type: "string"}, {Code: "iniServerParams", Field: "IniServerParams", Type: "string"}, {Code: "psqlUid", Field: "PsqlUid", Type: "string"}, {Code: "resourceCPU", Field: "ResourceCPU", Type: "int64"}, {Code: "resourceDisk", Field: "ResourceDisk", Type: "int64"}, {Code: "resourceInstances", Field: "ResourceInstances", Type: "int64"}, {Code: "resourceMemory", Field: "ResourceMemory", Type: "int64"}, }) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { return } if !newState.PsqlUid.IsNull() && !newState.PsqlUid.IsUnknown() { resolvedPsqlUid, err := r.client.ResolveRefSvcParamValue(ctx, 90, newState.PsqlUid.ValueString()) if err != nil { resp.Diagnostics.AddWarning("Failed to resolve psql_uid", err.Error()) } else if resolvedPsqlUid != "" && resolvedPsqlUid != newState.PsqlUid.ValueString() { newState.PsqlUid = types.StringValue(resolvedPsqlUid) } } // Restore user-provided casing в state (Read). // При чтении у нас нет plan — но предыдущий state уже хранит значение // в регистре пользователя (после первого Create оно было восстановлено). // Берём prior state (переменная state) как эталон регистра. // Если API вернул то же UUID только строчными буквами — восстанавливаем. if !state.PsqlUid.IsNull() && !state.PsqlUid.IsUnknown() && !newState.PsqlUid.IsNull() && !newState.PsqlUid.IsUnknown() { if strings.EqualFold(newState.PsqlUid.ValueString(), state.PsqlUid.ValueString()) { newState.PsqlUid = state.PsqlUid } } resp.Diagnostics.Append(resp.State.Set(ctx, &newState)...) } func (r *GiteaResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { var plan GiteaModel var state GiteaModel 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.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.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.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.ValueInt64() != state.ResourceDisk.ValueInt64() { hasServiceParamChanges = true } } } 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.IngressExtraAnnotations.IsNull() != state.IngressExtraAnnotations.IsNull() || plan.IngressExtraAnnotations.IsUnknown() != state.IngressExtraAnnotations.IsUnknown() { hasServiceParamChanges = true } else if !plan.IngressExtraAnnotations.IsNull() && !plan.IngressExtraAnnotations.IsUnknown() && !state.IngressExtraAnnotations.IsNull() && !state.IngressExtraAnnotations.IsUnknown() { if !strings.EqualFold(plan.IngressExtraAnnotations.ValueString(), state.IngressExtraAnnotations.ValueString()) { hasServiceParamChanges = true } } } if !hasServiceParamChanges { if plan.IniServerParams.IsNull() != state.IniServerParams.IsNull() || plan.IniServerParams.IsUnknown() != state.IniServerParams.IsUnknown() { hasServiceParamChanges = true } else if !plan.IniServerParams.IsNull() && !plan.IniServerParams.IsUnknown() && !state.IniServerParams.IsNull() && !state.IniServerParams.IsUnknown() { if !strings.EqualFold(plan.IniServerParams.ValueString(), state.IniServerParams.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{ 259: resources_core.FormatInt64(plan.ResourceCPU), 260: resources_core.FormatInt64(plan.ResourceMemory), 261: resources_core.FormatInt64(plan.ResourceDisk), 262: resources_core.FormatInt64(plan.ResourceInstances), 819: resources_core.FormatString(plan.IngressExtraAnnotations), 820: resources_core.FormatString(plan.IniServerParams), } 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(), 99, 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: "domain", Field: "Domain", Type: "string"}, {Code: "ingressExtraAnnotations", Field: "IngressExtraAnnotations", Type: "string"}, {Code: "iniServerParams", Field: "IniServerParams", Type: "string"}, {Code: "psqlUid", Field: "PsqlUid", Type: "string"}, {Code: "resourceCPU", Field: "ResourceCPU", Type: "int64"}, {Code: "resourceDisk", Field: "ResourceDisk", Type: "int64"}, {Code: "resourceInstances", Field: "ResourceInstances", Type: "int64"}, {Code: "resourceMemory", Field: "ResourceMemory", Type: "int64"}, }) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { return } if !state.PsqlUid.IsNull() && !state.PsqlUid.IsUnknown() { resolvedPsqlUid, err := r.client.ResolveRefSvcParamValue(ctx, 90, state.PsqlUid.ValueString()) if err != nil { resp.Diagnostics.AddWarning("Failed to resolve psql_uid", err.Error()) } else if resolvedPsqlUid != "" && resolvedPsqlUid != state.PsqlUid.ValueString() { state.PsqlUid = types.StringValue(resolvedPsqlUid) } } // Restore user-provided casing в state (Update). // После API-вызова modify state содержит значения в lower-case от API. // Plan == config == то что написал пользователь (регистр неизменён). // EqualFold: если UUID совпадает без учёта регистра — берём из plan. if !plan.PsqlUid.IsNull() && !plan.PsqlUid.IsUnknown() && !state.PsqlUid.IsNull() && !state.PsqlUid.IsUnknown() { if strings.EqualFold(state.PsqlUid.ValueString(), plan.PsqlUid.ValueString()) { state.PsqlUid = plan.PsqlUid } } resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) } func (r *GiteaResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { var state GiteaModel 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 *GiteaResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) } func (r *GiteaResource) 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 }