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: valo_tenant // Service ID: 149 var _ resource.Resource = &ValoTenantResource{} var _ resource.ResourceWithModifyPlan = &ValoTenantResource{} var _ resource.ResourceWithImportState = &ValoTenantResource{} type ValoTenantResource struct { client *core.UniversalClient } // ValoTenantValoOptionsModel — вложенная модель для map-fixed параметра valoOptions. type ValoTenantValoOptionsModel struct { UserCount types.Int64 `tfsdk:"user_count" json:"userCount"` RequestApproveMaxPeriod types.Int64 `tfsdk:"request_approve_max_period" json:"requestApproveMaxPeriod"` FfOnlineEditor types.Bool `tfsdk:"ff_online_editor" json:"ffOnlineEditor"` FfWatermark types.Bool `tfsdk:"ff_watermark" json:"ffWatermark"` FfUserImport types.Bool `tfsdk:"ff_user_import" json:"ffUserImport"` FfThemes types.Bool `tfsdk:"ff_themes" json:"ffThemes"` FfPublicLink types.Bool `tfsdk:"ff_public_link" json:"ffPublicLink"` FfLogging types.Bool `tfsdk:"ff_logging" json:"ffLogging"` } type ValoTenantModel 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"` ResourceRealm types.String `tfsdk:"resource_realm"` S3Storage types.Int64 `tfsdk:"s3_storage"` ValoOptions *ValoTenantValoOptionsModel `tfsdk:"valo_options"` 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 NewValoTenantResource() resource.Resource { return &ValoTenantResource{} } func (r *ValoTenantResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { resp.TypeName = req.ProviderTypeName + "_valo_tenant" } func (r *ValoTenantResource) 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{Required: true, MarkdownDescription: "Будет добавлено в зону valo.ngcloud.ru Не изменяется после создания."}, "resource_realm": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("valo.ngcloud.ru"), MarkdownDescription: "Не изменяется после создания."}, "s3_storage": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(10), MarkdownDescription: "Параметр указывается в `Gb`"}, "valo_options": schema.SingleNestedAttribute{Optional: true, Computed: true, Attributes: map[string]schema.Attribute{ "user_count": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(10)}, "request_approve_max_period": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(2), MarkdownDescription: "Максимальное значение периода согласования (в днях)"}, "ff_online_editor": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true), MarkdownDescription: "Тарифная опция"}, "ff_watermark": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true), MarkdownDescription: "Тарифная опция"}, "ff_user_import": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true), MarkdownDescription: "Тарифная опция"}, "ff_themes": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true), MarkdownDescription: "Тарифная опция"}, "ff_public_link": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true), MarkdownDescription: "Тарифная опция"}, "ff_logging": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true), MarkdownDescription: "Тарифная опция"}, }}, "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 *ValoTenantResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { if r.client == nil { return } var config *ValoTenantModel resp.Diagnostics.Append(req.Config.Get(ctx, &config)...) if resp.Diagnostics.HasError() { return } if config == nil { return } var state *ValoTenantModel 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 ValoTenantModel 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 } } 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.ResourceRealm.IsNull() && !plan.ResourceRealm.IsUnknown() && !state.ResourceRealm.IsNull() && !state.ResourceRealm.IsUnknown() { // FIX(uuid-case): сравниваем без учёта регистра — API возвращает UUID // в lowercase, пользователь мог написать upper/mixed. Это одно и то же // значение, менять его нельзя только если оно реально другое. if !strings.EqualFold(plan.ResourceRealm.ValueString(), state.ResourceRealm.ValueString()) { resp.Diagnostics.AddError("Нельзя изменить resource_realm", "Параметр задается при создании и не может быть изменен.") return } } return } if config.Domain.IsNull() { resp.Diagnostics.AddError("Missing required attribute", "domain is required.") return } if config.Domain.IsUnknown() { 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{ 655: resources_core.FormatString(config.ResourceRealm), 656: resources_core.FormatString(config.Domain), 657: resources_core.BuildJSON(map[string]string{"userCount": fmt.Sprintf("%d", config.ValoOptions.UserCount.ValueInt64()), "requestApproveMaxPeriod": fmt.Sprintf("%d", config.ValoOptions.RequestApproveMaxPeriod.ValueInt64()), "ffOnlineEditor": fmt.Sprintf("%v", config.ValoOptions.FfOnlineEditor.ValueBool()), "ffWatermark": fmt.Sprintf("%v", config.ValoOptions.FfWatermark.ValueBool()), "ffUserImport": fmt.Sprintf("%v", config.ValoOptions.FfUserImport.ValueBool()), "ffThemes": fmt.Sprintf("%v", config.ValoOptions.FfThemes.ValueBool()), "ffPublicLink": fmt.Sprintf("%v", config.ValoOptions.FfPublicLink.ValueBool()), "ffLogging": fmt.Sprintf("%v", config.ValoOptions.FfLogging.ValueBool())}), 658: resources_core.FormatInt64(config.S3Storage), } 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, 149, config.ResourceName.ValueString(), adoptExistingOnCreate, params, desiredDomain, domainServiceIDs)...) } func (r *ValoTenantResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { var data ValoTenantModel resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } if data.Domain.IsNull() || data.Domain.IsUnknown() { resp.Diagnostics.AddError("Missing required attribute", "domain is required.") return } 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, 149, 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{ 655: resources_core.FormatString(data.ResourceRealm), 656: resources_core.FormatString(data.Domain), 657: resources_core.BuildJSON(map[string]string{"userCount": fmt.Sprintf("%d", data.ValoOptions.UserCount.ValueInt64()), "requestApproveMaxPeriod": fmt.Sprintf("%d", data.ValoOptions.RequestApproveMaxPeriod.ValueInt64()), "ffOnlineEditor": fmt.Sprintf("%v", data.ValoOptions.FfOnlineEditor.ValueBool()), "ffWatermark": fmt.Sprintf("%v", data.ValoOptions.FfWatermark.ValueBool()), "ffUserImport": fmt.Sprintf("%v", data.ValoOptions.FfUserImport.ValueBool()), "ffThemes": fmt.Sprintf("%v", data.ValoOptions.FfThemes.ValueBool()), "ffPublicLink": fmt.Sprintf("%v", data.ValoOptions.FfPublicLink.ValueBool()), "ffLogging": fmt.Sprintf("%v", data.ValoOptions.FfLogging.ValueBool())}), 658: resources_core.FormatInt64(data.S3Storage), } 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, 149, 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, 149, 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: "resourceRealm", Field: "ResourceRealm", Type: "string"}, {Code: "s3Storage", Field: "S3Storage", Type: "int64"}, {Code: "valoOptions", Field: "ValoOptions", Type: "map-fixed"}, }) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { return } resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) } func (r *ValoTenantResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { var state ValoTenantModel 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(), 149, 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: "resourceRealm", Field: "ResourceRealm", Type: "string"}, {Code: "s3Storage", Field: "S3Storage", Type: "int64"}, {Code: "valoOptions", Field: "ValoOptions", Type: "map-fixed"}, }) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { return } resp.Diagnostics.Append(resp.State.Set(ctx, &newState)...) } func (r *ValoTenantResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { var plan ValoTenantModel var state ValoTenantModel 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.S3Storage.IsNull() != state.S3Storage.IsNull() || plan.S3Storage.IsUnknown() != state.S3Storage.IsUnknown() { hasServiceParamChanges = true } else if !plan.S3Storage.IsNull() && !plan.S3Storage.IsUnknown() && !state.S3Storage.IsNull() && !state.S3Storage.IsUnknown() { if plan.S3Storage.ValueInt64() != state.S3Storage.ValueInt64() { 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{ 659: resources_core.BuildJSON(map[string]string{"ffUserImport": fmt.Sprintf("%v", plan.ValoOptions.FfUserImport.ValueBool()), "ffThemes": fmt.Sprintf("%v", plan.ValoOptions.FfThemes.ValueBool()), "ffPublicLink": fmt.Sprintf("%v", plan.ValoOptions.FfPublicLink.ValueBool()), "ffLogging": fmt.Sprintf("%v", plan.ValoOptions.FfLogging.ValueBool()), "userCount": fmt.Sprintf("%d", plan.ValoOptions.UserCount.ValueInt64()), "requestApproveMaxPeriod": fmt.Sprintf("%d", plan.ValoOptions.RequestApproveMaxPeriod.ValueInt64()), "ffOnlineEditor": fmt.Sprintf("%v", plan.ValoOptions.FfOnlineEditor.ValueBool()), "ffWatermark": fmt.Sprintf("%v", plan.ValoOptions.FfWatermark.ValueBool())}), 660: resources_core.FormatInt64(plan.S3Storage), } 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(), 149, 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: "resourceRealm", Field: "ResourceRealm", Type: "string"}, {Code: "s3Storage", Field: "S3Storage", Type: "int64"}, {Code: "valoOptions", Field: "ValoOptions", Type: "map-fixed"}, }) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { return } resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) } func (r *ValoTenantResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { var state ValoTenantModel 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 *ValoTenantResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) } func (r *ValoTenantResource) 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 }