Files
tf_provider/generated/dev/go/13_s3bucket_resource.go
T
“Naeel” dd56bcda83 refactor: restructure project — separate tools, config, generated, provider
TOOLS/        — generators + scripts + config + ARCHITECTURE.md
  ├── yaml-generator/    (code)
  ├── resource-generator/ (code)
  ├── docs-generator/    (code)
  ├── scripts/           (← devops/*.sh)
  ├── config/            (← devops/profiles/ + devops/config/)
  │   ├── test/          profile.env, services_list.txt, operation_timeouts.json
  │   ├── prod/
  │   └── dev/
  └── ARCHITECTURE.md    (← devops/ARCHITECTURE.md)

generated/    — pipeline output only (gitignored)
  ├── test/resources_yaml/, go/, docs/, provider_build/
  ├── prod/
  └── dev/

provider/     — code only, no generated files
  resources_yaml/        — DELETED (generated)
  internal/resources_gen/ — DELETED (generated)

devops/       — removed (replaced by TOOLS/scripts + TOOLS/config + generated/)

Generators now fail if NUBES_*_DIR not set (no defaults to provider/).
Provider requires pipeline to populate resources_gen/ before build.
2026-07-06 09:06:09 +04:00

451 lines
20 KiB
Go

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: s3bucket
// Service ID: 13
var _ resource.Resource = &S3bucketResource{}
var _ resource.ResourceWithModifyPlan = &S3bucketResource{}
var _ resource.ResourceWithImportState = &S3bucketResource{}
type S3bucketResource struct {
client *core.UniversalClient
}
type S3bucketModel struct {
ID types.String `tfsdk:"id"`
ResourceName types.String `tfsdk:"resource_name"`
OperationTimeout types.String `tfsdk:"operation_timeout"`
LogLevel types.String `tfsdk:"log_level"`
BucketName types.String `tfsdk:"bucket_name"`
CorsAll types.Bool `tfsdk:"cors_all"`
ListAll types.Bool `tfsdk:"list_all"`
MaxSize types.String `tfsdk:"max_size"`
Placement types.String `tfsdk:"placement"`
ReadAll types.Bool `tfsdk:"read_all"`
S3UserUid types.String `tfsdk:"s3_user_uid"`
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 NewS3bucketResource() resource.Resource {
return &S3bucketResource{}
}
func (r *S3bucketResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_s3bucket"
}
func (r *S3bucketResource) 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},
"log_level": schema.StringAttribute{Optional: true, MarkdownDescription: "Operation stages log level: none (default), info, debug. Overrides provider-level log_level."},
"bucket_name": schema.StringAttribute{Required: true, MarkdownDescription: "Имя бакета s3 Не изменяется после создания."},
"cors_all": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Публичный доступ к чтению настроек позволяет любому пользователю интернета читать конфигурации CORS Не изменяется после создания."},
"list_all": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Публичный доступ к листингу позволяет любому пользователю интернета получить список объектов в бакете. Не изменяется после создания."},
"max_size": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("-1"), MarkdownDescription: "Максимальный размер бакета s3. Если поставить -1, будет безлимит. Размер указывается в Bytes Не изменяется после создания."},
"placement": schema.StringAttribute{Optional: true, Computed: true, Default: stringdefault.StaticString("HOT"), MarkdownDescription: "Класс хранилища, который используется по умолчанию при загрузке объектов. Чем холоднее, тем дешевле место, но дороже обращения Не изменяется после создания."},
"read_all": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(false), MarkdownDescription: "Публичный доступ на чтение позволяет любому пользователю интернета скачивать объекты из бакета. Не изменяется после создания."},
"s3_user_uid": schema.StringAttribute{Required: true, MarkdownDescription: "UID Корневой услуги S3. На основе него будет создан бакет. Не изменяется после создания."},
"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 *S3bucketResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) {
if r.client == nil {
return
}
var config *S3bucketModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
if config == nil {
return
}
var state *S3bucketModel
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 S3bucketModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
planChanged := false
if !plan.S3UserUid.IsNull() && !plan.S3UserUid.IsUnknown() {
resolvedS3UserUid, err := r.client.ResolveRefSvcParamValue(ctx, 12, plan.S3UserUid.ValueString())
if err != nil {
resp.Diagnostics.AddWarning("Failed to resolve s3_user_uid", err.Error())
} else if resolvedS3UserUid != "" && resolvedS3UserUid != plan.S3UserUid.ValueString() {
plan.S3UserUid = types.StringValue(resolvedS3UserUid)
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.BucketName.IsNull() && !plan.BucketName.IsUnknown() && !state.BucketName.IsNull() && !state.BucketName.IsUnknown() {
if plan.BucketName.ValueString() != state.BucketName.ValueString() {
resp.Diagnostics.AddError("Нельзя изменить bucket_name", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.CorsAll.IsNull() && !plan.CorsAll.IsUnknown() && !state.CorsAll.IsNull() && !state.CorsAll.IsUnknown() {
if plan.CorsAll.ValueBool() != state.CorsAll.ValueBool() {
resp.Diagnostics.AddError("Нельзя изменить cors_all", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.ListAll.IsNull() && !plan.ListAll.IsUnknown() && !state.ListAll.IsNull() && !state.ListAll.IsUnknown() {
if plan.ListAll.ValueBool() != state.ListAll.ValueBool() {
resp.Diagnostics.AddError("Нельзя изменить list_all", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.MaxSize.IsNull() && !plan.MaxSize.IsUnknown() && !state.MaxSize.IsNull() && !state.MaxSize.IsUnknown() {
if plan.MaxSize.ValueString() != state.MaxSize.ValueString() {
resp.Diagnostics.AddError("Нельзя изменить max_size", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.Placement.IsNull() && !plan.Placement.IsUnknown() && !state.Placement.IsNull() && !state.Placement.IsUnknown() {
if plan.Placement.ValueString() != state.Placement.ValueString() {
resp.Diagnostics.AddError("Нельзя изменить placement", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.ReadAll.IsNull() && !plan.ReadAll.IsUnknown() && !state.ReadAll.IsNull() && !state.ReadAll.IsUnknown() {
if plan.ReadAll.ValueBool() != state.ReadAll.ValueBool() {
resp.Diagnostics.AddError("Нельзя изменить read_all", "Параметр задается при создании и не может быть изменен.")
return
}
}
if !plan.S3UserUid.IsNull() && !plan.S3UserUid.IsUnknown() && !state.S3UserUid.IsNull() && !state.S3UserUid.IsUnknown() {
if plan.S3UserUid.ValueString() != state.S3UserUid.ValueString() {
resp.Diagnostics.AddError("Нельзя изменить s3_user_uid", "Параметр задается при создании и не может быть изменен.")
return
}
}
return
}
if config.BucketName.IsNull() || config.BucketName.IsUnknown() {
resp.Diagnostics.AddError("Missing required attribute", "bucket_name is required.")
return
}
if config.S3UserUid.IsNull() || config.S3UserUid.IsUnknown() {
resp.Diagnostics.AddError("Missing required attribute", "s3_user_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.S3UserUid.IsNull() && !config.S3UserUid.IsUnknown() {
resolvedS3UserUid, err := r.client.ResolveRefSvcParamValue(ctx, 12, config.S3UserUid.ValueString())
if err != nil {
resp.Diagnostics.AddWarning("Failed to resolve s3_user_uid", err.Error())
} else if resolvedS3UserUid != "" && resolvedS3UserUid != config.S3UserUid.ValueString() {
config.S3UserUid = types.StringValue(resolvedS3UserUid)
}
}
params := map[int]string{
124: resources_core.FormatString(config.S3UserUid),
125: resources_core.FormatString(config.BucketName),
126: resources_core.FormatString(config.MaxSize),
127: resources_core.FormatBool(config.ReadAll),
128: resources_core.FormatBool(config.ListAll),
129: resources_core.FormatBool(config.CorsAll),
130: resources_core.FormatString(config.Placement),
}
desiredDomain := ""
domainServiceIDs := []int{2, 50, 81, 82, 88, 89, 94, 95, 96, 97, 98, 99, 119, 149, 151, 153}
resp.Diagnostics.Append(resources_core.PlanExistingResourceDiagnosticsWithParamsAndDomainAndServices(ctx, r.client, 13, config.ResourceName.ValueString(), adoptExistingOnCreate, params, desiredDomain, domainServiceIDs)...)
}
func (r *S3bucketResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var data S3bucketModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
if data.BucketName.IsNull() || data.BucketName.IsUnknown() {
resp.Diagnostics.AddError("Missing required attribute", "bucket_name is required.")
return
}
if data.S3UserUid.IsNull() || data.S3UserUid.IsUnknown() {
resp.Diagnostics.AddError("Missing required attribute", "s3_user_uid is required.")
return
}
resourceName := data.ResourceName.ValueString()
desiredDomain := ""
domainServiceIDs := []int{2, 50, 81, 82, 88, 89, 94, 95, 96, 97, 98, 99, 119, 149, 151, 153}
resp.Diagnostics.Append(resources_core.CreateExistingResourceDiagnosticsWithDomainAndServices(ctx, r.client, 13, resourceName, data.AdoptExistingOnCreate.ValueBool(), desiredDomain, domainServiceIDs)...)
params := map[int]string{
124: resources_core.FormatString(data.S3UserUid),
125: resources_core.FormatString(data.BucketName),
126: resources_core.FormatString(data.MaxSize),
127: resources_core.FormatBool(data.ReadAll),
128: resources_core.FormatBool(data.ListAll),
129: resources_core.FormatBool(data.CorsAll),
130: resources_core.FormatString(data.Placement),
}
operationTimeout := ""
if !data.OperationTimeout.IsNull() && !data.OperationTimeout.IsUnknown() {
operationTimeout = data.OperationTimeout.ValueString()
}
if !data.LogLevel.IsNull() && !data.LogLevel.IsUnknown() {
ctx = core.CtxWithLogLevel(ctx, data.LogLevel.ValueString())
}
id, err := resources_core.CreateResourceWithTimeout(ctx, r.client, 13, 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, 13, 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: "bucketName", Field: "BucketName", Type: "string"},
{Code: "corsAll", Field: "CorsAll", Type: "bool"},
{Code: "listAll", Field: "ListAll", Type: "bool"},
{Code: "maxSize", Field: "MaxSize", Type: "string"},
{Code: "placement", Field: "Placement", Type: "string"},
{Code: "readAll", Field: "ReadAll", Type: "bool"},
})
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *S3bucketResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state S3bucketModel
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(), 13, 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: "bucketName", Field: "BucketName", Type: "string"},
{Code: "corsAll", Field: "CorsAll", Type: "bool"},
{Code: "listAll", Field: "ListAll", Type: "bool"},
{Code: "maxSize", Field: "MaxSize", Type: "string"},
{Code: "placement", Field: "Placement", Type: "string"},
{Code: "readAll", Field: "ReadAll", Type: "bool"},
})
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &newState)...)
}
func (r *S3bucketResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan S3bucketModel
var state S3bucketModel
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 !plan.LogLevel.IsNull() && !plan.LogLevel.IsUnknown() {
ctx = core.CtxWithLogLevel(ctx, plan.LogLevel.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(), 13, 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: "bucketName", Field: "BucketName", Type: "string"},
{Code: "corsAll", Field: "CorsAll", Type: "bool"},
{Code: "listAll", Field: "ListAll", Type: "bool"},
{Code: "maxSize", Field: "MaxSize", Type: "string"},
{Code: "placement", Field: "Placement", Type: "string"},
{Code: "readAll", Field: "ReadAll", Type: "bool"},
})
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *S3bucketResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state S3bucketModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if state.ID.IsNull() || state.ID.IsUnknown() {
return
}
deleteMode := "delete"
operationTimeout := ""
if !state.OperationTimeout.IsNull() && !state.OperationTimeout.IsUnknown() {
operationTimeout = state.OperationTimeout.ValueString()
}
if !state.LogLevel.IsNull() && !state.LogLevel.IsUnknown() {
ctx = core.CtxWithLogLevel(ctx, state.LogLevel.ValueString())
}
if err := resources_core.DeleteResourceWithTimeout(ctx, r.client, state.ID.ValueString(), deleteMode, operationTimeout); err != nil {
resp.Diagnostics.AddError("Ошибка клиента", err.Error())
return
}
}
func (r *S3bucketResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
func (r *S3bucketResource) 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
}