Files
tf_provider/generated/dev/go/113_vc_complex_resource.go
T

564 lines
32 KiB
Go

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: vc_complex
// Service ID: 113
var _ resource.Resource = &VcComplexResource{}
var _ resource.ResourceWithModifyPlan = &VcComplexResource{}
var _ resource.ResourceWithImportState = &VcComplexResource{}
type VcComplexResource struct {
client *core.UniversalClient
}
type VcComplexModel struct {
ID types.String `tfsdk:"id"`
ResourceName types.String `tfsdk:"resource_name"`
OperationTimeout types.String `tfsdk:"operation_timeout"`
LogLevel types.String `tfsdk:"log_level"`
CpuAllocated types.String `tfsdk:"cpu_allocated"`
CpuGuaranteed types.Int64 `tfsdk:"cpu_guaranteed"`
IpSpaceName types.String `tfsdk:"ip_space_name"`
MemAllocated types.Int64 `tfsdk:"mem_allocated"`
MemGuaranteed types.Int64 `tfsdk:"mem_guaranteed"`
NeedEnableAVI types.Bool `tfsdk:"need_enable_a_v_i"`
NeedExternalAddressSNAT types.Bool `tfsdk:"need_external_address_s_n_a_t"`
ResourceRealm types.String `tfsdk:"resource_realm"`
SegroupName types.String `tfsdk:"segroup_name"`
StorageConfig types.String `tfsdk:"storage_config"`
VIPCount types.Int64 `tfsdk:"v_i_p_count"`
VappName types.String `tfsdk:"vapp_name"`
VdcNetworkPool types.String `tfsdk:"vdc_network_pool"`
VdcProviderGateway types.String `tfsdk:"vdc_provider_gateway"`
VirtualServicesCount types.String `tfsdk:"virtual_services_count"`
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 NewVcComplexResource() resource.Resource {
return &VcComplexResource{}
}
func (r *VcComplexResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_vc_complex"
}
func (r *VcComplexResource) 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."},
"cpu_allocated": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("1"), MarkdownDescription: "шт Не изменяется после создания."},
"cpu_guaranteed": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(20), MarkdownDescription: "Не изменяется после создания."},
"ip_space_name": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("internet-ipv4-v1"), MarkdownDescription: "Имя ip Space для внешнего IP. Целесообразнее брать самый дешёвый, так как это vip для исходящего трафика. Необходимо задавать если включен needExternalAddressSNAT Не изменяется после создания."},
"mem_allocated": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(10), MarkdownDescription: "gb Не изменяется после создания."},
"mem_guaranteed": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(20), MarkdownDescription: "Не изменяется после создания."},
"need_enable_a_v_i": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Включает AVI в Cloud Director Не изменяется после создания."},
"need_external_address_s_n_a_t": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true), MarkdownDescription: "Выделяет внешний IP на Edge. Используется для SNAT всего трафика Не изменяется после создания."},
"resource_realm": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("sandbox.nubes.ru"), MarkdownDescription: "Платформа для развертывания Не изменяется после создания."},
"segroup_name": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("SEGROUP-SANDBOX-CL1-SHARED-01"), MarkdownDescription: "Наименование segroup, в котором будут выделяться пулы на AVI Не изменяется после создания."},
"storage_config": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("[{\"name\": \"\", \"size\": 1024}]"), MarkdownDescription: "Описывается как массив объектов, где описывается имя политики и её размер Не изменяется после создания.", PlanModifiers: []planmodifier.String{resources_core.JsonNormalize()}},
"v_i_p_count": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(0), MarkdownDescription: "шт Не изменяется после создания."},
"vapp_name": schema.StringAttribute{Required: true, MarkdownDescription: "Имя vApp Не изменяется после создания."},
"vdc_network_pool": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("nsxt-sandbox-geneve-np"), MarkdownDescription: "Не изменяется после создания."},
"vdc_provider_gateway": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("sandbox-v1cl1-pvdc"), MarkdownDescription: "Взять из свойств ресурсной платформы.<br/>Путь .vcd.providerVdc - взять KEY<br/><br/>providerGateway Cloud Director. Влияет ресурсы будут предоставлены. Является полем (List&lt;String&gt;) в свойствах рес. платформы ЛК, но сам параметр передаётся только как один String Не изменяется после создания."},
"virtual_services_count": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("1"), MarkdownDescription: "Кол-во виртуальных сервисов, которые выделяются на AVI. Во избежании коллапса пока выделяется до 4 Не изменяется после создания."},
"suspend_on_destroy": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false)},
"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 *VcComplexResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) {
if r.client == nil {
return
}
var config *VcComplexModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
if config == nil {
return
}
var state *VcComplexModel
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 VcComplexModel
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.CpuAllocated.IsNull() && !plan.CpuAllocated.IsUnknown() && !state.CpuAllocated.IsNull() && !state.CpuAllocated.IsUnknown() {
// FIX(uuid-case): сравниваем без учёта регистра — API возвращает UUID
// в lowercase, пользователь мог написать upper/mixed. Это одно и то же
// значение, менять его нельзя только если оно реально другое.
if !strings.EqualFold(plan.CpuAllocated.ValueString(), state.CpuAllocated.ValueString()) {
resp.Diagnostics.AddError("Нельзя изменить cpu_allocated", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.CpuGuaranteed.IsNull() && !plan.CpuGuaranteed.IsUnknown() && !state.CpuGuaranteed.IsNull() && !state.CpuGuaranteed.IsUnknown() {
if plan.CpuGuaranteed.ValueInt64() != state.CpuGuaranteed.ValueInt64() {
resp.Diagnostics.AddError("Нельзя изменить cpu_guaranteed", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.IpSpaceName.IsNull() && !plan.IpSpaceName.IsUnknown() && !state.IpSpaceName.IsNull() && !state.IpSpaceName.IsUnknown() {
// FIX(uuid-case): сравниваем без учёта регистра — API возвращает UUID
// в lowercase, пользователь мог написать upper/mixed. Это одно и то же
// значение, менять его нельзя только если оно реально другое.
if !strings.EqualFold(plan.IpSpaceName.ValueString(), state.IpSpaceName.ValueString()) {
resp.Diagnostics.AddError("Нельзя изменить ip_space_name", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.MemAllocated.IsNull() && !plan.MemAllocated.IsUnknown() && !state.MemAllocated.IsNull() && !state.MemAllocated.IsUnknown() {
if plan.MemAllocated.ValueInt64() != state.MemAllocated.ValueInt64() {
resp.Diagnostics.AddError("Нельзя изменить mem_allocated", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.MemGuaranteed.IsNull() && !plan.MemGuaranteed.IsUnknown() && !state.MemGuaranteed.IsNull() && !state.MemGuaranteed.IsUnknown() {
if plan.MemGuaranteed.ValueInt64() != state.MemGuaranteed.ValueInt64() {
resp.Diagnostics.AddError("Нельзя изменить mem_guaranteed", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.NeedEnableAVI.IsNull() && !plan.NeedEnableAVI.IsUnknown() && !state.NeedEnableAVI.IsNull() && !state.NeedEnableAVI.IsUnknown() {
if plan.NeedEnableAVI.ValueBool() != state.NeedEnableAVI.ValueBool() {
resp.Diagnostics.AddError("Нельзя изменить need_enable_a_v_i", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.NeedExternalAddressSNAT.IsNull() && !plan.NeedExternalAddressSNAT.IsUnknown() && !state.NeedExternalAddressSNAT.IsNull() && !state.NeedExternalAddressSNAT.IsUnknown() {
if plan.NeedExternalAddressSNAT.ValueBool() != state.NeedExternalAddressSNAT.ValueBool() {
resp.Diagnostics.AddError("Нельзя изменить need_external_address_s_n_a_t", "Параметр задается при создании и не может быть изменен.")
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
}
}
if !plan.SegroupName.IsNull() && !plan.SegroupName.IsUnknown() && !state.SegroupName.IsNull() && !state.SegroupName.IsUnknown() {
// FIX(uuid-case): сравниваем без учёта регистра — API возвращает UUID
// в lowercase, пользователь мог написать upper/mixed. Это одно и то же
// значение, менять его нельзя только если оно реально другое.
if !strings.EqualFold(plan.SegroupName.ValueString(), state.SegroupName.ValueString()) {
resp.Diagnostics.AddError("Нельзя изменить segroup_name", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.StorageConfig.IsNull() && !plan.StorageConfig.IsUnknown() && !state.StorageConfig.IsNull() && !state.StorageConfig.IsUnknown() {
// FIX(uuid-case): сравниваем без учёта регистра — API возвращает UUID
// в lowercase, пользователь мог написать upper/mixed. Это одно и то же
// значение, менять его нельзя только если оно реально другое.
if !strings.EqualFold(plan.StorageConfig.ValueString(), state.StorageConfig.ValueString()) {
resp.Diagnostics.AddError("Нельзя изменить storage_config", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.VIPCount.IsNull() && !plan.VIPCount.IsUnknown() && !state.VIPCount.IsNull() && !state.VIPCount.IsUnknown() {
if plan.VIPCount.ValueInt64() != state.VIPCount.ValueInt64() {
resp.Diagnostics.AddError("Нельзя изменить v_i_p_count", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.VappName.IsNull() && !plan.VappName.IsUnknown() && !state.VappName.IsNull() && !state.VappName.IsUnknown() {
// FIX(uuid-case): сравниваем без учёта регистра — API возвращает UUID
// в lowercase, пользователь мог написать upper/mixed. Это одно и то же
// значение, менять его нельзя только если оно реально другое.
if !strings.EqualFold(plan.VappName.ValueString(), state.VappName.ValueString()) {
resp.Diagnostics.AddError("Нельзя изменить vapp_name", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.VdcNetworkPool.IsNull() && !plan.VdcNetworkPool.IsUnknown() && !state.VdcNetworkPool.IsNull() && !state.VdcNetworkPool.IsUnknown() {
// FIX(uuid-case): сравниваем без учёта регистра — API возвращает UUID
// в lowercase, пользователь мог написать upper/mixed. Это одно и то же
// значение, менять его нельзя только если оно реально другое.
if !strings.EqualFold(plan.VdcNetworkPool.ValueString(), state.VdcNetworkPool.ValueString()) {
resp.Diagnostics.AddError("Нельзя изменить vdc_network_pool", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.VdcProviderGateway.IsNull() && !plan.VdcProviderGateway.IsUnknown() && !state.VdcProviderGateway.IsNull() && !state.VdcProviderGateway.IsUnknown() {
// FIX(uuid-case): сравниваем без учёта регистра — API возвращает UUID
// в lowercase, пользователь мог написать upper/mixed. Это одно и то же
// значение, менять его нельзя только если оно реально другое.
if !strings.EqualFold(plan.VdcProviderGateway.ValueString(), state.VdcProviderGateway.ValueString()) {
resp.Diagnostics.AddError("Нельзя изменить vdc_provider_gateway", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.VirtualServicesCount.IsNull() && !plan.VirtualServicesCount.IsUnknown() && !state.VirtualServicesCount.IsNull() && !state.VirtualServicesCount.IsUnknown() {
// FIX(uuid-case): сравниваем без учёта регистра — API возвращает UUID
// в lowercase, пользователь мог написать upper/mixed. Это одно и то же
// значение, менять его нельзя только если оно реально другое.
if !strings.EqualFold(plan.VirtualServicesCount.ValueString(), state.VirtualServicesCount.ValueString()) {
resp.Diagnostics.AddError("Нельзя изменить virtual_services_count", "Параметр задается при создании и не может быть изменен.")
return
}
}
return
}
if config.VappName.IsNull() {
resp.Diagnostics.AddError("Missing required attribute", "vapp_name is required.")
return
}
if config.VappName.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{
332: resources_core.FormatString(config.ResourceRealm),
334: resources_core.FormatString(config.VappName),
358: resources_core.FormatString(config.VdcProviderGateway),
359: resources_core.FormatString(config.VirtualServicesCount),
360: resources_core.FormatString(config.IpSpaceName),
399: resources_core.FormatString(config.StorageConfig),
400: resources_core.FormatString(config.VdcNetworkPool),
401: resources_core.FormatInt64(config.CpuGuaranteed),
402: resources_core.FormatInt64(config.MemGuaranteed),
403: resources_core.FormatString(config.SegroupName),
404: resources_core.FormatBool(config.NeedExternalAddressSNAT),
405: resources_core.FormatBool(config.NeedEnableAVI),
566: resources_core.FormatString(config.CpuAllocated),
567: resources_core.FormatInt64(config.MemAllocated),
568: resources_core.FormatInt64(config.VIPCount),
}
desiredDomain := ""
domainServiceIDs := []int{81, 82, 88, 96, 97, 98, 99, 119, 149, 151, 153}
resp.Diagnostics.Append(resources_core.PlanExistingResourceDiagnosticsWithParamsAndDomainAndServices(ctx, r.client, 113, config.ResourceName.ValueString(), adoptExistingOnCreate, params, desiredDomain, domainServiceIDs)...)
}
func (r *VcComplexResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var data VcComplexModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
if data.VappName.IsNull() || data.VappName.IsUnknown() {
resp.Diagnostics.AddError("Missing required attribute", "vapp_name is required.")
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, 113, 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{
332: resources_core.FormatString(data.ResourceRealm),
334: resources_core.FormatString(data.VappName),
358: resources_core.FormatString(data.VdcProviderGateway),
359: resources_core.FormatString(data.VirtualServicesCount),
360: resources_core.FormatString(data.IpSpaceName),
399: resources_core.FormatString(data.StorageConfig),
400: resources_core.FormatString(data.VdcNetworkPool),
401: resources_core.FormatInt64(data.CpuGuaranteed),
402: resources_core.FormatInt64(data.MemGuaranteed),
403: resources_core.FormatString(data.SegroupName),
404: resources_core.FormatBool(data.NeedExternalAddressSNAT),
405: resources_core.FormatBool(data.NeedEnableAVI),
566: resources_core.FormatString(data.CpuAllocated),
567: resources_core.FormatInt64(data.MemAllocated),
568: resources_core.FormatInt64(data.VIPCount),
}
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, 113, 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, 113, 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: "cpuAllocated", Field: "CpuAllocated", Type: "string"},
{Code: "cpuGuaranteed", Field: "CpuGuaranteed", Type: "int64"},
{Code: "ipSpaceName", Field: "IpSpaceName", Type: "string"},
{Code: "memAllocated", Field: "MemAllocated", Type: "int64"},
{Code: "memGuaranteed", Field: "MemGuaranteed", Type: "int64"},
{Code: "needEnableAVI", Field: "NeedEnableAVI", Type: "bool"},
{Code: "needExternalAddressSNAT", Field: "NeedExternalAddressSNAT", Type: "bool"},
{Code: "resourceRealm", Field: "ResourceRealm", Type: "string"},
{Code: "segroupName", Field: "SegroupName", Type: "string"},
{Code: "storageConfig", Field: "StorageConfig", Type: "string"},
{Code: "vIPCount", Field: "VIPCount", Type: "int64"},
{Code: "vappName", Field: "VappName", Type: "string"},
{Code: "vdcNetworkPool", Field: "VdcNetworkPool", Type: "string"},
{Code: "vdcProviderGateway", Field: "VdcProviderGateway", Type: "string"},
{Code: "virtualServicesCount", Field: "VirtualServicesCount", Type: "string"},
})
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *VcComplexResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state VcComplexModel
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(), 113, 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: "cpuAllocated", Field: "CpuAllocated", Type: "string"},
{Code: "cpuGuaranteed", Field: "CpuGuaranteed", Type: "int64"},
{Code: "ipSpaceName", Field: "IpSpaceName", Type: "string"},
{Code: "memAllocated", Field: "MemAllocated", Type: "int64"},
{Code: "memGuaranteed", Field: "MemGuaranteed", Type: "int64"},
{Code: "needEnableAVI", Field: "NeedEnableAVI", Type: "bool"},
{Code: "needExternalAddressSNAT", Field: "NeedExternalAddressSNAT", Type: "bool"},
{Code: "resourceRealm", Field: "ResourceRealm", Type: "string"},
{Code: "segroupName", Field: "SegroupName", Type: "string"},
{Code: "storageConfig", Field: "StorageConfig", Type: "string"},
{Code: "vIPCount", Field: "VIPCount", Type: "int64"},
{Code: "vappName", Field: "VappName", Type: "string"},
{Code: "vdcNetworkPool", Field: "VdcNetworkPool", Type: "string"},
{Code: "vdcProviderGateway", Field: "VdcProviderGateway", Type: "string"},
{Code: "virtualServicesCount", Field: "VirtualServicesCount", Type: "string"},
})
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &newState)...)
}
func (r *VcComplexResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan VcComplexModel
var state VcComplexModel
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 {
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{}
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(), 113, 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: "cpuAllocated", Field: "CpuAllocated", Type: "string"},
{Code: "cpuGuaranteed", Field: "CpuGuaranteed", Type: "int64"},
{Code: "ipSpaceName", Field: "IpSpaceName", Type: "string"},
{Code: "memAllocated", Field: "MemAllocated", Type: "int64"},
{Code: "memGuaranteed", Field: "MemGuaranteed", Type: "int64"},
{Code: "needEnableAVI", Field: "NeedEnableAVI", Type: "bool"},
{Code: "needExternalAddressSNAT", Field: "NeedExternalAddressSNAT", Type: "bool"},
{Code: "resourceRealm", Field: "ResourceRealm", Type: "string"},
{Code: "segroupName", Field: "SegroupName", Type: "string"},
{Code: "storageConfig", Field: "StorageConfig", Type: "string"},
{Code: "vIPCount", Field: "VIPCount", Type: "int64"},
{Code: "vappName", Field: "VappName", Type: "string"},
{Code: "vdcNetworkPool", Field: "VdcNetworkPool", Type: "string"},
{Code: "vdcProviderGateway", Field: "VdcProviderGateway", Type: "string"},
{Code: "virtualServicesCount", Field: "VirtualServicesCount", Type: "string"},
})
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *VcComplexResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state VcComplexModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if state.ID.IsNull() || state.ID.IsUnknown() {
return
}
deleteMode := "delete"
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 *VcComplexResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
func (r *VcComplexResource) 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
}