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:
“Naeel”
2026-03-07 10:23:52 +04:00
parent 4115e0f172
commit 19c9e016a8
10 changed files with 1193 additions and 6 deletions
@@ -0,0 +1,292 @@
// 2026-03-07
// client.go — HTTP-клиент для REST API sless оператора.
// Намеренно изолирован от terraform-plugin-framework — при переносе в nubes
// этот файл кладётся в internal/core/ без изменений.
// Все методы принимают ctx для правильной работы с таймаутами terraform.
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
)
// Client — HTTP-клиент к sless operator REST API.
type Client struct {
httpClient *http.Client
endpoint string
token string
}
// New создаёт клиент. endpoint — базовый URL оператора (без trailing slash).
func New(endpoint, token string) *Client {
return &Client{
httpClient: &http.Client{Timeout: 30 * time.Second},
endpoint: endpoint,
token: token,
}
}
// --- JSON-структуры (зеркало handler/functions.go и handler/triggers.go) ---
// FunctionRequest — тело POST/PUT /v1/namespaces/{ns}/functions[/{name}]
type FunctionRequest struct {
Name string `json:"name"`
Runtime string `json:"runtime"`
Entrypoint string `json:"entrypoint,omitempty"`
MemoryMB int32 `json:"memory_mb,omitempty"`
TimeoutSec int32 `json:"timeout_sec,omitempty"`
Env map[string]string `json:"env_vars,omitempty"`
}
// FunctionResponse — ответ GET /v1/namespaces/{ns}/functions/{name}
type FunctionResponse struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Runtime string `json:"runtime"`
Entrypoint string `json:"entrypoint"`
MemoryMB int32 `json:"memory_mb"`
TimeoutSec int32 `json:"timeout_sec"`
Env map[string]string `json:"env_vars"`
S3Bucket string `json:"s3_bucket"`
S3Key string `json:"s3_key"`
Phase string `json:"phase"`
ImageRef string `json:"image_ref"`
Message string `json:"message"`
}
// TriggerRequest — тело POST /v1/namespaces/{ns}/triggers
type TriggerRequest struct {
Name string `json:"name"`
Type string `json:"type"`
FunctionRef string `json:"function"`
Schedule string `json:"schedule,omitempty"`
}
// TriggerResponse — ответ GET /v1/namespaces/{ns}/triggers/{name}
type TriggerResponse struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Type string `json:"type"`
FunctionRef string `json:"function"`
Schedule string `json:"schedule"`
Active bool `json:"active"`
URL string `json:"url"`
Message string `json:"message"`
}
// --- Внутренний хелпер: выполнить JSON-запрос с Bearer-токеном ---
func (c *Client) doJSON(ctx context.Context, method, url string, body interface{}) (*http.Response, error) {
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
bodyReader = bytes.NewReader(data)
}
req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Authorization", "Bearer "+c.token)
return c.httpClient.Do(req)
}
// --- Function CRUD ---
// CreateFunction — POST /v1/namespaces/{ns}/functions → 201
func (c *Client) CreateFunction(ctx context.Context, ns string, req FunctionRequest) (*FunctionResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/functions", c.endpoint, ns)
resp, err := c.doJSON(ctx, http.MethodPost, url, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("create function: status %d: %s", resp.StatusCode, body)
}
var fn FunctionResponse
return &fn, json.NewDecoder(resp.Body).Decode(&fn)
}
// GetFunction — GET /v1/namespaces/{ns}/functions/{name} → nil если 404
func (c *Client) GetFunction(ctx context.Context, ns, name string) (*FunctionResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/functions/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, nil
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("get function: status %d: %s", resp.StatusCode, body)
}
var fn FunctionResponse
return &fn, json.NewDecoder(resp.Body).Decode(&fn)
}
// UpdateFunction — PUT /v1/namespaces/{ns}/functions/{name} → 200
func (c *Client) UpdateFunction(ctx context.Context, ns, name string, req FunctionRequest) (*FunctionResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/functions/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodPut, url, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("update function: status %d: %s", resp.StatusCode, body)
}
var fn FunctionResponse
return &fn, json.NewDecoder(resp.Body).Decode(&fn)
}
// DeleteFunction — DELETE /v1/namespaces/{ns}/functions/{name} → 204
func (c *Client) DeleteFunction(ctx context.Context, ns, name string) error {
url := fmt.Sprintf("%s/v1/namespaces/%s/functions/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodDelete, url, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("delete function: status %d: %s", resp.StatusCode, body)
}
return nil
}
// UploadCode — POST /v1/namespaces/{ns}/functions/{name}/upload (multipart, field=code)
// После вызова оператор начинает kaniko-сборку образа.
func (c *Client) UploadCode(ctx context.Context, ns, name, zipPath string) error {
f, err := os.Open(zipPath)
if err != nil {
return fmt.Errorf("open zip %q: %w", zipPath, err)
}
defer f.Close()
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
fw, err := mw.CreateFormFile("code", filepath.Base(zipPath))
if err != nil {
return fmt.Errorf("create form file: %w", err)
}
if _, err := io.Copy(fw, f); err != nil {
return fmt.Errorf("copy zip: %w", err)
}
mw.Close()
url := fmt.Sprintf("%s/v1/namespaces/%s/functions/%s/upload", c.endpoint, ns, name)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", mw.FormDataContentType())
req.Header.Set("Authorization", "Bearer "+c.token)
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("upload code: status %d: %s", resp.StatusCode, body)
}
return nil
}
// WaitReady опрашивает функцию каждые 5 секунд пока phase != Ready/Failed.
// Нужен после UploadCode — kaniko-сборка занимает ~1 минуту.
func (c *Client) WaitReady(ctx context.Context, ns, name string, timeout time.Duration) (*FunctionResponse, error) {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
fn, err := c.GetFunction(ctx, ns, name)
if err != nil {
return nil, err
}
if fn == nil {
return nil, fmt.Errorf("function %s/%s not found while waiting", ns, name)
}
switch fn.Phase {
case "Ready":
return fn, nil
case "Failed":
return nil, fmt.Errorf("function build failed: %s", fn.Message)
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(5 * time.Second):
}
}
return nil, fmt.Errorf("timeout waiting for function %s/%s to become Ready", ns, name)
}
// --- Trigger CRUD ---
// CreateTrigger — POST /v1/namespaces/{ns}/triggers → 201
func (c *Client) CreateTrigger(ctx context.Context, ns string, req TriggerRequest) (*TriggerResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/triggers", c.endpoint, ns)
resp, err := c.doJSON(ctx, http.MethodPost, url, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("create trigger: status %d: %s", resp.StatusCode, body)
}
var tr TriggerResponse
return &tr, json.NewDecoder(resp.Body).Decode(&tr)
}
// GetTrigger — GET /v1/namespaces/{ns}/triggers/{name} → nil если 404
func (c *Client) GetTrigger(ctx context.Context, ns, name string) (*TriggerResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/triggers/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, nil
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("get trigger: status %d: %s", resp.StatusCode, body)
}
var tr TriggerResponse
return &tr, json.NewDecoder(resp.Body).Decode(&tr)
}
// DeleteTrigger — DELETE /v1/namespaces/{ns}/triggers/{name} → 204
func (c *Client) DeleteTrigger(ctx context.Context, ns, name string) error {
url := fmt.Sprintf("%s/v1/namespaces/%s/triggers/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodDelete, url, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("delete trigger: status %d: %s", resp.StatusCode, body)
}
return nil
}
@@ -0,0 +1,104 @@
// 2026-03-07
// provider.go — описание провайдера sless для Terraform.
// Паттерн идентичен nubes провайдеру (NubesProvider) — для облегчения переноса.
// Атрибуты: endpoint (URL оператора) + token (Bearer).
// Env-переменные: SLESS_ENDPOINT, SLESS_API_TOKEN.
package provider
import (
"context"
"os"
"strings"
"terraform-provider-sless/internal/client"
"terraform-provider-sless/internal/resources"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/provider"
"github.com/hashicorp/terraform-plugin-framework/provider/schema"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var _ provider.Provider = &SlessProvider{}
type SlessProvider struct {
version string
}
// SlessProviderModel — конфигурация блока provider {} в .tf файле.
type SlessProviderModel struct {
Endpoint types.String `tfsdk:"endpoint"`
Token types.String `tfsdk:"token"`
}
// New возвращает фабрику провайдера — точная копия паттерна nubes.
func New(version string) func() provider.Provider {
return func() provider.Provider {
return &SlessProvider{version: version}
}
}
func (p *SlessProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "sless"
resp.Version = p.version
}
func (p *SlessProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"endpoint": schema.StringAttribute{
MarkdownDescription: "sless operator API endpoint, например http://sless-operator.sless.svc:9090",
Optional: true,
},
"token": schema.StringAttribute{
MarkdownDescription: "Bearer-токен аутентификации (env: SLESS_API_TOKEN)",
Optional: true,
Sensitive: true,
},
},
}
}
// Configure инициализирует HTTP-клиент и кладёт его в ResourceData/DataSourceData.
// Ресурсы получают клиент через Configure(req.ProviderData).
func (p *SlessProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
var config SlessProviderModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
endpoint := "http://localhost:9090"
token := ""
if !config.Endpoint.IsNull() && config.Endpoint.ValueString() != "" {
endpoint = config.Endpoint.ValueString()
} else if v := os.Getenv("SLESS_ENDPOINT"); v != "" {
endpoint = v
}
if !config.Token.IsNull() {
token = strings.TrimSpace(config.Token.ValueString())
}
if token == "" {
if v := os.Getenv("SLESS_API_TOKEN"); v != "" {
token = strings.TrimSpace(v)
}
}
c := client.New(endpoint, token)
resp.ResourceData = c
resp.DataSourceData = c
}
func (p *SlessProvider) Resources(_ context.Context) []func() resource.Resource {
return []func() resource.Resource{
resources.NewFunctionResource,
resources.NewTriggerResource,
}
}
func (p *SlessProvider) DataSources(_ context.Context) []func() datasource.DataSource {
return nil
}
@@ -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
}
@@ -0,0 +1,185 @@
// 2026-03-07
// trigger_resource.go — Terraform ресурс sless_trigger.
// Поддерживает type=http (создаёт Service+Ingress) и type=cron (запускает по schedule).
// Все ключевые поля имеют RequiresReplace — API не поддерживает обновление триггеров.
// URL функции (для http-триггера) — computed, пишется оператором в status.url.
package resources
import (
"context"
"fmt"
"terraform-provider-sless/internal/client"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
"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"
)
var _ resource.Resource = &TriggerResource{}
type TriggerResource struct {
client *client.Client
}
func NewTriggerResource() resource.Resource {
return &TriggerResource{}
}
// TriggerModel — модель состояния terraform для sless_trigger.
type TriggerModel struct {
Namespace types.String `tfsdk:"namespace"`
Name types.String `tfsdk:"name"`
Type types.String `tfsdk:"type"`
FunctionRef types.String `tfsdk:"function"`
Schedule types.String `tfsdk:"schedule"`
Active types.Bool `tfsdk:"active"`
URL types.String `tfsdk:"url"`
}
func (r *TriggerResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_trigger"
}
func (r *TriggerResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"namespace": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"name": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
// type: "http" или "cron"
"type": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
// function: имя Function CRD в том же namespace
"function": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
// schedule: только для type=cron, формат cron ("*/5 * * * *")
"schedule": schema.StringAttribute{
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
// active, url — только для чтения, вычисляются оператором
"active": schema.BoolAttribute{
Computed: true,
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
"url": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
},
}
}
func (r *TriggerResource) 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 *TriggerResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan TriggerModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
tr, err := r.client.CreateTrigger(ctx, plan.Namespace.ValueString(), client.TriggerRequest{
Name: plan.Name.ValueString(),
Type: plan.Type.ValueString(),
FunctionRef: plan.FunctionRef.ValueString(),
Schedule: plan.Schedule.ValueString(),
})
if err != nil {
resp.Diagnostics.AddError("create trigger", err.Error())
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, trToModel(tr))...)
}
func (r *TriggerResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state TriggerModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tr, err := r.client.GetTrigger(ctx, state.Namespace.ValueString(), state.Name.ValueString())
if err != nil {
resp.Diagnostics.AddError("read trigger", err.Error())
return
}
if tr == nil {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, trToModel(tr))...)
}
// Update — никогда не вызывается: все поля имеют RequiresReplace.
// Метод обязателен интерфейсом resource.Resource.
func (r *TriggerResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) {
resp.Diagnostics.AddError("update not supported", "all trigger fields require replacement")
}
func (r *TriggerResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state TriggerModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.DeleteTrigger(ctx, state.Namespace.ValueString(), state.Name.ValueString()); err != nil {
resp.Diagnostics.AddError("delete trigger", err.Error())
}
}
// trToModel конвертирует API-ответ → state модель.
func trToModel(tr *client.TriggerResponse) TriggerModel {
return TriggerModel{
Namespace: types.StringValue(tr.Namespace),
Name: types.StringValue(tr.Name),
Type: types.StringValue(tr.Type),
FunctionRef: types.StringValue(tr.FunctionRef),
Schedule: types.StringValue(tr.Schedule),
Active: types.BoolValue(tr.Active),
URL: types.StringValue(tr.URL),
}
}