feat: Terraform провайдер sless v0.1.0 + обновление doc/progress.md
Независимый Go-модуль terraform/provider/ для управления функциями через REST API. Ресурсы: - sless_function: CRUD + upload zip + WaitReady (kaniko build 5 мин) - sless_trigger: CRUD (http/cron) Компоненты: - internal/client/client.go — HTTP-клиент, готов к переносу в nubes - internal/provider/provider.go — паттерн идентичен nubes NubesProvider - internal/resources/ — function_resource.go, trigger_resource.go - hack/build-and-publish.sh — GPG-подпись + mc upload в S3 Опубликовано: terra.k8c.ru/naeel/sless v0.1.0 Проверено: terraform init успешен
This commit is contained in:
@@ -0,0 +1,311 @@
|
||||
// 2026-03-07
|
||||
// function_resource.go — Terraform ресурс sless_function.
|
||||
//
|
||||
// Lifecycle:
|
||||
//
|
||||
// Create: POST /functions → если code_path задан: upload zip → WaitReady (5 мин)
|
||||
// Read: GET /functions/{name} → sync state
|
||||
// Update: PUT /functions/{name} → если code_hash изменился: upload zip → WaitReady
|
||||
// Delete: DELETE /functions/{name}
|
||||
//
|
||||
// code_hash — пользователь задаёт сам (например filemd5("./handler.zip")).
|
||||
// Изменение hash → провайдер перезагружает zip и ждёт новой сборки.
|
||||
// Это стандартный паттерн для file-based ресурсов в terraform-plugin-framework.
|
||||
//
|
||||
// При переносе в nubes: файл кладётся в internal/resources_gen/ без изменений,
|
||||
// client.Client заменяется на *core.UniversalClient или аналогичный.
|
||||
package resources
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"terraform-provider-sless/internal/client"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
// buildTimeout — максимальное время ожидания kaniko-сборки образа.
|
||||
const buildTimeout = 5 * time.Minute
|
||||
|
||||
var _ resource.Resource = &FunctionResource{}
|
||||
|
||||
type FunctionResource struct {
|
||||
client *client.Client
|
||||
}
|
||||
|
||||
func NewFunctionResource() resource.Resource {
|
||||
return &FunctionResource{}
|
||||
}
|
||||
|
||||
// FunctionModel — модель состояния terraform для sless_function.
|
||||
type FunctionModel struct {
|
||||
Namespace types.String `tfsdk:"namespace"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Runtime types.String `tfsdk:"runtime"`
|
||||
Entrypoint types.String `tfsdk:"entrypoint"`
|
||||
MemoryMB types.Int64 `tfsdk:"memory_mb"`
|
||||
TimeoutSec types.Int64 `tfsdk:"timeout_sec"`
|
||||
EnvVars types.Map `tfsdk:"env_vars"`
|
||||
CodePath types.String `tfsdk:"code_path"`
|
||||
// code_hash — sha256/md5 zip-файла, пользователь задаёт через filemd5().
|
||||
// Изменение hash → провайдер перезагружает код и запускает пересборку.
|
||||
CodeHash types.String `tfsdk:"code_hash"`
|
||||
Phase types.String `tfsdk:"phase"`
|
||||
ImageRef types.String `tfsdk:"image_ref"`
|
||||
}
|
||||
|
||||
func (r *FunctionResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_function"
|
||||
}
|
||||
|
||||
func (r *FunctionResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
// namespace + name — immutable, смена требует пересоздания ресурса
|
||||
"namespace": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"runtime": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"entrypoint": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"memory_mb": schema.Int64Attribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
"timeout_sec": schema.Int64Attribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
"env_vars": schema.MapAttribute{
|
||||
ElementType: types.StringType,
|
||||
Optional: true,
|
||||
},
|
||||
"code_path": schema.StringAttribute{
|
||||
Optional: true,
|
||||
},
|
||||
// code_hash — задаётся через filemd5("./handler.zip") в .tf
|
||||
"code_hash": schema.StringAttribute{
|
||||
Optional: true,
|
||||
},
|
||||
// phase, image_ref — только для чтения, вычисляются оператором
|
||||
"phase": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"image_ref": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *FunctionResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
c, ok := req.ProviderData.(*client.Client)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError(
|
||||
"unexpected provider data",
|
||||
fmt.Sprintf("expected *client.Client, got: %T", req.ProviderData),
|
||||
)
|
||||
return
|
||||
}
|
||||
r.client = c
|
||||
}
|
||||
|
||||
func (r *FunctionResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan FunctionModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ns := plan.Namespace.ValueString()
|
||||
envVars, d := mapToStringMap(ctx, plan.EnvVars)
|
||||
resp.Diagnostics.Append(d...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
fn, err := r.client.CreateFunction(ctx, ns, client.FunctionRequest{
|
||||
Name: plan.Name.ValueString(),
|
||||
Runtime: plan.Runtime.ValueString(),
|
||||
Entrypoint: plan.Entrypoint.ValueString(),
|
||||
MemoryMB: int32(plan.MemoryMB.ValueInt64()),
|
||||
TimeoutSec: int32(plan.TimeoutSec.ValueInt64()),
|
||||
Env: envVars,
|
||||
})
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("create function", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if !plan.CodePath.IsNull() && plan.CodePath.ValueString() != "" {
|
||||
if err := r.client.UploadCode(ctx, ns, fn.Name, plan.CodePath.ValueString()); err != nil {
|
||||
resp.Diagnostics.AddError("upload code", err.Error())
|
||||
return
|
||||
}
|
||||
fn, err = r.client.WaitReady(ctx, ns, fn.Name, buildTimeout)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("waiting for function ready", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, fnToModel(plan, fn))...)
|
||||
}
|
||||
|
||||
func (r *FunctionResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state FunctionModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
fn, err := r.client.GetFunction(ctx, state.Namespace.ValueString(), state.Name.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("read function", err.Error())
|
||||
return
|
||||
}
|
||||
if fn == nil {
|
||||
// Ресурс удалён вне terraform — убираем из state
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, fnToModel(state, fn))...)
|
||||
}
|
||||
|
||||
func (r *FunctionResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan, state FunctionModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ns := plan.Namespace.ValueString()
|
||||
name := plan.Name.ValueString()
|
||||
|
||||
envVars, d := mapToStringMap(ctx, plan.EnvVars)
|
||||
resp.Diagnostics.Append(d...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
fn, err := r.client.UpdateFunction(ctx, ns, name, client.FunctionRequest{
|
||||
Name: name,
|
||||
Runtime: plan.Runtime.ValueString(),
|
||||
Entrypoint: plan.Entrypoint.ValueString(),
|
||||
MemoryMB: int32(plan.MemoryMB.ValueInt64()),
|
||||
TimeoutSec: int32(plan.TimeoutSec.ValueInt64()),
|
||||
Env: envVars,
|
||||
})
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("update function", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Перезагружаем код только если code_hash изменился
|
||||
// Это предотвращает ненужные пересборки при apply без изменений кода
|
||||
if !plan.CodeHash.Equal(state.CodeHash) && !plan.CodePath.IsNull() && plan.CodePath.ValueString() != "" {
|
||||
if err := r.client.UploadCode(ctx, ns, name, plan.CodePath.ValueString()); err != nil {
|
||||
resp.Diagnostics.AddError("upload code", err.Error())
|
||||
return
|
||||
}
|
||||
fn, err = r.client.WaitReady(ctx, ns, name, buildTimeout)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("waiting for function ready", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, fnToModel(plan, fn))...)
|
||||
}
|
||||
|
||||
func (r *FunctionResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state FunctionModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.client.DeleteFunction(ctx, state.Namespace.ValueString(), state.Name.ValueString()); err != nil {
|
||||
resp.Diagnostics.AddError("delete function", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// fnToModel конвертирует API-ответ + plan (для локальных полей) → state модель.
|
||||
// plan используется для code_path и code_hash — API их не хранит.
|
||||
func fnToModel(plan FunctionModel, fn *client.FunctionResponse) FunctionModel {
|
||||
return FunctionModel{
|
||||
Namespace: types.StringValue(fn.Namespace),
|
||||
Name: types.StringValue(fn.Name),
|
||||
Runtime: types.StringValue(fn.Runtime),
|
||||
Entrypoint: types.StringValue(fn.Entrypoint),
|
||||
MemoryMB: types.Int64Value(int64(fn.MemoryMB)),
|
||||
TimeoutSec: types.Int64Value(int64(fn.TimeoutSec)),
|
||||
EnvVars: plan.EnvVars, // API возвращает null для пустого map — берём из plan
|
||||
CodePath: plan.CodePath,
|
||||
CodeHash: plan.CodeHash,
|
||||
Phase: types.StringValue(fn.Phase),
|
||||
ImageRef: types.StringValue(fn.ImageRef),
|
||||
}
|
||||
}
|
||||
|
||||
// mapToStringMap конвертирует types.Map → map[string]string.
|
||||
func mapToStringMap(ctx context.Context, m types.Map) (map[string]string, diag.Diagnostics) {
|
||||
if m.IsNull() || m.IsUnknown() {
|
||||
return nil, nil
|
||||
}
|
||||
elements := m.Elements()
|
||||
result := make(map[string]string, len(elements))
|
||||
var diags diag.Diagnostics
|
||||
for k, v := range elements {
|
||||
sv, ok := v.(attr.Value)
|
||||
if !ok {
|
||||
diags.AddError("env_vars conversion", fmt.Sprintf("unexpected type for key %q", k))
|
||||
continue
|
||||
}
|
||||
strVal, ok := sv.(types.String)
|
||||
if !ok {
|
||||
diags.AddError("env_vars conversion", fmt.Sprintf("value for key %q is not a string", k))
|
||||
continue
|
||||
}
|
||||
result[k] = strVal.ValueString()
|
||||
}
|
||||
return result, diags
|
||||
}
|
||||
Reference in New Issue
Block a user