diff --git a/universal_rebuild/internal/resources_gen/150_k8s_sthutrval_cluster_reconcile_action.go b/universal_rebuild/internal/resources_gen/150_k8s_sthutrval_cluster_reconcile_action.go new file mode 100644 index 0000000..ab84648 --- /dev/null +++ b/universal_rebuild/internal/resources_gen/150_k8s_sthutrval_cluster_reconcile_action.go @@ -0,0 +1,128 @@ +package resources_gen + +import ( + "context" + "strings" + + "terraform-provider-nubes/internal/core" + "terraform-provider-nubes/internal/resources_core" + + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Code generated by tools/gen_v2. DO NOT EDIT. +// Service: k8s_sthutrval_cluster +// Action: reconcile + +var _ resource.Resource = &K8sSthutrvalClusterReconcileResource{} + +// K8sSthutrvalClusterReconcileResource triggers a one-time action. +type K8sSthutrvalClusterReconcileResource struct { + client *core.UniversalClient +} + +type K8sSthutrvalClusterReconcileModel struct { + ID types.String `tfsdk:"id"` + K8sSthutrvalClusterID types.String `tfsdk:"k8s_sthutrval_cluster_id"` + RunID types.String `tfsdk:"run_id"` + OperationTimeout types.String `tfsdk:"operation_timeout"` +} + +func NewK8sSthutrvalClusterReconcileResource() resource.Resource { + return &K8sSthutrvalClusterReconcileResource{} +} + +func (r *K8sSthutrvalClusterReconcileResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_k8s_sthutrval_cluster_reconcile" +} + +func (r *K8sSthutrvalClusterReconcileResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + attrs := map[string]schema.Attribute{ + "id": schema.StringAttribute{Computed: true}, + "k8s_sthutrval_cluster_id": schema.StringAttribute{Required: true}, + "run_id": schema.StringAttribute{Required: true}, + "operation_timeout": schema.StringAttribute{Optional: true}, + } + resp.Schema = schema.Schema{Attributes: attrs} +} + +func (r *K8sSthutrvalClusterReconcileResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan K8sSthutrvalClusterReconcileModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + instanceUID := strings.TrimSpace(plan.K8sSthutrvalClusterID.ValueString()) + runID := strings.TrimSpace(plan.RunID.ValueString()) + if instanceUID == "" || runID == "" { + resp.Diagnostics.AddError("Ошибка клиента", "отсутствует идентификатор экземпляра или run_id") + return + } + + params := map[string]string{} + + operationTimeout := "" + if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { + operationTimeout = plan.OperationTimeout.ValueString() + } + if err := resources_core.RunOperationByCodeWithTimeout(ctx, r.client, instanceUID, "reconcile", params, operationTimeout); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + + plan.ID = types.StringValue(resources_core.BuildActionID(instanceUID, "reconcile", runID)) + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *K8sSthutrvalClusterReconcileResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state K8sSthutrvalClusterReconcileModel + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *K8sSthutrvalClusterReconcileResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan K8sSthutrvalClusterReconcileModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + instanceUID := strings.TrimSpace(plan.K8sSthutrvalClusterID.ValueString()) + runID := strings.TrimSpace(plan.RunID.ValueString()) + if instanceUID == "" || runID == "" { + resp.Diagnostics.AddError("Ошибка клиента", "отсутствует идентификатор экземпляра или run_id") + return + } + + params := map[string]string{} + + if err := resources_core.RunOperationByCode(ctx, r.client, instanceUID, "reconcile", params); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + + plan.ID = types.StringValue(resources_core.BuildActionID(instanceUID, "reconcile", runID)) + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *K8sSthutrvalClusterReconcileResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + // No-op: removing the resource does not trigger a remote action. +} + +func (r *K8sSthutrvalClusterReconcileResource) 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 +} diff --git a/universal_rebuild/internal/resources_gen/150_k8s_sthutrval_cluster_resource.go b/universal_rebuild/internal/resources_gen/150_k8s_sthutrval_cluster_resource.go new file mode 100644 index 0000000..1aea186 --- /dev/null +++ b/universal_rebuild/internal/resources_gen/150_k8s_sthutrval_cluster_resource.go @@ -0,0 +1,664 @@ +package resources_gen + +import ( + "context" + + "terraform-provider-nubes/internal/core" + "terraform-provider-nubes/internal/resources_core" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Code generated by tools/gen_v2. DO NOT EDIT. +// Service: k8s_sthutrval_cluster +// Service ID: 150 + +var _ resource.Resource = &K8sSthutrvalClusterResource{} +var _ resource.ResourceWithModifyPlan = &K8sSthutrvalClusterResource{} +var _ resource.ResourceWithImportState = &K8sSthutrvalClusterResource{} + +type K8sSthutrvalClusterResource struct { + client *core.UniversalClient +} + +type K8sSthutrvalClusterModel struct { + ID types.String `tfsdk:"id"` + ResourceName types.String `tfsdk:"resource_name"` + OperationTimeout types.String `tfsdk:"operation_timeout"` + AccessIpListAPI types.String `tfsdk:"access_ip_list_a_p_i"` + AccessIpListIngress types.String `tfsdk:"access_ip_list_ingress"` + AppVersion types.String `tfsdk:"app_version"` + ClusterName types.String `tfsdk:"cluster_name"` + ControlPlaneCount types.Int64 `tfsdk:"control_plane_count"` + ControlPlaneSizingDisk types.Int64 `tfsdk:"control_plane_sizing_disk"` + ControlPlaneSizingPolicy types.String `tfsdk:"control_plane_sizing_policy"` + NeedExternalAddressAPI types.Bool `tfsdk:"need_external_address_a_p_i"` + NeedExternalAddressIngress types.Bool `tfsdk:"need_external_address_ingress"` + NsxtUid types.String `tfsdk:"nsxt_uid"` + VdcUid types.String `tfsdk:"vdc_uid"` + WorkersCount types.Int64 `tfsdk:"workers_count"` + WorkersSizingDisk types.Int64 `tfsdk:"workers_sizing_disk"` + WorkersSizingPolicy types.String `tfsdk:"workers_sizing_policy"` + 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 NewK8sSthutrvalClusterResource() resource.Resource { + return &K8sSthutrvalClusterResource{} +} + +func (r *K8sSthutrvalClusterResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_k8s_sthutrval_cluster" +} + +func (r *K8sSthutrvalClusterResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + attrs := map[string]schema.Attribute{ + "id": schema.StringAttribute{Computed: true}, + "resource_name": schema.StringAttribute{Required: true}, + "operation_timeout": schema.StringAttribute{Optional: true}, + "access_ip_list_a_p_i": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("[]"), MarkdownDescription: "Access IP List для подключения к Kubernetes API. Указывается массив. Если передан пустой массив, доступ выделяется всем"}, + "access_ip_list_ingress": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("[]"), MarkdownDescription: "Access IP List для подключения к Ingress. Указывается массив. Если передан пустой массив, доступ выделяется всем"}, + "app_version": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("2.12.1"), MarkdownDescription: "Версия Штурвал (не является версией Kubernetes)"}, + "cluster_name": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("example1"), MarkdownDescription: "Наименование кластера Kubernetes. Имя будет использоваться в fqdn (svc.$CLUSTER_NAME) Не изменяется после создания."}, + "control_plane_count": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(1)}, + "control_plane_sizing_disk": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(30), MarkdownDescription: "Настройка Control Plane. Disk (Gb)"}, + "control_plane_sizing_policy": schema.StringAttribute{Required: true, MarkdownDescription: "Настройка Control Plane. CPU (шт) / MEM (gb).
Наверное, должна подтягиваться из свойств ресурсной платформы Не изменяется после создания."}, + "need_external_address_a_p_i": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true), MarkdownDescription: "Выделяет внешний IP для доступа к kubernetes API. Пока нельзя выставить false Не изменяется после создания."}, + "need_external_address_ingress": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true), MarkdownDescription: "Выделяет внешний IP для доступа к Ingress Не изменяется после создания."}, + "nsxt_uid": schema.StringAttribute{Required: true, MarkdownDescription: "InstanceUid nsxt. Nsxt должен быть создан Не изменяется после создания."}, + "vdc_uid": schema.StringAttribute{Required: true, MarkdownDescription: "UI display_name for service_id=21 (mapped to UUID in core) Не изменяется после создания."}, + "workers_count": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(2), MarkdownDescription: "Настройка workers. Кол-во нод"}, + "workers_sizing_disk": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(40), MarkdownDescription: "Настройка workers. Disk (Gb)"}, + "workers_sizing_policy": schema.StringAttribute{Required: true, MarkdownDescription: "Настройка workers. CPU (шт) / MEM (gb) Не изменяется после создания."}, + "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 *K8sSthutrvalClusterResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { + if r.client == nil { + return + } + + var config *K8sSthutrvalClusterModel + resp.Diagnostics.Append(req.Config.Get(ctx, &config)...) + if resp.Diagnostics.HasError() { + return + } + if config == nil { + return + } + + var state *K8sSthutrvalClusterModel + 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 K8sSthutrvalClusterModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + planChanged := false + if !plan.NsxtUid.IsNull() && !plan.NsxtUid.IsUnknown() { + resolvedNsxtUid, err := r.client.ResolveRefSvcParamValue(ctx, 22, plan.NsxtUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve nsxt_uid", err.Error()) + } else if resolvedNsxtUid != "" && resolvedNsxtUid != plan.NsxtUid.ValueString() { + plan.NsxtUid = types.StringValue(resolvedNsxtUid) + planChanged = true + } + } + if !plan.VdcUid.IsNull() && !plan.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, plan.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_uid", err.Error()) + } else if resolvedVdcUid != "" && resolvedVdcUid != plan.VdcUid.ValueString() { + plan.VdcUid = types.StringValue(resolvedVdcUid) + planChanged = true + } + } + if planChanged { + resp.Diagnostics.Append(resp.Plan.Set(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + } + if !plan.ResourceName.IsNull() && !plan.ResourceName.IsUnknown() && !state.ResourceName.IsNull() && !state.ResourceName.IsUnknown() { + if plan.ResourceName.ValueString() != state.ResourceName.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить resource_name", "Параметр resource_name задается при создании и не может быть изменен. Создайте новый ресурс с другим именем.") + return + } + } + if !plan.ClusterName.IsNull() && !plan.ClusterName.IsUnknown() && !state.ClusterName.IsNull() && !state.ClusterName.IsUnknown() { + if plan.ClusterName.ValueString() != state.ClusterName.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить cluster_name", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.ControlPlaneSizingPolicy.IsNull() && !plan.ControlPlaneSizingPolicy.IsUnknown() && !state.ControlPlaneSizingPolicy.IsNull() && !state.ControlPlaneSizingPolicy.IsUnknown() { + if plan.ControlPlaneSizingPolicy.ValueString() != state.ControlPlaneSizingPolicy.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить control_plane_sizing_policy", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.NeedExternalAddressAPI.IsNull() && !plan.NeedExternalAddressAPI.IsUnknown() && !state.NeedExternalAddressAPI.IsNull() && !state.NeedExternalAddressAPI.IsUnknown() { + if plan.NeedExternalAddressAPI.ValueBool() != state.NeedExternalAddressAPI.ValueBool() { + resp.Diagnostics.AddError("Нельзя изменить need_external_address_a_p_i", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.NeedExternalAddressIngress.IsNull() && !plan.NeedExternalAddressIngress.IsUnknown() && !state.NeedExternalAddressIngress.IsNull() && !state.NeedExternalAddressIngress.IsUnknown() { + if plan.NeedExternalAddressIngress.ValueBool() != state.NeedExternalAddressIngress.ValueBool() { + resp.Diagnostics.AddError("Нельзя изменить need_external_address_ingress", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.NsxtUid.IsNull() && !plan.NsxtUid.IsUnknown() && !state.NsxtUid.IsNull() && !state.NsxtUid.IsUnknown() { + if plan.NsxtUid.ValueString() != state.NsxtUid.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить nsxt_uid", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.VdcUid.IsNull() && !plan.VdcUid.IsUnknown() && !state.VdcUid.IsNull() && !state.VdcUid.IsUnknown() { + if plan.VdcUid.ValueString() != state.VdcUid.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить vdc_uid", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.WorkersSizingPolicy.IsNull() && !plan.WorkersSizingPolicy.IsUnknown() && !state.WorkersSizingPolicy.IsNull() && !state.WorkersSizingPolicy.IsUnknown() { + if plan.WorkersSizingPolicy.ValueString() != state.WorkersSizingPolicy.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить workers_sizing_policy", "Параметр задается при создании и не может быть изменен.") + return + } + } + return + } + if config.ControlPlaneSizingPolicy.IsNull() || config.ControlPlaneSizingPolicy.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "control_plane_sizing_policy is required.") + return + } + if config.NsxtUid.IsNull() || config.NsxtUid.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "nsxt_uid is required.") + return + } + if config.VdcUid.IsNull() || config.VdcUid.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "vdc_uid is required.") + return + } + if config.WorkersSizingPolicy.IsNull() || config.WorkersSizingPolicy.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "workers_sizing_policy is required.") + return + } + + if config.ResourceName.IsNull() || config.ResourceName.IsUnknown() { + return + } + adoptExistingOnCreate := false + if !config.AdoptExistingOnCreate.IsNull() && !config.AdoptExistingOnCreate.IsUnknown() { + adoptExistingOnCreate = config.AdoptExistingOnCreate.ValueBool() + } + if !config.NsxtUid.IsNull() && !config.NsxtUid.IsUnknown() { + resolvedNsxtUid, err := r.client.ResolveRefSvcParamValue(ctx, 22, config.NsxtUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve nsxt_uid", err.Error()) + } else if resolvedNsxtUid != "" && resolvedNsxtUid != config.NsxtUid.ValueString() { + config.NsxtUid = types.StringValue(resolvedNsxtUid) + } + } + if !config.VdcUid.IsNull() && !config.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, config.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_uid", err.Error()) + } else if resolvedVdcUid != "" && resolvedVdcUid != config.VdcUid.ValueString() { + config.VdcUid = types.StringValue(resolvedVdcUid) + } + } + params := map[int]string{ + 344: resources_core.FormatString(config.NsxtUid), + 345: resources_core.FormatString(config.ClusterName), + 346: resources_core.FormatString(config.ControlPlaneSizingPolicy), + 347: resources_core.FormatInt64(config.ControlPlaneSizingDisk), + 348: resources_core.FormatInt64(config.ControlPlaneCount), + 349: resources_core.FormatString(config.WorkersSizingPolicy), + 350: resources_core.FormatInt64(config.WorkersSizingDisk), + 351: resources_core.FormatInt64(config.WorkersCount), + 352: resources_core.FormatString(config.AppVersion), + 353: resources_core.FormatBool(config.NeedExternalAddressAPI), + 354: resources_core.FormatString(config.AccessIpListAPI), + 355: resources_core.FormatBool(config.NeedExternalAddressIngress), + 356: resources_core.FormatString(config.AccessIpListIngress), + 747: resources_core.FormatString(config.VdcUid), + } + + resp.Diagnostics.Append(resources_core.PlanExistingResourceDiagnosticsWithParams(ctx, r.client, 150, config.ResourceName.ValueString(), adoptExistingOnCreate, params)...) +} + +func (r *K8sSthutrvalClusterResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data K8sSthutrvalClusterModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + if data.ControlPlaneSizingPolicy.IsNull() || data.ControlPlaneSizingPolicy.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "control_plane_sizing_policy is required.") + return + } + if data.NsxtUid.IsNull() || data.NsxtUid.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "nsxt_uid is required.") + return + } + if data.VdcUid.IsNull() || data.VdcUid.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "vdc_uid is required.") + return + } + if data.WorkersSizingPolicy.IsNull() || data.WorkersSizingPolicy.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "workers_sizing_policy is required.") + return + } + if !data.NsxtUid.IsNull() && !data.NsxtUid.IsUnknown() { + resolvedNsxtUid, err := r.client.ResolveRefSvcParamValue(ctx, 22, data.NsxtUid.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + if resolvedNsxtUid != "" && resolvedNsxtUid != data.NsxtUid.ValueString() { + data.NsxtUid = types.StringValue(resolvedNsxtUid) + } + } + if !data.VdcUid.IsNull() && !data.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, data.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + if resolvedVdcUid != "" && resolvedVdcUid != data.VdcUid.ValueString() { + data.VdcUid = types.StringValue(resolvedVdcUid) + } + } + + resourceName := data.ResourceName.ValueString() + resp.Diagnostics.Append(resources_core.CreateExistingResourceDiagnostics(ctx, r.client, 150, resourceName, data.AdoptExistingOnCreate.ValueBool())...) + + params := map[int]string{ + 344: resources_core.FormatString(data.NsxtUid), + 345: resources_core.FormatString(data.ClusterName), + 346: resources_core.FormatString(data.ControlPlaneSizingPolicy), + 347: resources_core.FormatInt64(data.ControlPlaneSizingDisk), + 348: resources_core.FormatInt64(data.ControlPlaneCount), + 349: resources_core.FormatString(data.WorkersSizingPolicy), + 350: resources_core.FormatInt64(data.WorkersSizingDisk), + 351: resources_core.FormatInt64(data.WorkersCount), + 352: resources_core.FormatString(data.AppVersion), + 353: resources_core.FormatBool(data.NeedExternalAddressAPI), + 354: resources_core.FormatString(data.AccessIpListAPI), + 355: resources_core.FormatBool(data.NeedExternalAddressIngress), + 356: resources_core.FormatString(data.AccessIpListIngress), + 747: resources_core.FormatString(data.VdcUid), + } + + operationTimeout := "" + if !data.OperationTimeout.IsNull() && !data.OperationTimeout.IsUnknown() { + operationTimeout = data.OperationTimeout.ValueString() + } + id, err := resources_core.CreateResourceWithTimeout(ctx, r.client, 150, 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, 150, 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: "accessIpListAPI", Field: "AccessIpListAPI", Type: "string"}, + {Code: "accessIpListIngress", Field: "AccessIpListIngress", Type: "string"}, + {Code: "appVersion", Field: "AppVersion", Type: "string"}, + {Code: "clusterName", Field: "ClusterName", Type: "string"}, + {Code: "controlPlaneCount", Field: "ControlPlaneCount", Type: "int64"}, + {Code: "controlPlaneSizingDisk", Field: "ControlPlaneSizingDisk", Type: "int64"}, + {Code: "controlPlaneSizingPolicy", Field: "ControlPlaneSizingPolicy", Type: "string"}, + {Code: "needExternalAddressAPI", Field: "NeedExternalAddressAPI", Type: "bool"}, + {Code: "needExternalAddressIngress", Field: "NeedExternalAddressIngress", Type: "bool"}, + {Code: "nsxtUid", Field: "NsxtUid", Type: "string"}, + {Code: "vdcUid", Field: "VdcUid", Type: "string"}, + {Code: "workersCount", Field: "WorkersCount", Type: "int64"}, + {Code: "workersSizingDisk", Field: "WorkersSizingDisk", Type: "int64"}, + {Code: "workersSizingPolicy", Field: "WorkersSizingPolicy", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !state.NsxtUid.IsNull() && !state.NsxtUid.IsUnknown() { + resolvedNsxtUid, err := r.client.ResolveRefSvcParamValue(ctx, 22, state.NsxtUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve nsxt_uid", err.Error()) + } else if resolvedNsxtUid != "" && resolvedNsxtUid != state.NsxtUid.ValueString() { + state.NsxtUid = types.StringValue(resolvedNsxtUid) + } + } + if !state.VdcUid.IsNull() && !state.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, state.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_uid", err.Error()) + } else if resolvedVdcUid != "" && resolvedVdcUid != state.VdcUid.ValueString() { + state.VdcUid = types.StringValue(resolvedVdcUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *K8sSthutrvalClusterResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state K8sSthutrvalClusterModel + 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(), 150, 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: "accessIpListAPI", Field: "AccessIpListAPI", Type: "string"}, + {Code: "accessIpListIngress", Field: "AccessIpListIngress", Type: "string"}, + {Code: "appVersion", Field: "AppVersion", Type: "string"}, + {Code: "clusterName", Field: "ClusterName", Type: "string"}, + {Code: "controlPlaneCount", Field: "ControlPlaneCount", Type: "int64"}, + {Code: "controlPlaneSizingDisk", Field: "ControlPlaneSizingDisk", Type: "int64"}, + {Code: "controlPlaneSizingPolicy", Field: "ControlPlaneSizingPolicy", Type: "string"}, + {Code: "needExternalAddressAPI", Field: "NeedExternalAddressAPI", Type: "bool"}, + {Code: "needExternalAddressIngress", Field: "NeedExternalAddressIngress", Type: "bool"}, + {Code: "nsxtUid", Field: "NsxtUid", Type: "string"}, + {Code: "vdcUid", Field: "VdcUid", Type: "string"}, + {Code: "workersCount", Field: "WorkersCount", Type: "int64"}, + {Code: "workersSizingDisk", Field: "WorkersSizingDisk", Type: "int64"}, + {Code: "workersSizingPolicy", Field: "WorkersSizingPolicy", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !newState.NsxtUid.IsNull() && !newState.NsxtUid.IsUnknown() { + resolvedNsxtUid, err := r.client.ResolveRefSvcParamValue(ctx, 22, newState.NsxtUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve nsxt_uid", err.Error()) + } else if resolvedNsxtUid != "" && resolvedNsxtUid != newState.NsxtUid.ValueString() { + newState.NsxtUid = types.StringValue(resolvedNsxtUid) + } + } + if !newState.VdcUid.IsNull() && !newState.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, newState.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_uid", err.Error()) + } else if resolvedVdcUid != "" && resolvedVdcUid != newState.VdcUid.ValueString() { + newState.VdcUid = types.StringValue(resolvedVdcUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &newState)...) +} + +func (r *K8sSthutrvalClusterResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan K8sSthutrvalClusterModel + var state K8sSthutrvalClusterModel + 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.ControlPlaneCount.IsNull() != state.ControlPlaneCount.IsNull() || plan.ControlPlaneCount.IsUnknown() != state.ControlPlaneCount.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.ControlPlaneCount.IsNull() && !plan.ControlPlaneCount.IsUnknown() && !state.ControlPlaneCount.IsNull() && !state.ControlPlaneCount.IsUnknown() { + if plan.ControlPlaneCount.ValueInt64() != state.ControlPlaneCount.ValueInt64() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.WorkersCount.IsNull() != state.WorkersCount.IsNull() || plan.WorkersCount.IsUnknown() != state.WorkersCount.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.WorkersCount.IsNull() && !plan.WorkersCount.IsUnknown() && !state.WorkersCount.IsNull() && !state.WorkersCount.IsUnknown() { + if plan.WorkersCount.ValueInt64() != state.WorkersCount.ValueInt64() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.AccessIpListAPI.IsNull() != state.AccessIpListAPI.IsNull() || plan.AccessIpListAPI.IsUnknown() != state.AccessIpListAPI.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.AccessIpListAPI.IsNull() && !plan.AccessIpListAPI.IsUnknown() && !state.AccessIpListAPI.IsNull() && !state.AccessIpListAPI.IsUnknown() { + if plan.AccessIpListAPI.ValueString() != state.AccessIpListAPI.ValueString() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.AccessIpListIngress.IsNull() != state.AccessIpListIngress.IsNull() || plan.AccessIpListIngress.IsUnknown() != state.AccessIpListIngress.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.AccessIpListIngress.IsNull() && !plan.AccessIpListIngress.IsUnknown() && !state.AccessIpListIngress.IsNull() && !state.AccessIpListIngress.IsUnknown() { + if plan.AccessIpListIngress.ValueString() != state.AccessIpListIngress.ValueString() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.AppVersion.IsNull() != state.AppVersion.IsNull() || plan.AppVersion.IsUnknown() != state.AppVersion.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.AppVersion.IsNull() && !plan.AppVersion.IsUnknown() && !state.AppVersion.IsNull() && !state.AppVersion.IsUnknown() { + if plan.AppVersion.ValueString() != state.AppVersion.ValueString() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.ControlPlaneSizingDisk.IsNull() != state.ControlPlaneSizingDisk.IsNull() || plan.ControlPlaneSizingDisk.IsUnknown() != state.ControlPlaneSizingDisk.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.ControlPlaneSizingDisk.IsNull() && !plan.ControlPlaneSizingDisk.IsUnknown() && !state.ControlPlaneSizingDisk.IsNull() && !state.ControlPlaneSizingDisk.IsUnknown() { + if plan.ControlPlaneSizingDisk.ValueInt64() != state.ControlPlaneSizingDisk.ValueInt64() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.WorkersSizingDisk.IsNull() != state.WorkersSizingDisk.IsNull() || plan.WorkersSizingDisk.IsUnknown() != state.WorkersSizingDisk.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.WorkersSizingDisk.IsNull() && !plan.WorkersSizingDisk.IsUnknown() && !state.WorkersSizingDisk.IsNull() && !state.WorkersSizingDisk.IsUnknown() { + if plan.WorkersSizingDisk.ValueInt64() != state.WorkersSizingDisk.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 + } + + params := map[int]string{ + 362: resources_core.FormatInt64(plan.ControlPlaneCount), + 363: resources_core.FormatInt64(plan.WorkersCount), + 364: resources_core.FormatString(plan.AccessIpListAPI), + 365: resources_core.FormatString(plan.AccessIpListIngress), + 563: resources_core.FormatString(plan.AppVersion), + 637: resources_core.FormatInt64(plan.ControlPlaneSizingDisk), + 638: resources_core.FormatInt64(plan.WorkersSizingDisk), + } + + operationTimeout := "" + if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { + operationTimeout = plan.OperationTimeout.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(), 150, 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: "accessIpListAPI", Field: "AccessIpListAPI", Type: "string"}, + {Code: "accessIpListIngress", Field: "AccessIpListIngress", Type: "string"}, + {Code: "appVersion", Field: "AppVersion", Type: "string"}, + {Code: "clusterName", Field: "ClusterName", Type: "string"}, + {Code: "controlPlaneCount", Field: "ControlPlaneCount", Type: "int64"}, + {Code: "controlPlaneSizingDisk", Field: "ControlPlaneSizingDisk", Type: "int64"}, + {Code: "controlPlaneSizingPolicy", Field: "ControlPlaneSizingPolicy", Type: "string"}, + {Code: "needExternalAddressAPI", Field: "NeedExternalAddressAPI", Type: "bool"}, + {Code: "needExternalAddressIngress", Field: "NeedExternalAddressIngress", Type: "bool"}, + {Code: "nsxtUid", Field: "NsxtUid", Type: "string"}, + {Code: "vdcUid", Field: "VdcUid", Type: "string"}, + {Code: "workersCount", Field: "WorkersCount", Type: "int64"}, + {Code: "workersSizingDisk", Field: "WorkersSizingDisk", Type: "int64"}, + {Code: "workersSizingPolicy", Field: "WorkersSizingPolicy", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !state.NsxtUid.IsNull() && !state.NsxtUid.IsUnknown() { + resolvedNsxtUid, err := r.client.ResolveRefSvcParamValue(ctx, 22, state.NsxtUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve nsxt_uid", err.Error()) + } else if resolvedNsxtUid != "" && resolvedNsxtUid != state.NsxtUid.ValueString() { + state.NsxtUid = types.StringValue(resolvedNsxtUid) + } + } + if !state.VdcUid.IsNull() && !state.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, state.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_uid", err.Error()) + } else if resolvedVdcUid != "" && resolvedVdcUid != state.VdcUid.ValueString() { + state.VdcUid = types.StringValue(resolvedVdcUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *K8sSthutrvalClusterResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state K8sSthutrvalClusterModel + 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 err := resources_core.DeleteResourceWithTimeout(ctx, r.client, state.ID.ValueString(), deleteMode, operationTimeout); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } +} + +func (r *K8sSthutrvalClusterResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +func (r *K8sSthutrvalClusterResource) 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 +} diff --git a/universal_rebuild/internal/resources_gen/150_k8s_sthutrval_cluster_update_secrets_action.go b/universal_rebuild/internal/resources_gen/150_k8s_sthutrval_cluster_update_secrets_action.go new file mode 100644 index 0000000..387b4d8 --- /dev/null +++ b/universal_rebuild/internal/resources_gen/150_k8s_sthutrval_cluster_update_secrets_action.go @@ -0,0 +1,128 @@ +package resources_gen + +import ( + "context" + "strings" + + "terraform-provider-nubes/internal/core" + "terraform-provider-nubes/internal/resources_core" + + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Code generated by tools/gen_v2. DO NOT EDIT. +// Service: k8s_sthutrval_cluster +// Action: update_secrets + +var _ resource.Resource = &K8sSthutrvalClusterUpdateSecretsResource{} + +// K8sSthutrvalClusterUpdateSecretsResource triggers a one-time action. +type K8sSthutrvalClusterUpdateSecretsResource struct { + client *core.UniversalClient +} + +type K8sSthutrvalClusterUpdateSecretsModel struct { + ID types.String `tfsdk:"id"` + K8sSthutrvalClusterID types.String `tfsdk:"k8s_sthutrval_cluster_id"` + RunID types.String `tfsdk:"run_id"` + OperationTimeout types.String `tfsdk:"operation_timeout"` +} + +func NewK8sSthutrvalClusterUpdateSecretsResource() resource.Resource { + return &K8sSthutrvalClusterUpdateSecretsResource{} +} + +func (r *K8sSthutrvalClusterUpdateSecretsResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_k8s_sthutrval_cluster_update_secrets" +} + +func (r *K8sSthutrvalClusterUpdateSecretsResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + attrs := map[string]schema.Attribute{ + "id": schema.StringAttribute{Computed: true}, + "k8s_sthutrval_cluster_id": schema.StringAttribute{Required: true}, + "run_id": schema.StringAttribute{Required: true}, + "operation_timeout": schema.StringAttribute{Optional: true}, + } + resp.Schema = schema.Schema{Attributes: attrs} +} + +func (r *K8sSthutrvalClusterUpdateSecretsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan K8sSthutrvalClusterUpdateSecretsModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + instanceUID := strings.TrimSpace(plan.K8sSthutrvalClusterID.ValueString()) + runID := strings.TrimSpace(plan.RunID.ValueString()) + if instanceUID == "" || runID == "" { + resp.Diagnostics.AddError("Ошибка клиента", "отсутствует идентификатор экземпляра или run_id") + return + } + + params := map[string]string{} + + operationTimeout := "" + if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { + operationTimeout = plan.OperationTimeout.ValueString() + } + if err := resources_core.RunOperationByCodeWithTimeout(ctx, r.client, instanceUID, "update_secrets", params, operationTimeout); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + + plan.ID = types.StringValue(resources_core.BuildActionID(instanceUID, "update_secrets", runID)) + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *K8sSthutrvalClusterUpdateSecretsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state K8sSthutrvalClusterUpdateSecretsModel + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *K8sSthutrvalClusterUpdateSecretsResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan K8sSthutrvalClusterUpdateSecretsModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + instanceUID := strings.TrimSpace(plan.K8sSthutrvalClusterID.ValueString()) + runID := strings.TrimSpace(plan.RunID.ValueString()) + if instanceUID == "" || runID == "" { + resp.Diagnostics.AddError("Ошибка клиента", "отсутствует идентификатор экземпляра или run_id") + return + } + + params := map[string]string{} + + if err := resources_core.RunOperationByCode(ctx, r.client, instanceUID, "update_secrets", params); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + + plan.ID = types.StringValue(resources_core.BuildActionID(instanceUID, "update_secrets", runID)) + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *K8sSthutrvalClusterUpdateSecretsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + // No-op: removing the resource does not trigger a remote action. +} + +func (r *K8sSthutrvalClusterUpdateSecretsResource) 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 +} diff --git a/universal_rebuild/internal/resources_gen/19_vc_org_reconcile_action.go b/universal_rebuild/internal/resources_gen/19_vc_org_reconcile_action.go new file mode 100644 index 0000000..e8a2d39 --- /dev/null +++ b/universal_rebuild/internal/resources_gen/19_vc_org_reconcile_action.go @@ -0,0 +1,128 @@ +package resources_gen + +import ( + "context" + "strings" + + "terraform-provider-nubes/internal/core" + "terraform-provider-nubes/internal/resources_core" + + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Code generated by tools/gen_v2. DO NOT EDIT. +// Service: vc_org +// Action: reconcile + +var _ resource.Resource = &VcOrgReconcileResource{} + +// VcOrgReconcileResource triggers a one-time action. +type VcOrgReconcileResource struct { + client *core.UniversalClient +} + +type VcOrgReconcileModel struct { + ID types.String `tfsdk:"id"` + VcOrgID types.String `tfsdk:"vc_org_id"` + RunID types.String `tfsdk:"run_id"` + OperationTimeout types.String `tfsdk:"operation_timeout"` +} + +func NewVcOrgReconcileResource() resource.Resource { + return &VcOrgReconcileResource{} +} + +func (r *VcOrgReconcileResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_vc_org_reconcile" +} + +func (r *VcOrgReconcileResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + attrs := map[string]schema.Attribute{ + "id": schema.StringAttribute{Computed: true}, + "vc_org_id": schema.StringAttribute{Required: true}, + "run_id": schema.StringAttribute{Required: true}, + "operation_timeout": schema.StringAttribute{Optional: true}, + } + resp.Schema = schema.Schema{Attributes: attrs} +} + +func (r *VcOrgReconcileResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan VcOrgReconcileModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + instanceUID := strings.TrimSpace(plan.VcOrgID.ValueString()) + runID := strings.TrimSpace(plan.RunID.ValueString()) + if instanceUID == "" || runID == "" { + resp.Diagnostics.AddError("Ошибка клиента", "отсутствует идентификатор экземпляра или run_id") + return + } + + params := map[string]string{} + + operationTimeout := "" + if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { + operationTimeout = plan.OperationTimeout.ValueString() + } + if err := resources_core.RunOperationByCodeWithTimeout(ctx, r.client, instanceUID, "reconcile", params, operationTimeout); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + + plan.ID = types.StringValue(resources_core.BuildActionID(instanceUID, "reconcile", runID)) + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *VcOrgReconcileResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state VcOrgReconcileModel + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcOrgReconcileResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan VcOrgReconcileModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + instanceUID := strings.TrimSpace(plan.VcOrgID.ValueString()) + runID := strings.TrimSpace(plan.RunID.ValueString()) + if instanceUID == "" || runID == "" { + resp.Diagnostics.AddError("Ошибка клиента", "отсутствует идентификатор экземпляра или run_id") + return + } + + params := map[string]string{} + + if err := resources_core.RunOperationByCode(ctx, r.client, instanceUID, "reconcile", params); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + + plan.ID = types.StringValue(resources_core.BuildActionID(instanceUID, "reconcile", runID)) + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *VcOrgReconcileResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + // No-op: removing the resource does not trigger a remote action. +} + +func (r *VcOrgReconcileResource) 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 +} diff --git a/universal_rebuild/internal/resources_gen/19_vc_org_resource.go b/universal_rebuild/internal/resources_gen/19_vc_org_resource.go new file mode 100644 index 0000000..de654c8 --- /dev/null +++ b/universal_rebuild/internal/resources_gen/19_vc_org_resource.go @@ -0,0 +1,369 @@ +package resources_gen + +import ( + "context" + + "terraform-provider-nubes/internal/core" + "terraform-provider-nubes/internal/resources_core" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Code generated by tools/gen_v2. DO NOT EDIT. +// Service: vc_org +// Service ID: 19 + +var _ resource.Resource = &VcOrgResource{} +var _ resource.ResourceWithModifyPlan = &VcOrgResource{} +var _ resource.ResourceWithImportState = &VcOrgResource{} + +type VcOrgResource struct { + client *core.UniversalClient +} + +type VcOrgModel struct { + ID types.String `tfsdk:"id"` + ResourceName types.String `tfsdk:"resource_name"` + OperationTimeout types.String `tfsdk:"operation_timeout"` + OrganizationType types.String `tfsdk:"organization_type"` + ResourceRealm types.String `tfsdk:"resource_realm"` + VIPConfigure types.String `tfsdk:"v_i_p_configure"` + 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 NewVcOrgResource() resource.Resource { + return &VcOrgResource{} +} + +func (r *VcOrgResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_vc_org" +} + +func (r *VcOrgResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + attrs := map[string]schema.Attribute{ + "id": schema.StringAttribute{Computed: true}, + "resource_name": schema.StringAttribute{Required: true}, + "operation_timeout": schema.StringAttribute{Optional: true}, + "organization_type": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("iaas"), MarkdownDescription: "Доступ к организации предоставляется только при выборе `iaas` Не изменяется после создания."}, + "resource_realm": schema.StringAttribute{Required: true, MarkdownDescription: "Облако в котором будет развёрнут тенант Не изменяется после создания."}, + "v_i_p_configure": schema.StringAttribute{Required: true}, + "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 *VcOrgResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { + if r.client == nil { + return + } + + var config *VcOrgModel + resp.Diagnostics.Append(req.Config.Get(ctx, &config)...) + if resp.Diagnostics.HasError() { + return + } + if config == nil { + return + } + + var state *VcOrgModel + 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 VcOrgModel + 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.OrganizationType.IsNull() && !plan.OrganizationType.IsUnknown() && !state.OrganizationType.IsNull() && !state.OrganizationType.IsUnknown() { + if plan.OrganizationType.ValueString() != state.OrganizationType.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить organization_type", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.ResourceRealm.IsNull() && !plan.ResourceRealm.IsUnknown() && !state.ResourceRealm.IsNull() && !state.ResourceRealm.IsUnknown() { + if plan.ResourceRealm.ValueString() != state.ResourceRealm.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить resource_realm", "Параметр задается при создании и не может быть изменен.") + return + } + } + return + } + if config.ResourceRealm.IsNull() || config.ResourceRealm.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "resource_realm is required.") + return + } + if config.VIPConfigure.IsNull() || config.VIPConfigure.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "v_i_p_configure is required.") + 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{ + 418: resources_core.FormatString(config.ResourceRealm), + 556: resources_core.FormatString(config.OrganizationType), + } + + resp.Diagnostics.Append(resources_core.PlanExistingResourceDiagnosticsWithParams(ctx, r.client, 19, config.ResourceName.ValueString(), adoptExistingOnCreate, params)...) +} + +func (r *VcOrgResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data VcOrgModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + if data.ResourceRealm.IsNull() || data.ResourceRealm.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "resource_realm is required.") + return + } + if data.VIPConfigure.IsNull() || data.VIPConfigure.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "v_i_p_configure is required.") + return + } + + resourceName := data.ResourceName.ValueString() + resp.Diagnostics.Append(resources_core.CreateExistingResourceDiagnostics(ctx, r.client, 19, resourceName, data.AdoptExistingOnCreate.ValueBool())...) + + params := map[int]string{ + 418: resources_core.FormatString(data.ResourceRealm), + 556: resources_core.FormatString(data.OrganizationType), + } + + operationTimeout := "" + if !data.OperationTimeout.IsNull() && !data.OperationTimeout.IsUnknown() { + operationTimeout = data.OperationTimeout.ValueString() + } + id, err := resources_core.CreateResourceWithTimeout(ctx, r.client, 19, 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, 19, 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: "organizationType", Field: "OrganizationType", Type: "string"}, + {Code: "resourceRealm", Field: "ResourceRealm", Type: "string"}, + {Code: "vIPConfigure", Field: "VIPConfigure", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcOrgResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state VcOrgModel + 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(), 19, 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: "organizationType", Field: "OrganizationType", Type: "string"}, + {Code: "resourceRealm", Field: "ResourceRealm", Type: "string"}, + {Code: "vIPConfigure", Field: "VIPConfigure", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &newState)...) +} + +func (r *VcOrgResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan VcOrgModel + var state VcOrgModel + 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.VIPConfigure.IsNull() != state.VIPConfigure.IsNull() || plan.VIPConfigure.IsUnknown() != state.VIPConfigure.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.VIPConfigure.IsNull() && !plan.VIPConfigure.IsUnknown() && !state.VIPConfigure.IsNull() && !state.VIPConfigure.IsUnknown() { + if plan.VIPConfigure.ValueString() != state.VIPConfigure.ValueString() { + hasServiceParamChanges = true + } + } + } + + if !hasServiceParamChanges { + plan.ID = instanceID + plan.StateParams = state.StateParams + plan.StateOut = state.StateOut + plan.StateParamsFlat = state.StateParamsFlat + plan.StateOutFlat = state.StateOutFlat + plan.VaultSecrets = state.VaultSecrets + plan.VaultUrl = state.VaultUrl + plan.VaultUserPath = state.VaultUserPath + plan.VaultFields = state.VaultFields + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) + return + } + + params := map[int]string{ + 662: resources_core.FormatString(plan.VIPConfigure), + } + + operationTimeout := "" + if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { + operationTimeout = plan.OperationTimeout.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(), 19, 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: "organizationType", Field: "OrganizationType", Type: "string"}, + {Code: "resourceRealm", Field: "ResourceRealm", Type: "string"}, + {Code: "vIPConfigure", Field: "VIPConfigure", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcOrgResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state VcOrgModel + 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 err := resources_core.DeleteResourceWithTimeout(ctx, r.client, state.ID.ValueString(), deleteMode, operationTimeout); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } +} + +func (r *VcOrgResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +func (r *VcOrgResource) 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 +} diff --git a/universal_rebuild/internal/resources_gen/20_vc_org_saas_resource.go b/universal_rebuild/internal/resources_gen/20_vc_org_saas_resource.go new file mode 100644 index 0000000..87fa0eb --- /dev/null +++ b/universal_rebuild/internal/resources_gen/20_vc_org_saas_resource.go @@ -0,0 +1,331 @@ +package resources_gen + +import ( + "context" + + "terraform-provider-nubes/internal/core" + "terraform-provider-nubes/internal/resources_core" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Code generated by tools/gen_v2. DO NOT EDIT. +// Service: vc_org_saas +// Service ID: 20 + +var _ resource.Resource = &VcOrgSaasResource{} +var _ resource.ResourceWithModifyPlan = &VcOrgSaasResource{} +var _ resource.ResourceWithImportState = &VcOrgSaasResource{} + +type VcOrgSaasResource struct { + client *core.UniversalClient +} + +type VcOrgSaasModel struct { + ID types.String `tfsdk:"id"` + ResourceName types.String `tfsdk:"resource_name"` + OperationTimeout types.String `tfsdk:"operation_timeout"` + ResourceRealm types.String `tfsdk:"resource_realm"` + 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 NewVcOrgSaasResource() resource.Resource { + return &VcOrgSaasResource{} +} + +func (r *VcOrgSaasResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_vc_org_saas" +} + +func (r *VcOrgSaasResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + attrs := map[string]schema.Attribute{ + "id": schema.StringAttribute{Computed: true}, + "resource_name": schema.StringAttribute{Required: true}, + "operation_timeout": schema.StringAttribute{Optional: true}, + "resource_realm": schema.StringAttribute{Required: 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 *VcOrgSaasResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { + if r.client == nil { + return + } + + var config *VcOrgSaasModel + resp.Diagnostics.Append(req.Config.Get(ctx, &config)...) + if resp.Diagnostics.HasError() { + return + } + if config == nil { + return + } + + var state *VcOrgSaasModel + 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 VcOrgSaasModel + 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.ResourceRealm.IsNull() && !plan.ResourceRealm.IsUnknown() && !state.ResourceRealm.IsNull() && !state.ResourceRealm.IsUnknown() { + if plan.ResourceRealm.ValueString() != state.ResourceRealm.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить resource_realm", "Параметр задается при создании и не может быть изменен.") + return + } + } + return + } + if config.ResourceRealm.IsNull() || config.ResourceRealm.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "resource_realm is required.") + 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{ + 185: resources_core.FormatString(config.ResourceRealm), + } + + resp.Diagnostics.Append(resources_core.PlanExistingResourceDiagnosticsWithParams(ctx, r.client, 20, config.ResourceName.ValueString(), adoptExistingOnCreate, params)...) +} + +func (r *VcOrgSaasResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data VcOrgSaasModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + if data.ResourceRealm.IsNull() || data.ResourceRealm.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "resource_realm is required.") + return + } + + resourceName := data.ResourceName.ValueString() + resp.Diagnostics.Append(resources_core.CreateExistingResourceDiagnostics(ctx, r.client, 20, resourceName, data.AdoptExistingOnCreate.ValueBool())...) + + params := map[int]string{ + 185: resources_core.FormatString(data.ResourceRealm), + } + + operationTimeout := "" + if !data.OperationTimeout.IsNull() && !data.OperationTimeout.IsUnknown() { + operationTimeout = data.OperationTimeout.ValueString() + } + id, err := resources_core.CreateResourceWithTimeout(ctx, r.client, 20, 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, 20, 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: "resourceRealm", Field: "ResourceRealm", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcOrgSaasResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state VcOrgSaasModel + 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(), 20, 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: "resourceRealm", Field: "ResourceRealm", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &newState)...) +} + +func (r *VcOrgSaasResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan VcOrgSaasModel + var state VcOrgSaasModel + 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 + } + + params := map[int]string{} + + operationTimeout := "" + if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { + operationTimeout = plan.OperationTimeout.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(), 20, 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: "resourceRealm", Field: "ResourceRealm", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcOrgSaasResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state VcOrgSaasModel + 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 err := resources_core.DeleteResourceWithTimeout(ctx, r.client, state.ID.ValueString(), deleteMode, operationTimeout); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } +} + +func (r *VcOrgSaasResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +func (r *VcOrgSaasResource) 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 +} diff --git a/universal_rebuild/internal/resources_gen/21_vc_vdc_reconcile_action.go b/universal_rebuild/internal/resources_gen/21_vc_vdc_reconcile_action.go new file mode 100644 index 0000000..0725e11 --- /dev/null +++ b/universal_rebuild/internal/resources_gen/21_vc_vdc_reconcile_action.go @@ -0,0 +1,128 @@ +package resources_gen + +import ( + "context" + "strings" + + "terraform-provider-nubes/internal/core" + "terraform-provider-nubes/internal/resources_core" + + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Code generated by tools/gen_v2. DO NOT EDIT. +// Service: vc_vdc +// Action: reconcile + +var _ resource.Resource = &VcVdcReconcileResource{} + +// VcVdcReconcileResource triggers a one-time action. +type VcVdcReconcileResource struct { + client *core.UniversalClient +} + +type VcVdcReconcileModel struct { + ID types.String `tfsdk:"id"` + VcVdcID types.String `tfsdk:"vc_vdc_id"` + RunID types.String `tfsdk:"run_id"` + OperationTimeout types.String `tfsdk:"operation_timeout"` +} + +func NewVcVdcReconcileResource() resource.Resource { + return &VcVdcReconcileResource{} +} + +func (r *VcVdcReconcileResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_vc_vdc_reconcile" +} + +func (r *VcVdcReconcileResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + attrs := map[string]schema.Attribute{ + "id": schema.StringAttribute{Computed: true}, + "vc_vdc_id": schema.StringAttribute{Required: true}, + "run_id": schema.StringAttribute{Required: true}, + "operation_timeout": schema.StringAttribute{Optional: true}, + } + resp.Schema = schema.Schema{Attributes: attrs} +} + +func (r *VcVdcReconcileResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan VcVdcReconcileModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + instanceUID := strings.TrimSpace(plan.VcVdcID.ValueString()) + runID := strings.TrimSpace(plan.RunID.ValueString()) + if instanceUID == "" || runID == "" { + resp.Diagnostics.AddError("Ошибка клиента", "отсутствует идентификатор экземпляра или run_id") + return + } + + params := map[string]string{} + + operationTimeout := "" + if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { + operationTimeout = plan.OperationTimeout.ValueString() + } + if err := resources_core.RunOperationByCodeWithTimeout(ctx, r.client, instanceUID, "reconcile", params, operationTimeout); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + + plan.ID = types.StringValue(resources_core.BuildActionID(instanceUID, "reconcile", runID)) + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *VcVdcReconcileResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state VcVdcReconcileModel + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcVdcReconcileResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan VcVdcReconcileModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + instanceUID := strings.TrimSpace(plan.VcVdcID.ValueString()) + runID := strings.TrimSpace(plan.RunID.ValueString()) + if instanceUID == "" || runID == "" { + resp.Diagnostics.AddError("Ошибка клиента", "отсутствует идентификатор экземпляра или run_id") + return + } + + params := map[string]string{} + + if err := resources_core.RunOperationByCode(ctx, r.client, instanceUID, "reconcile", params); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + + plan.ID = types.StringValue(resources_core.BuildActionID(instanceUID, "reconcile", runID)) + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *VcVdcReconcileResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + // No-op: removing the resource does not trigger a remote action. +} + +func (r *VcVdcReconcileResource) 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 +} diff --git a/universal_rebuild/internal/resources_gen/21_vc_vdc_resource.go b/universal_rebuild/internal/resources_gen/21_vc_vdc_resource.go new file mode 100644 index 0000000..b122325 --- /dev/null +++ b/universal_rebuild/internal/resources_gen/21_vc_vdc_resource.go @@ -0,0 +1,518 @@ +package resources_gen + +import ( + "context" + + "terraform-provider-nubes/internal/core" + "terraform-provider-nubes/internal/resources_core" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Code generated by tools/gen_v2. DO NOT EDIT. +// Service: vc_vdc +// Service ID: 21 + +var _ resource.Resource = &VcVdcResource{} +var _ resource.ResourceWithModifyPlan = &VcVdcResource{} +var _ resource.ResourceWithImportState = &VcVdcResource{} + +type VcVdcResource struct { + client *core.UniversalClient +} + +type VcVdcModel struct { + ID types.String `tfsdk:"id"` + ResourceName types.String `tfsdk:"resource_name"` + OperationTimeout types.String `tfsdk:"operation_timeout"` + CpuAllocated types.Int64 `tfsdk:"cpu_allocated"` + CpuGuaranteed types.Int64 `tfsdk:"cpu_guaranteed"` + MemAllocated types.Int64 `tfsdk:"mem_allocated"` + MemGuaranteed types.Int64 `tfsdk:"mem_guaranteed"` + NetworkProvider types.String `tfsdk:"network_provider"` + OrganizationUid types.String `tfsdk:"organization_uid"` + ProviderVdc types.String `tfsdk:"provider_vdc"` + StorageConfig types.String `tfsdk:"storage_config"` + 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 NewVcVdcResource() resource.Resource { + return &VcVdcResource{} +} + +func (r *VcVdcResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_vc_vdc" +} + +func (r *VcVdcResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + attrs := map[string]schema.Attribute{ + "id": schema.StringAttribute{Computed: true}, + "resource_name": schema.StringAttribute{Required: true}, + "operation_timeout": schema.StringAttribute{Optional: true}, + "cpu_allocated": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(10), MarkdownDescription: "шт"}, + "cpu_guaranteed": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(20), MarkdownDescription: "% резервирования Не изменяется после создания."}, + "mem_allocated": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(20), MarkdownDescription: "gb"}, + "mem_guaranteed": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(20), MarkdownDescription: "% резервирования Не изменяется после создания."}, + "network_provider": schema.StringAttribute{Required: true, MarkdownDescription: "Не изменяется после создания."}, + "organization_uid": schema.StringAttribute{Required: true, MarkdownDescription: "Для создания VDC предварительно необходимо создать организацию через услугу `Организация в Cloud Director` Не изменяется после создания."}, + "provider_vdc": schema.StringAttribute{Required: true, MarkdownDescription: "Приписка `2.8` - Скорость vCPU - 2800MHz
И так далее...
Не изменяется после создания."}, + "storage_config": schema.StringAttribute{Required: 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 *VcVdcResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { + if r.client == nil { + return + } + + var config *VcVdcModel + resp.Diagnostics.Append(req.Config.Get(ctx, &config)...) + if resp.Diagnostics.HasError() { + return + } + if config == nil { + return + } + + var state *VcVdcModel + 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 VcVdcModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + planChanged := false + if !plan.OrganizationUid.IsNull() && !plan.OrganizationUid.IsUnknown() { + resolvedOrganizationUid, err := r.client.ResolveRefSvcParamValue(ctx, 19, plan.OrganizationUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve organization_uid", err.Error()) + } else if resolvedOrganizationUid != "" && resolvedOrganizationUid != plan.OrganizationUid.ValueString() { + plan.OrganizationUid = types.StringValue(resolvedOrganizationUid) + planChanged = true + } + } + if planChanged { + resp.Diagnostics.Append(resp.Plan.Set(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + } + if !plan.ResourceName.IsNull() && !plan.ResourceName.IsUnknown() && !state.ResourceName.IsNull() && !state.ResourceName.IsUnknown() { + if plan.ResourceName.ValueString() != state.ResourceName.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить resource_name", "Параметр resource_name задается при создании и не может быть изменен. Создайте новый ресурс с другим именем.") + return + } + } + if !plan.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.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.NetworkProvider.IsNull() && !plan.NetworkProvider.IsUnknown() && !state.NetworkProvider.IsNull() && !state.NetworkProvider.IsUnknown() { + if plan.NetworkProvider.ValueString() != state.NetworkProvider.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить network_provider", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.OrganizationUid.IsNull() && !plan.OrganizationUid.IsUnknown() && !state.OrganizationUid.IsNull() && !state.OrganizationUid.IsUnknown() { + if plan.OrganizationUid.ValueString() != state.OrganizationUid.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить organization_uid", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.ProviderVdc.IsNull() && !plan.ProviderVdc.IsUnknown() && !state.ProviderVdc.IsNull() && !state.ProviderVdc.IsUnknown() { + if plan.ProviderVdc.ValueString() != state.ProviderVdc.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить provider_vdc", "Параметр задается при создании и не может быть изменен.") + return + } + } + return + } + if config.NetworkProvider.IsNull() || config.NetworkProvider.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "network_provider is required.") + return + } + if config.OrganizationUid.IsNull() || config.OrganizationUid.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "organization_uid is required.") + return + } + if config.ProviderVdc.IsNull() || config.ProviderVdc.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "provider_vdc is required.") + return + } + if config.StorageConfig.IsNull() || config.StorageConfig.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "storage_config is required.") + return + } + + if config.ResourceName.IsNull() || config.ResourceName.IsUnknown() { + return + } + adoptExistingOnCreate := false + if !config.AdoptExistingOnCreate.IsNull() && !config.AdoptExistingOnCreate.IsUnknown() { + adoptExistingOnCreate = config.AdoptExistingOnCreate.ValueBool() + } + if !config.OrganizationUid.IsNull() && !config.OrganizationUid.IsUnknown() { + resolvedOrganizationUid, err := r.client.ResolveRefSvcParamValue(ctx, 19, config.OrganizationUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve organization_uid", err.Error()) + } else if resolvedOrganizationUid != "" && resolvedOrganizationUid != config.OrganizationUid.ValueString() { + config.OrganizationUid = types.StringValue(resolvedOrganizationUid) + } + } + params := map[int]string{ + 30: resources_core.FormatString(config.OrganizationUid), + 335: resources_core.FormatString(config.ProviderVdc), + 361: resources_core.FormatString(config.StorageConfig), + 397: resources_core.FormatInt64(config.CpuGuaranteed), + 398: resources_core.FormatInt64(config.MemGuaranteed), + 557: resources_core.FormatInt64(config.CpuAllocated), + 558: resources_core.FormatInt64(config.MemAllocated), + 746: resources_core.FormatString(config.NetworkProvider), + } + + resp.Diagnostics.Append(resources_core.PlanExistingResourceDiagnosticsWithParams(ctx, r.client, 21, config.ResourceName.ValueString(), adoptExistingOnCreate, params)...) +} + +func (r *VcVdcResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data VcVdcModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + if data.NetworkProvider.IsNull() || data.NetworkProvider.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "network_provider is required.") + return + } + if data.OrganizationUid.IsNull() || data.OrganizationUid.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "organization_uid is required.") + return + } + if data.ProviderVdc.IsNull() || data.ProviderVdc.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "provider_vdc is required.") + return + } + if data.StorageConfig.IsNull() || data.StorageConfig.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "storage_config is required.") + return + } + if !data.OrganizationUid.IsNull() && !data.OrganizationUid.IsUnknown() { + resolvedOrganizationUid, err := r.client.ResolveRefSvcParamValue(ctx, 19, data.OrganizationUid.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + if resolvedOrganizationUid != "" && resolvedOrganizationUid != data.OrganizationUid.ValueString() { + data.OrganizationUid = types.StringValue(resolvedOrganizationUid) + } + } + + resourceName := data.ResourceName.ValueString() + resp.Diagnostics.Append(resources_core.CreateExistingResourceDiagnostics(ctx, r.client, 21, resourceName, data.AdoptExistingOnCreate.ValueBool())...) + + params := map[int]string{ + 30: resources_core.FormatString(data.OrganizationUid), + 335: resources_core.FormatString(data.ProviderVdc), + 361: resources_core.FormatString(data.StorageConfig), + 397: resources_core.FormatInt64(data.CpuGuaranteed), + 398: resources_core.FormatInt64(data.MemGuaranteed), + 557: resources_core.FormatInt64(data.CpuAllocated), + 558: resources_core.FormatInt64(data.MemAllocated), + 746: resources_core.FormatString(data.NetworkProvider), + } + + operationTimeout := "" + if !data.OperationTimeout.IsNull() && !data.OperationTimeout.IsUnknown() { + operationTimeout = data.OperationTimeout.ValueString() + } + id, err := resources_core.CreateResourceWithTimeout(ctx, r.client, 21, 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, 21, 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: "int64"}, + {Code: "cpuGuaranteed", Field: "CpuGuaranteed", Type: "int64"}, + {Code: "memAllocated", Field: "MemAllocated", Type: "int64"}, + {Code: "memGuaranteed", Field: "MemGuaranteed", Type: "int64"}, + {Code: "networkProvider", Field: "NetworkProvider", Type: "string"}, + {Code: "organizationUid", Field: "OrganizationUid", Type: "string"}, + {Code: "providerVdc", Field: "ProviderVdc", Type: "string"}, + {Code: "storageConfig", Field: "StorageConfig", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !state.OrganizationUid.IsNull() && !state.OrganizationUid.IsUnknown() { + resolvedOrganizationUid, err := r.client.ResolveRefSvcParamValue(ctx, 19, state.OrganizationUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve organization_uid", err.Error()) + } else if resolvedOrganizationUid != "" && resolvedOrganizationUid != state.OrganizationUid.ValueString() { + state.OrganizationUid = types.StringValue(resolvedOrganizationUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcVdcResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state VcVdcModel + 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(), 21, 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: "int64"}, + {Code: "cpuGuaranteed", Field: "CpuGuaranteed", Type: "int64"}, + {Code: "memAllocated", Field: "MemAllocated", Type: "int64"}, + {Code: "memGuaranteed", Field: "MemGuaranteed", Type: "int64"}, + {Code: "networkProvider", Field: "NetworkProvider", Type: "string"}, + {Code: "organizationUid", Field: "OrganizationUid", Type: "string"}, + {Code: "providerVdc", Field: "ProviderVdc", Type: "string"}, + {Code: "storageConfig", Field: "StorageConfig", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !newState.OrganizationUid.IsNull() && !newState.OrganizationUid.IsUnknown() { + resolvedOrganizationUid, err := r.client.ResolveRefSvcParamValue(ctx, 19, newState.OrganizationUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve organization_uid", err.Error()) + } else if resolvedOrganizationUid != "" && resolvedOrganizationUid != newState.OrganizationUid.ValueString() { + newState.OrganizationUid = types.StringValue(resolvedOrganizationUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &newState)...) +} + +func (r *VcVdcResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan VcVdcModel + var state VcVdcModel + 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.CpuAllocated.IsNull() != state.CpuAllocated.IsNull() || plan.CpuAllocated.IsUnknown() != state.CpuAllocated.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.CpuAllocated.IsNull() && !plan.CpuAllocated.IsUnknown() && !state.CpuAllocated.IsNull() && !state.CpuAllocated.IsUnknown() { + if plan.CpuAllocated.ValueInt64() != state.CpuAllocated.ValueInt64() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.MemAllocated.IsNull() != state.MemAllocated.IsNull() || plan.MemAllocated.IsUnknown() != state.MemAllocated.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.MemAllocated.IsNull() && !plan.MemAllocated.IsUnknown() && !state.MemAllocated.IsNull() && !state.MemAllocated.IsUnknown() { + if plan.MemAllocated.ValueInt64() != state.MemAllocated.ValueInt64() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.StorageConfig.IsNull() != state.StorageConfig.IsNull() || plan.StorageConfig.IsUnknown() != state.StorageConfig.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.StorageConfig.IsNull() && !plan.StorageConfig.IsUnknown() && !state.StorageConfig.IsNull() && !state.StorageConfig.IsUnknown() { + if plan.StorageConfig.ValueString() != state.StorageConfig.ValueString() { + hasServiceParamChanges = true + } + } + } + + if !hasServiceParamChanges { + plan.ID = instanceID + plan.StateParams = state.StateParams + plan.StateOut = state.StateOut + plan.StateParamsFlat = state.StateParamsFlat + plan.StateOutFlat = state.StateOutFlat + plan.VaultSecrets = state.VaultSecrets + plan.VaultUrl = state.VaultUrl + plan.VaultUserPath = state.VaultUserPath + plan.VaultFields = state.VaultFields + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) + return + } + + params := map[int]string{ + 560: resources_core.FormatInt64(plan.CpuAllocated), + 561: resources_core.FormatInt64(plan.MemAllocated), + 562: resources_core.FormatString(plan.StorageConfig), + } + + operationTimeout := "" + if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { + operationTimeout = plan.OperationTimeout.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(), 21, 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: "int64"}, + {Code: "cpuGuaranteed", Field: "CpuGuaranteed", Type: "int64"}, + {Code: "memAllocated", Field: "MemAllocated", Type: "int64"}, + {Code: "memGuaranteed", Field: "MemGuaranteed", Type: "int64"}, + {Code: "networkProvider", Field: "NetworkProvider", Type: "string"}, + {Code: "organizationUid", Field: "OrganizationUid", Type: "string"}, + {Code: "providerVdc", Field: "ProviderVdc", Type: "string"}, + {Code: "storageConfig", Field: "StorageConfig", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !state.OrganizationUid.IsNull() && !state.OrganizationUid.IsUnknown() { + resolvedOrganizationUid, err := r.client.ResolveRefSvcParamValue(ctx, 19, state.OrganizationUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve organization_uid", err.Error()) + } else if resolvedOrganizationUid != "" && resolvedOrganizationUid != state.OrganizationUid.ValueString() { + state.OrganizationUid = types.StringValue(resolvedOrganizationUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcVdcResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state VcVdcModel + 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 err := resources_core.DeleteResourceWithTimeout(ctx, r.client, state.ID.ValueString(), deleteMode, operationTimeout); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } +} + +func (r *VcVdcResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +func (r *VcVdcResource) 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 +} diff --git a/universal_rebuild/internal/resources_gen/22_vc_nsxt_reconcile_action.go b/universal_rebuild/internal/resources_gen/22_vc_nsxt_reconcile_action.go new file mode 100644 index 0000000..32068dd --- /dev/null +++ b/universal_rebuild/internal/resources_gen/22_vc_nsxt_reconcile_action.go @@ -0,0 +1,128 @@ +package resources_gen + +import ( + "context" + "strings" + + "terraform-provider-nubes/internal/core" + "terraform-provider-nubes/internal/resources_core" + + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Code generated by tools/gen_v2. DO NOT EDIT. +// Service: vc_nsxt +// Action: reconcile + +var _ resource.Resource = &VcNsxtReconcileResource{} + +// VcNsxtReconcileResource triggers a one-time action. +type VcNsxtReconcileResource struct { + client *core.UniversalClient +} + +type VcNsxtReconcileModel struct { + ID types.String `tfsdk:"id"` + VcNsxtID types.String `tfsdk:"vc_nsxt_id"` + RunID types.String `tfsdk:"run_id"` + OperationTimeout types.String `tfsdk:"operation_timeout"` +} + +func NewVcNsxtReconcileResource() resource.Resource { + return &VcNsxtReconcileResource{} +} + +func (r *VcNsxtReconcileResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_vc_nsxt_reconcile" +} + +func (r *VcNsxtReconcileResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + attrs := map[string]schema.Attribute{ + "id": schema.StringAttribute{Computed: true}, + "vc_nsxt_id": schema.StringAttribute{Required: true}, + "run_id": schema.StringAttribute{Required: true}, + "operation_timeout": schema.StringAttribute{Optional: true}, + } + resp.Schema = schema.Schema{Attributes: attrs} +} + +func (r *VcNsxtReconcileResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan VcNsxtReconcileModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + instanceUID := strings.TrimSpace(plan.VcNsxtID.ValueString()) + runID := strings.TrimSpace(plan.RunID.ValueString()) + if instanceUID == "" || runID == "" { + resp.Diagnostics.AddError("Ошибка клиента", "отсутствует идентификатор экземпляра или run_id") + return + } + + params := map[string]string{} + + operationTimeout := "" + if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { + operationTimeout = plan.OperationTimeout.ValueString() + } + if err := resources_core.RunOperationByCodeWithTimeout(ctx, r.client, instanceUID, "reconcile", params, operationTimeout); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + + plan.ID = types.StringValue(resources_core.BuildActionID(instanceUID, "reconcile", runID)) + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *VcNsxtReconcileResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state VcNsxtReconcileModel + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcNsxtReconcileResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan VcNsxtReconcileModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + instanceUID := strings.TrimSpace(plan.VcNsxtID.ValueString()) + runID := strings.TrimSpace(plan.RunID.ValueString()) + if instanceUID == "" || runID == "" { + resp.Diagnostics.AddError("Ошибка клиента", "отсутствует идентификатор экземпляра или run_id") + return + } + + params := map[string]string{} + + if err := resources_core.RunOperationByCode(ctx, r.client, instanceUID, "reconcile", params); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + + plan.ID = types.StringValue(resources_core.BuildActionID(instanceUID, "reconcile", runID)) + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *VcNsxtReconcileResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + // No-op: removing the resource does not trigger a remote action. +} + +func (r *VcNsxtReconcileResource) 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 +} diff --git a/universal_rebuild/internal/resources_gen/22_vc_nsxt_resource.go b/universal_rebuild/internal/resources_gen/22_vc_nsxt_resource.go new file mode 100644 index 0000000..c2c3dcb --- /dev/null +++ b/universal_rebuild/internal/resources_gen/22_vc_nsxt_resource.go @@ -0,0 +1,525 @@ +package resources_gen + +import ( + "context" + + "terraform-provider-nubes/internal/core" + "terraform-provider-nubes/internal/resources_core" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Code generated by tools/gen_v2. DO NOT EDIT. +// Service: vc_nsxt +// Service ID: 22 + +var _ resource.Resource = &VcNsxtResource{} +var _ resource.ResourceWithModifyPlan = &VcNsxtResource{} +var _ resource.ResourceWithImportState = &VcNsxtResource{} + +type VcNsxtResource struct { + client *core.UniversalClient +} + +type VcNsxtModel struct { + ID types.String `tfsdk:"id"` + ResourceName types.String `tfsdk:"resource_name"` + OperationTimeout types.String `tfsdk:"operation_timeout"` + IpSpaceName types.String `tfsdk:"ip_space_name"` + NeedEnableAVI types.Bool `tfsdk:"need_enable_a_v_i"` + NeedExternalAddressSNAT types.Bool `tfsdk:"need_external_address_s_n_a_t"` + VdcGroupUid types.String `tfsdk:"vdc_group_uid"` + VdcType types.String `tfsdk:"vdc_type"` + VdcUid types.String `tfsdk:"vdc_uid"` + VirtualServicesCount types.Int64 `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 NewVcNsxtResource() resource.Resource { + return &VcNsxtResource{} +} + +func (r *VcNsxtResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_vc_nsxt" +} + +func (r *VcNsxtResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + attrs := map[string]schema.Attribute{ + "id": schema.StringAttribute{Computed: true}, + "resource_name": schema.StringAttribute{Required: true}, + "operation_timeout": schema.StringAttribute{Optional: true}, + "ip_space_name": schema.StringAttribute{Optional: true, MarkdownDescription: "Имя ip Space для внешнего IP

getKeyListFromStruct(getInstanceState(getValueFromStruct(getInstanceState(getValueFromStruct(getInstanceState(), "params.vdcUid")), "params.organizationUid")), "params.vIPConfigure")"}, + "need_enable_a_v_i": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Включение Load Balancer"}, + "need_external_address_s_n_a_t": schema.BoolAttribute{Optional: true, MarkdownDescription: "Создать правило SNAT на подсеть `10.10.102.0/24`"}, + "vdc_group_uid": schema.StringAttribute{Optional: true, MarkdownDescription: "UUID Услуги `Группа виртуальных датацентров (groupvDC)` Не изменяется после создания."}, + "vdc_type": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("vdc"), MarkdownDescription: "Тип родительской услуги Не изменяется после создания."}, + "vdc_uid": schema.StringAttribute{Optional: true, MarkdownDescription: "UUID Услуги `Виртуальный датацентр (vDC)` Не изменяется после создания."}, + "virtual_services_count": schema.Int64Attribute{Optional: true, Computed: true, Default: int64default.StaticInt64(1), MarkdownDescription: "Кол-во виртуальных сервисов, которые выделяются на AVI"}, + "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 *VcNsxtResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { + if r.client == nil { + return + } + + var config *VcNsxtModel + resp.Diagnostics.Append(req.Config.Get(ctx, &config)...) + if resp.Diagnostics.HasError() { + return + } + if config == nil { + return + } + + var state *VcNsxtModel + 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 VcNsxtModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + planChanged := false + if !plan.VdcGroupUid.IsNull() && !plan.VdcGroupUid.IsUnknown() { + resolvedVdcGroupUid, err := r.client.ResolveRefSvcParamValue(ctx, 29, plan.VdcGroupUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_group_uid", err.Error()) + } else if resolvedVdcGroupUid != "" && resolvedVdcGroupUid != plan.VdcGroupUid.ValueString() { + plan.VdcGroupUid = types.StringValue(resolvedVdcGroupUid) + planChanged = true + } + } + if !plan.VdcUid.IsNull() && !plan.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, plan.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_uid", err.Error()) + } else if resolvedVdcUid != "" && resolvedVdcUid != plan.VdcUid.ValueString() { + plan.VdcUid = types.StringValue(resolvedVdcUid) + planChanged = true + } + } + if planChanged { + resp.Diagnostics.Append(resp.Plan.Set(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + } + if !plan.ResourceName.IsNull() && !plan.ResourceName.IsUnknown() && !state.ResourceName.IsNull() && !state.ResourceName.IsUnknown() { + if plan.ResourceName.ValueString() != state.ResourceName.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить resource_name", "Параметр resource_name задается при создании и не может быть изменен. Создайте новый ресурс с другим именем.") + return + } + } + if !plan.VdcGroupUid.IsNull() && !plan.VdcGroupUid.IsUnknown() && !state.VdcGroupUid.IsNull() && !state.VdcGroupUid.IsUnknown() { + if plan.VdcGroupUid.ValueString() != state.VdcGroupUid.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить vdc_group_uid", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.VdcType.IsNull() && !plan.VdcType.IsUnknown() && !state.VdcType.IsNull() && !state.VdcType.IsUnknown() { + if plan.VdcType.ValueString() != state.VdcType.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить vdc_type", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.VdcUid.IsNull() && !plan.VdcUid.IsUnknown() && !state.VdcUid.IsNull() && !state.VdcUid.IsUnknown() { + if plan.VdcUid.ValueString() != state.VdcUid.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить vdc_uid", "Параметр задается при создании и не может быть изменен.") + return + } + } + return + } + + if config.ResourceName.IsNull() || config.ResourceName.IsUnknown() { + return + } + adoptExistingOnCreate := false + if !config.AdoptExistingOnCreate.IsNull() && !config.AdoptExistingOnCreate.IsUnknown() { + adoptExistingOnCreate = config.AdoptExistingOnCreate.ValueBool() + } + if !config.VdcGroupUid.IsNull() && !config.VdcGroupUid.IsUnknown() { + resolvedVdcGroupUid, err := r.client.ResolveRefSvcParamValue(ctx, 29, config.VdcGroupUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_group_uid", err.Error()) + } else if resolvedVdcGroupUid != "" && resolvedVdcGroupUid != config.VdcGroupUid.ValueString() { + config.VdcGroupUid = types.StringValue(resolvedVdcGroupUid) + } + } + if !config.VdcUid.IsNull() && !config.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, config.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_uid", err.Error()) + } else if resolvedVdcUid != "" && resolvedVdcUid != config.VdcUid.ValueString() { + config.VdcUid = types.StringValue(resolvedVdcUid) + } + } + params := map[int]string{ + 8: resources_core.FormatString(config.VdcUid), + 340: resources_core.FormatBool(config.NeedEnableAVI), + 341: resources_core.FormatInt64(config.VirtualServicesCount), + 621: resources_core.FormatString(config.VdcType), + 622: resources_core.FormatString(config.VdcGroupUid), + } + + resp.Diagnostics.Append(resources_core.PlanExistingResourceDiagnosticsWithParams(ctx, r.client, 22, config.ResourceName.ValueString(), adoptExistingOnCreate, params)...) +} + +func (r *VcNsxtResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data VcNsxtModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + if !data.VdcGroupUid.IsNull() && !data.VdcGroupUid.IsUnknown() { + resolvedVdcGroupUid, err := r.client.ResolveRefSvcParamValue(ctx, 29, data.VdcGroupUid.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + if resolvedVdcGroupUid != "" && resolvedVdcGroupUid != data.VdcGroupUid.ValueString() { + data.VdcGroupUid = types.StringValue(resolvedVdcGroupUid) + } + } + if !data.VdcUid.IsNull() && !data.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, data.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + if resolvedVdcUid != "" && resolvedVdcUid != data.VdcUid.ValueString() { + data.VdcUid = types.StringValue(resolvedVdcUid) + } + } + + resourceName := data.ResourceName.ValueString() + resp.Diagnostics.Append(resources_core.CreateExistingResourceDiagnostics(ctx, r.client, 22, resourceName, data.AdoptExistingOnCreate.ValueBool())...) + + params := map[int]string{ + 8: resources_core.FormatString(data.VdcUid), + 340: resources_core.FormatBool(data.NeedEnableAVI), + 341: resources_core.FormatInt64(data.VirtualServicesCount), + 621: resources_core.FormatString(data.VdcType), + 622: resources_core.FormatString(data.VdcGroupUid), + } + + operationTimeout := "" + if !data.OperationTimeout.IsNull() && !data.OperationTimeout.IsUnknown() { + operationTimeout = data.OperationTimeout.ValueString() + } + id, err := resources_core.CreateResourceWithTimeout(ctx, r.client, 22, 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, 22, 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: "ipSpaceName", Field: "IpSpaceName", Type: "string"}, + {Code: "needEnableAVI", Field: "NeedEnableAVI", Type: "bool"}, + {Code: "needExternalAddressSNAT", Field: "NeedExternalAddressSNAT", Type: "bool"}, + {Code: "vdcGroupUid", Field: "VdcGroupUid", Type: "string"}, + {Code: "vdcType", Field: "VdcType", Type: "string"}, + {Code: "vdcUid", Field: "VdcUid", Type: "string"}, + {Code: "virtualServicesCount", Field: "VirtualServicesCount", Type: "int64"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !state.VdcGroupUid.IsNull() && !state.VdcGroupUid.IsUnknown() { + resolvedVdcGroupUid, err := r.client.ResolveRefSvcParamValue(ctx, 29, state.VdcGroupUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_group_uid", err.Error()) + } else if resolvedVdcGroupUid != "" && resolvedVdcGroupUid != state.VdcGroupUid.ValueString() { + state.VdcGroupUid = types.StringValue(resolvedVdcGroupUid) + } + } + if !state.VdcUid.IsNull() && !state.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, state.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_uid", err.Error()) + } else if resolvedVdcUid != "" && resolvedVdcUid != state.VdcUid.ValueString() { + state.VdcUid = types.StringValue(resolvedVdcUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcNsxtResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state VcNsxtModel + 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(), 22, 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: "ipSpaceName", Field: "IpSpaceName", Type: "string"}, + {Code: "needEnableAVI", Field: "NeedEnableAVI", Type: "bool"}, + {Code: "needExternalAddressSNAT", Field: "NeedExternalAddressSNAT", Type: "bool"}, + {Code: "vdcGroupUid", Field: "VdcGroupUid", Type: "string"}, + {Code: "vdcType", Field: "VdcType", Type: "string"}, + {Code: "vdcUid", Field: "VdcUid", Type: "string"}, + {Code: "virtualServicesCount", Field: "VirtualServicesCount", Type: "int64"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !newState.VdcGroupUid.IsNull() && !newState.VdcGroupUid.IsUnknown() { + resolvedVdcGroupUid, err := r.client.ResolveRefSvcParamValue(ctx, 29, newState.VdcGroupUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_group_uid", err.Error()) + } else if resolvedVdcGroupUid != "" && resolvedVdcGroupUid != newState.VdcGroupUid.ValueString() { + newState.VdcGroupUid = types.StringValue(resolvedVdcGroupUid) + } + } + if !newState.VdcUid.IsNull() && !newState.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, newState.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_uid", err.Error()) + } else if resolvedVdcUid != "" && resolvedVdcUid != newState.VdcUid.ValueString() { + newState.VdcUid = types.StringValue(resolvedVdcUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &newState)...) +} + +func (r *VcNsxtResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan VcNsxtModel + var state VcNsxtModel + 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.NeedEnableAVI.IsNull() != state.NeedEnableAVI.IsNull() || plan.NeedEnableAVI.IsUnknown() != state.NeedEnableAVI.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.NeedEnableAVI.IsNull() && !plan.NeedEnableAVI.IsUnknown() && !state.NeedEnableAVI.IsNull() && !state.NeedEnableAVI.IsUnknown() { + if plan.NeedEnableAVI.ValueBool() != state.NeedEnableAVI.ValueBool() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.VirtualServicesCount.IsNull() != state.VirtualServicesCount.IsNull() || plan.VirtualServicesCount.IsUnknown() != state.VirtualServicesCount.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.VirtualServicesCount.IsNull() && !plan.VirtualServicesCount.IsUnknown() && !state.VirtualServicesCount.IsNull() && !state.VirtualServicesCount.IsUnknown() { + if plan.VirtualServicesCount.ValueInt64() != state.VirtualServicesCount.ValueInt64() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.NeedExternalAddressSNAT.IsNull() != state.NeedExternalAddressSNAT.IsNull() || plan.NeedExternalAddressSNAT.IsUnknown() != state.NeedExternalAddressSNAT.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.NeedExternalAddressSNAT.IsNull() && !plan.NeedExternalAddressSNAT.IsUnknown() && !state.NeedExternalAddressSNAT.IsNull() && !state.NeedExternalAddressSNAT.IsUnknown() { + if plan.NeedExternalAddressSNAT.ValueBool() != state.NeedExternalAddressSNAT.ValueBool() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.IpSpaceName.IsNull() != state.IpSpaceName.IsNull() || plan.IpSpaceName.IsUnknown() != state.IpSpaceName.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.IpSpaceName.IsNull() && !plan.IpSpaceName.IsUnknown() && !state.IpSpaceName.IsNull() && !state.IpSpaceName.IsUnknown() { + if plan.IpSpaceName.ValueString() != state.IpSpaceName.ValueString() { + hasServiceParamChanges = true + } + } + } + + if !hasServiceParamChanges { + plan.ID = instanceID + plan.StateParams = state.StateParams + plan.StateOut = state.StateOut + plan.StateParamsFlat = state.StateParamsFlat + plan.StateOutFlat = state.StateOutFlat + plan.VaultSecrets = state.VaultSecrets + plan.VaultUrl = state.VaultUrl + plan.VaultUserPath = state.VaultUserPath + plan.VaultFields = state.VaultFields + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) + return + } + + params := map[int]string{ + 368: resources_core.FormatBool(plan.NeedEnableAVI), + 369: resources_core.FormatInt64(plan.VirtualServicesCount), + 371: resources_core.FormatBool(plan.NeedExternalAddressSNAT), + 372: resources_core.FormatString(plan.IpSpaceName), + } + + operationTimeout := "" + if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { + operationTimeout = plan.OperationTimeout.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(), 22, 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: "ipSpaceName", Field: "IpSpaceName", Type: "string"}, + {Code: "needEnableAVI", Field: "NeedEnableAVI", Type: "bool"}, + {Code: "needExternalAddressSNAT", Field: "NeedExternalAddressSNAT", Type: "bool"}, + {Code: "vdcGroupUid", Field: "VdcGroupUid", Type: "string"}, + {Code: "vdcType", Field: "VdcType", Type: "string"}, + {Code: "vdcUid", Field: "VdcUid", Type: "string"}, + {Code: "virtualServicesCount", Field: "VirtualServicesCount", Type: "int64"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !state.VdcGroupUid.IsNull() && !state.VdcGroupUid.IsUnknown() { + resolvedVdcGroupUid, err := r.client.ResolveRefSvcParamValue(ctx, 29, state.VdcGroupUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_group_uid", err.Error()) + } else if resolvedVdcGroupUid != "" && resolvedVdcGroupUid != state.VdcGroupUid.ValueString() { + state.VdcGroupUid = types.StringValue(resolvedVdcGroupUid) + } + } + if !state.VdcUid.IsNull() && !state.VdcUid.IsUnknown() { + resolvedVdcUid, err := r.client.ResolveRefSvcParamValue(ctx, 21, state.VdcUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vdc_uid", err.Error()) + } else if resolvedVdcUid != "" && resolvedVdcUid != state.VdcUid.ValueString() { + state.VdcUid = types.StringValue(resolvedVdcUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcNsxtResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state VcNsxtModel + 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 err := resources_core.DeleteResourceWithTimeout(ctx, r.client, state.ID.ValueString(), deleteMode, operationTimeout); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } +} + +func (r *VcNsxtResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +func (r *VcNsxtResource) 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 +} diff --git a/universal_rebuild/internal/resources_gen/23_vc_vm_resource.go b/universal_rebuild/internal/resources_gen/23_vc_vm_resource.go new file mode 100644 index 0000000..744b786 --- /dev/null +++ b/universal_rebuild/internal/resources_gen/23_vc_vm_resource.go @@ -0,0 +1,506 @@ +package resources_gen + +import ( + "context" + + "terraform-provider-nubes/internal/core" + "terraform-provider-nubes/internal/resources_core" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Code generated by tools/gen_v2. DO NOT EDIT. +// Service: vc_vm +// Service ID: 23 + +var _ resource.Resource = &VcVmResource{} +var _ resource.ResourceWithModifyPlan = &VcVmResource{} +var _ resource.ResourceWithImportState = &VcVmResource{} + +type VcVmResource struct { + client *core.UniversalClient +} + +type VcVmModel struct { + ID types.String `tfsdk:"id"` + ResourceName types.String `tfsdk:"resource_name"` + OperationTimeout types.String `tfsdk:"operation_timeout"` + AccessIpList types.String `tfsdk:"access_ip_list"` + IpSpaceName types.String `tfsdk:"ip_space_name"` + TemplateName types.String `tfsdk:"template_name"` + VappUid types.String `tfsdk:"vapp_uid"` + VmCpu types.String `tfsdk:"vm_cpu"` + VmDisksize types.String `tfsdk:"vm_disksize"` + VmName types.String `tfsdk:"vm_name"` + VmRam types.String `tfsdk:"vm_ram"` + 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 NewVcVmResource() resource.Resource { + return &VcVmResource{} +} + +func (r *VcVmResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_vc_vm" +} + +func (r *VcVmResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + attrs := map[string]schema.Attribute{ + "id": schema.StringAttribute{Computed: true}, + "resource_name": schema.StringAttribute{Required: true}, + "operation_timeout": schema.StringAttribute{Optional: true}, + "access_ip_list": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("79.111.119.78/32 185.247.187.1/32"), MarkdownDescription: "Вставить содержимое из 'curl ifconfig.io'
IP адреса в CIDR формате через пробел для настройки аксес листов"}, + "ip_space_name": schema.StringAttribute{Required: true, MarkdownDescription: "Брать из свойств ресурсной платформы
.vcd.ipSpace

Имя IP-space для выделения внешнего IP (IP выделяется обязательно) Не изменяется после создания."}, + "template_name": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("RockyLinux_9-16G"), MarkdownDescription: "ОС Не изменяется после создания."}, + "vapp_uid": schema.StringAttribute{Required: true, MarkdownDescription: "InstanceUid vApp. vApp должен быть создан Не изменяется после создания."}, + "vm_cpu": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("2"), MarkdownDescription: "CPU"}, + "vm_disksize": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("10"), MarkdownDescription: "Размер диска под сервис (GB)"}, + "vm_name": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("vm0001"), MarkdownDescription: "Имя ВМ. Не поддерживает спец-символы Не изменяется после создания."}, + "vm_ram": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("2"), MarkdownDescription: "RAM (GB)"}, + "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 *VcVmResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { + if r.client == nil { + return + } + + var config *VcVmModel + resp.Diagnostics.Append(req.Config.Get(ctx, &config)...) + if resp.Diagnostics.HasError() { + return + } + if config == nil { + return + } + + var state *VcVmModel + 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 VcVmModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + planChanged := false + if !plan.VappUid.IsNull() && !plan.VappUid.IsUnknown() { + resolvedVappUid, err := r.client.ResolveRefSvcParamValue(ctx, 26, plan.VappUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vapp_uid", err.Error()) + } else if resolvedVappUid != "" && resolvedVappUid != plan.VappUid.ValueString() { + plan.VappUid = types.StringValue(resolvedVappUid) + planChanged = true + } + } + if planChanged { + resp.Diagnostics.Append(resp.Plan.Set(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + } + if !plan.ResourceName.IsNull() && !plan.ResourceName.IsUnknown() && !state.ResourceName.IsNull() && !state.ResourceName.IsUnknown() { + if plan.ResourceName.ValueString() != state.ResourceName.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить resource_name", "Параметр resource_name задается при создании и не может быть изменен. Создайте новый ресурс с другим именем.") + return + } + } + if !plan.IpSpaceName.IsNull() && !plan.IpSpaceName.IsUnknown() && !state.IpSpaceName.IsNull() && !state.IpSpaceName.IsUnknown() { + if plan.IpSpaceName.ValueString() != state.IpSpaceName.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить ip_space_name", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.TemplateName.IsNull() && !plan.TemplateName.IsUnknown() && !state.TemplateName.IsNull() && !state.TemplateName.IsUnknown() { + if plan.TemplateName.ValueString() != state.TemplateName.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить template_name", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.VappUid.IsNull() && !plan.VappUid.IsUnknown() && !state.VappUid.IsNull() && !state.VappUid.IsUnknown() { + if plan.VappUid.ValueString() != state.VappUid.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить vapp_uid", "Параметр задается при создании и не может быть изменен.") + return + } + } + if !plan.VmName.IsNull() && !plan.VmName.IsUnknown() && !state.VmName.IsNull() && !state.VmName.IsUnknown() { + if plan.VmName.ValueString() != state.VmName.ValueString() { + resp.Diagnostics.AddError("Нельзя изменить vm_name", "Параметр задается при создании и не может быть изменен.") + return + } + } + return + } + if config.IpSpaceName.IsNull() || config.IpSpaceName.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "ip_space_name is required.") + return + } + if config.VappUid.IsNull() || config.VappUid.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "vapp_uid is required.") + return + } + + if config.ResourceName.IsNull() || config.ResourceName.IsUnknown() { + return + } + adoptExistingOnCreate := false + if !config.AdoptExistingOnCreate.IsNull() && !config.AdoptExistingOnCreate.IsUnknown() { + adoptExistingOnCreate = config.AdoptExistingOnCreate.ValueBool() + } + if !config.VappUid.IsNull() && !config.VappUid.IsUnknown() { + resolvedVappUid, err := r.client.ResolveRefSvcParamValue(ctx, 26, config.VappUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vapp_uid", err.Error()) + } else if resolvedVappUid != "" && resolvedVappUid != config.VappUid.ValueString() { + config.VappUid = types.StringValue(resolvedVappUid) + } + } + params := map[int]string{ + 33: resources_core.FormatString(config.VappUid), + 35: resources_core.FormatString(config.VmName), + 36: resources_core.FormatString(config.VmCpu), + 37: resources_core.FormatString(config.VmRam), + 38: resources_core.FormatString(config.VmDisksize), + 176: resources_core.FormatString(config.TemplateName), + 177: resources_core.FormatString(config.AccessIpList), + 406: resources_core.FormatString(config.IpSpaceName), + } + + resp.Diagnostics.Append(resources_core.PlanExistingResourceDiagnosticsWithParams(ctx, r.client, 23, config.ResourceName.ValueString(), adoptExistingOnCreate, params)...) +} + +func (r *VcVmResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data VcVmModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + if data.IpSpaceName.IsNull() || data.IpSpaceName.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "ip_space_name is required.") + return + } + if data.VappUid.IsNull() || data.VappUid.IsUnknown() { + resp.Diagnostics.AddError("Missing required attribute", "vapp_uid is required.") + return + } + if !data.VappUid.IsNull() && !data.VappUid.IsUnknown() { + resolvedVappUid, err := r.client.ResolveRefSvcParamValue(ctx, 26, data.VappUid.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } + if resolvedVappUid != "" && resolvedVappUid != data.VappUid.ValueString() { + data.VappUid = types.StringValue(resolvedVappUid) + } + } + + resourceName := data.ResourceName.ValueString() + resp.Diagnostics.Append(resources_core.CreateExistingResourceDiagnostics(ctx, r.client, 23, resourceName, data.AdoptExistingOnCreate.ValueBool())...) + + params := map[int]string{ + 33: resources_core.FormatString(data.VappUid), + 35: resources_core.FormatString(data.VmName), + 36: resources_core.FormatString(data.VmCpu), + 37: resources_core.FormatString(data.VmRam), + 38: resources_core.FormatString(data.VmDisksize), + 176: resources_core.FormatString(data.TemplateName), + 177: resources_core.FormatString(data.AccessIpList), + 406: resources_core.FormatString(data.IpSpaceName), + } + + operationTimeout := "" + if !data.OperationTimeout.IsNull() && !data.OperationTimeout.IsUnknown() { + operationTimeout = data.OperationTimeout.ValueString() + } + id, err := resources_core.CreateResourceWithTimeout(ctx, r.client, 23, 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, 23, 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: "accessIpList", Field: "AccessIpList", Type: "string"}, + {Code: "ipSpaceName", Field: "IpSpaceName", Type: "string"}, + {Code: "templateName", Field: "TemplateName", Type: "string"}, + {Code: "vappUid", Field: "VappUid", Type: "string"}, + {Code: "vmCpu", Field: "VmCpu", Type: "string"}, + {Code: "vmDisksize", Field: "VmDisksize", Type: "string"}, + {Code: "vmName", Field: "VmName", Type: "string"}, + {Code: "vmRam", Field: "VmRam", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !state.VappUid.IsNull() && !state.VappUid.IsUnknown() { + resolvedVappUid, err := r.client.ResolveRefSvcParamValue(ctx, 26, state.VappUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vapp_uid", err.Error()) + } else if resolvedVappUid != "" && resolvedVappUid != state.VappUid.ValueString() { + state.VappUid = types.StringValue(resolvedVappUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcVmResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state VcVmModel + 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(), 23, 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: "accessIpList", Field: "AccessIpList", Type: "string"}, + {Code: "ipSpaceName", Field: "IpSpaceName", Type: "string"}, + {Code: "templateName", Field: "TemplateName", Type: "string"}, + {Code: "vappUid", Field: "VappUid", Type: "string"}, + {Code: "vmCpu", Field: "VmCpu", Type: "string"}, + {Code: "vmDisksize", Field: "VmDisksize", Type: "string"}, + {Code: "vmName", Field: "VmName", Type: "string"}, + {Code: "vmRam", Field: "VmRam", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !newState.VappUid.IsNull() && !newState.VappUid.IsUnknown() { + resolvedVappUid, err := r.client.ResolveRefSvcParamValue(ctx, 26, newState.VappUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vapp_uid", err.Error()) + } else if resolvedVappUid != "" && resolvedVappUid != newState.VappUid.ValueString() { + newState.VappUid = types.StringValue(resolvedVappUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &newState)...) +} + +func (r *VcVmResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan VcVmModel + var state VcVmModel + 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.VmCpu.IsNull() != state.VmCpu.IsNull() || plan.VmCpu.IsUnknown() != state.VmCpu.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.VmCpu.IsNull() && !plan.VmCpu.IsUnknown() && !state.VmCpu.IsNull() && !state.VmCpu.IsUnknown() { + if plan.VmCpu.ValueString() != state.VmCpu.ValueString() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.VmRam.IsNull() != state.VmRam.IsNull() || plan.VmRam.IsUnknown() != state.VmRam.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.VmRam.IsNull() && !plan.VmRam.IsUnknown() && !state.VmRam.IsNull() && !state.VmRam.IsUnknown() { + if plan.VmRam.ValueString() != state.VmRam.ValueString() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.VmDisksize.IsNull() != state.VmDisksize.IsNull() || plan.VmDisksize.IsUnknown() != state.VmDisksize.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.VmDisksize.IsNull() && !plan.VmDisksize.IsUnknown() && !state.VmDisksize.IsNull() && !state.VmDisksize.IsUnknown() { + if plan.VmDisksize.ValueString() != state.VmDisksize.ValueString() { + hasServiceParamChanges = true + } + } + } + if !hasServiceParamChanges { + if plan.AccessIpList.IsNull() != state.AccessIpList.IsNull() || plan.AccessIpList.IsUnknown() != state.AccessIpList.IsUnknown() { + hasServiceParamChanges = true + } else if !plan.AccessIpList.IsNull() && !plan.AccessIpList.IsUnknown() && !state.AccessIpList.IsNull() && !state.AccessIpList.IsUnknown() { + if plan.AccessIpList.ValueString() != state.AccessIpList.ValueString() { + hasServiceParamChanges = true + } + } + } + + if !hasServiceParamChanges { + plan.ID = instanceID + plan.StateParams = state.StateParams + plan.StateOut = state.StateOut + plan.StateParamsFlat = state.StateParamsFlat + plan.StateOutFlat = state.StateOutFlat + plan.VaultSecrets = state.VaultSecrets + plan.VaultUrl = state.VaultUrl + plan.VaultUserPath = state.VaultUserPath + plan.VaultFields = state.VaultFields + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) + return + } + + params := map[int]string{ + 186: resources_core.FormatString(plan.VmCpu), + 187: resources_core.FormatString(plan.VmRam), + 188: resources_core.FormatString(plan.VmDisksize), + 189: resources_core.FormatString(plan.AccessIpList), + } + + operationTimeout := "" + if !plan.OperationTimeout.IsNull() && !plan.OperationTimeout.IsUnknown() { + operationTimeout = plan.OperationTimeout.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(), 23, 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: "accessIpList", Field: "AccessIpList", Type: "string"}, + {Code: "ipSpaceName", Field: "IpSpaceName", Type: "string"}, + {Code: "templateName", Field: "TemplateName", Type: "string"}, + {Code: "vappUid", Field: "VappUid", Type: "string"}, + {Code: "vmCpu", Field: "VmCpu", Type: "string"}, + {Code: "vmDisksize", Field: "VmDisksize", Type: "string"}, + {Code: "vmName", Field: "VmName", Type: "string"}, + {Code: "vmRam", Field: "VmRam", Type: "string"}, + }) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + if !state.VappUid.IsNull() && !state.VappUid.IsUnknown() { + resolvedVappUid, err := r.client.ResolveRefSvcParamValue(ctx, 26, state.VappUid.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("Failed to resolve vapp_uid", err.Error()) + } else if resolvedVappUid != "" && resolvedVappUid != state.VappUid.ValueString() { + state.VappUid = types.StringValue(resolvedVappUid) + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *VcVmResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state VcVmModel + 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 err := resources_core.DeleteResourceWithTimeout(ctx, r.client, state.ID.ValueString(), deleteMode, operationTimeout); err != nil { + resp.Diagnostics.AddError("Ошибка клиента", err.Error()) + return + } +} + +func (r *VcVmResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +func (r *VcVmResource) 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 +}