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:
@@ -28,3 +28,4 @@ Dockerfile.cross
|
|||||||
*.swp
|
*.swp
|
||||||
*.swo
|
*.swo
|
||||||
*~
|
*~
|
||||||
|
terraform/provider/build/
|
||||||
|
|||||||
+41
-6
@@ -38,16 +38,51 @@
|
|||||||
| 6 | PostgreSQL Deployment + Service | ✅ | deployments/k8s/postgres.yaml, Running |
|
| 6 | PostgreSQL Deployment + Service | ✅ | deployments/k8s/postgres.yaml, Running |
|
||||||
| 7 | Secret postgres-secret | ✅ | в namespace sless |
|
| 7 | Secret postgres-secret | ✅ | в namespace sless |
|
||||||
|
|
||||||
|
### Runtime image + Upload endpoint (2026-03-07)
|
||||||
|
|
||||||
|
| # | Компонент | Статус | Заметки |
|
||||||
|
|---|-----------|--------|---------|
|
||||||
|
| 1 | runtimes/python3.11/server.py | ✅ | HTTP wrapper :8080, loads /app/function/handler.py |
|
||||||
|
| 2 | runtimes/python3.11/Dockerfile | ✅ | FROM python:3.11-slim, naeel/sless-runtime-python3.11:latest |
|
||||||
|
| 3 | Secret sless-registry-auth | ✅ | DockerHub creds для kaniko в namespace sless |
|
||||||
|
| 4 | internal/api/handler/upload.go | ✅ | POST /v1/namespaces/{ns}/functions/{name}/upload |
|
||||||
|
| 5 | Fix: kaniko S3 endpoint | ✅ | https:// + S3_FORCE_PATH_STYLE=true (Ceph) |
|
||||||
|
| 6 | Fix: бесконечный цикл сборки | ✅ | idempotency guard через аннотацию last-built-s3key |
|
||||||
|
|
||||||
|
### E2E тест (2026-03-07)
|
||||||
|
|
||||||
|
| # | Шаг | Результат |
|
||||||
|
|---|-----|-----------|
|
||||||
|
| 1 | Запуск оператора локально | ✅ `source hack/local.env && go run main.go` |
|
||||||
|
| 2 | Создание функции hello + upload handler.zip | ✅ kaniko собрал naeel/sless-default-hello:latest |
|
||||||
|
| 3 | Function phase=Ready, Deployment Running | ✅ namespace sless-fn-default |
|
||||||
|
| 4 | `GET /health` | ✅ `{"status": "ok"}` |
|
||||||
|
| 5 | `POST / {"name":"Naeel"}` | ✅ `{"message": "Hello, Naeel!"}` |
|
||||||
|
|
||||||
|
### Terraform провайдер (2026-03-07)
|
||||||
|
|
||||||
|
| # | Компонент | Статус | Заметки |
|
||||||
|
|---|-----------|--------|---------|
|
||||||
|
| 1 | terraform/provider/ — независимый Go-модуль | ✅ | module: terraform-provider-sless |
|
||||||
|
| 2 | internal/client/client.go | ✅ | HTTP-клиент sless API, готов к переносу в nubes |
|
||||||
|
| 3 | internal/provider/provider.go | ✅ | паттерн идентичен nubes NubesProvider |
|
||||||
|
| 4 | sless_function resource | ✅ | CRUD + upload zip + WaitReady (kaniko) |
|
||||||
|
| 5 | sless_trigger resource | ✅ | CRUD (http/cron) |
|
||||||
|
| 6 | hack/build-and-publish.sh | ✅ | GPG-подпись + mc upload в S3 |
|
||||||
|
| 7 | Публикация в terra.k8c.ru | ✅ | v0.1.0, key CB3A0DF161ECC416 |
|
||||||
|
| 8 | terraform init | ✅ | Installed terra.k8c.ru/naeel/sless v0.1.0 |
|
||||||
|
|
||||||
|
**Примечание:** Код провайдера писался с прицелом на перенос в nubes провайдер.
|
||||||
|
`internal/client/` → `internal/core/` nubes, ресурсы → `internal/resources_gen/`.
|
||||||
|
|
||||||
### Что ещё не сделано
|
### Что ещё не сделано
|
||||||
|
|
||||||
| # | Компонент | Статус | Заметки |
|
| # | Компонент | Статус | Заметки |
|
||||||
|---|-----------|--------|---------|
|
|---|-----------|--------|---------|
|
||||||
| 1 | Запуск оператора локально | ⏳ | source hack/local.env && go run main.go |
|
| 1 | terraform apply e2e — функция с postgres | ⏳ | функция делает SELECT к postgres.sless.svc |
|
||||||
| 2 | Проверка подключения к Ceph S3 из кластера | ⏳ | endpoint: s3.msk-1.ngcloud.ru |
|
| 2 | HTTP trigger e2e тест | ⏳ | Service+Ingress через TriggerController |
|
||||||
| 3 | Endpoint загрузки кода функции (upload zip) | ⏳ | POST /v1/…/upload |
|
| 3 | deployments/k8s/operator.yaml | ⏳ | Deployment оператора в кластере |
|
||||||
| 4 | deployments/k8s/operator.yaml | ⏳ | Deployment оператора в кластере |
|
| 4 | Перенос ресурсов sless в nubes провайдер | ⏳ | после e2e тестирования |
|
||||||
| 5 | hack/test.sh — curl smoke-тесты | ⏳ | |
|
|
||||||
| 6 | Terraform provider — ресурс serverless_function | ⏳ | отдельная репа |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// 2026-03-07
|
||||||
|
// Модуль Terraform провайдера для sless (serverless functions operator).
|
||||||
|
// Независимый модуль: не импортирует ничего из sless оператора.
|
||||||
|
// После тестирования — клиент и ресурсы переносятся в nubes провайдер.
|
||||||
|
module terraform-provider-sless
|
||||||
|
|
||||||
|
go 1.22
|
||||||
|
|
||||||
|
require github.com/hashicorp/terraform-plugin-framework v1.8.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/fatih/color v1.13.0 // indirect
|
||||||
|
github.com/golang/protobuf v1.5.4 // indirect
|
||||||
|
github.com/hashicorp/go-hclog v1.5.0 // indirect
|
||||||
|
github.com/hashicorp/go-plugin v1.6.0 // indirect
|
||||||
|
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||||
|
github.com/hashicorp/terraform-plugin-go v0.22.2 // indirect
|
||||||
|
github.com/hashicorp/terraform-plugin-log v0.9.0 // indirect
|
||||||
|
github.com/hashicorp/terraform-registry-address v0.2.3 // indirect
|
||||||
|
github.com/hashicorp/terraform-svchost v0.1.1 // indirect
|
||||||
|
github.com/hashicorp/yamux v0.1.1 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.12 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.14 // indirect
|
||||||
|
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
|
||||||
|
github.com/oklog/run v1.0.0 // indirect
|
||||||
|
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
|
||||||
|
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
|
||||||
|
golang.org/x/net v0.21.0 // indirect
|
||||||
|
golang.org/x/sys v0.17.0 // indirect
|
||||||
|
golang.org/x/text v0.14.0 // indirect
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de // indirect
|
||||||
|
google.golang.org/grpc v1.63.2 // indirect
|
||||||
|
google.golang.org/protobuf v1.33.0 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
github.com/bufbuild/protocompile v0.4.0 h1:LbFKd2XowZvQ/kajzguUp2DC9UEIQhIq77fZZlaQsNA=
|
||||||
|
github.com/bufbuild/protocompile v0.4.0/go.mod h1:3v93+mbWn/v3xzN+31nwkJfrEpAUwp+BagBSZWx+TP8=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w=
|
||||||
|
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
|
||||||
|
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||||
|
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||||
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
|
github.com/hashicorp/go-hclog v1.5.0 h1:bI2ocEMgcVlz55Oj1xZNBsVi900c7II+fWDyV9o+13c=
|
||||||
|
github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
|
||||||
|
github.com/hashicorp/go-plugin v1.6.0 h1:wgd4KxHJTVGGqWBq4QPB1i5BZNEx9BR8+OFmHDmTk8A=
|
||||||
|
github.com/hashicorp/go-plugin v1.6.0/go.mod h1:lBS5MtSSBZk0SHc66KACcjjlU6WzEVP/8pwz68aMkCI=
|
||||||
|
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
|
||||||
|
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||||
|
github.com/hashicorp/terraform-plugin-framework v1.8.0 h1:P07qy8RKLcoBkCrY2RHJer5AEvJnDuXomBgou6fD8kI=
|
||||||
|
github.com/hashicorp/terraform-plugin-framework v1.8.0/go.mod h1:/CpTukO88PcL/62noU7cuyaSJ4Rsim+A/pa+3rUVufY=
|
||||||
|
github.com/hashicorp/terraform-plugin-go v0.22.2 h1:5o8uveu6eZUf5J7xGPV0eY0TPXg3qpmwX9sce03Bxnc=
|
||||||
|
github.com/hashicorp/terraform-plugin-go v0.22.2/go.mod h1:drq8Snexp9HsbFZddvyLHN6LuWHHndSQg+gV+FPkcIM=
|
||||||
|
github.com/hashicorp/terraform-plugin-log v0.9.0 h1:i7hOA+vdAItN1/7UrfBqBwvYPQ9TFvymaRGZED3FCV0=
|
||||||
|
github.com/hashicorp/terraform-plugin-log v0.9.0/go.mod h1:rKL8egZQ/eXSyDqzLUuwUYLVdlYeamldAHSxjUFADow=
|
||||||
|
github.com/hashicorp/terraform-registry-address v0.2.3 h1:2TAiKJ1A3MAkZlH1YI/aTVcLZRu7JseiXNRHbOAyoTI=
|
||||||
|
github.com/hashicorp/terraform-registry-address v0.2.3/go.mod h1:lFHA76T8jfQteVfT7caREqguFrW3c4MFSPhZB7HHgUM=
|
||||||
|
github.com/hashicorp/terraform-svchost v0.1.1 h1:EZZimZ1GxdqFRinZ1tpJwVxxt49xc/S52uzrw4x0jKQ=
|
||||||
|
github.com/hashicorp/terraform-svchost v0.1.1/go.mod h1:mNsjQfZyf/Jhz35v6/0LWcv26+X7JPS+buii2c9/ctc=
|
||||||
|
github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE=
|
||||||
|
github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ=
|
||||||
|
github.com/jhump/protoreflect v1.15.1 h1:HUMERORf3I3ZdX05WaQ6MIpd/NJ434hTp5YiKgfCL6c=
|
||||||
|
github.com/jhump/protoreflect v1.15.1/go.mod h1:jD/2GMKKE6OqX8qTjhADU1e6DShO+gavG9e0Q693nKo=
|
||||||
|
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||||
|
github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40=
|
||||||
|
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
|
||||||
|
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||||
|
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
|
||||||
|
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||||
|
github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU=
|
||||||
|
github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8=
|
||||||
|
github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw=
|
||||||
|
github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s=
|
||||||
|
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
|
||||||
|
github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=
|
||||||
|
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
|
||||||
|
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
|
||||||
|
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
|
||||||
|
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
|
||||||
|
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||||
|
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
|
||||||
|
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||||
|
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de h1:cZGRis4/ot9uVm639a+rHCUaG0JJHEsdyzSQTMX+suY=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:H4O17MA/PE9BsGx3w+a+W2VOLLD1Qf7oJneAoU6WktY=
|
||||||
|
google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM=
|
||||||
|
google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA=
|
||||||
|
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
|
||||||
|
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
Executable
+130
@@ -0,0 +1,130 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 2026-03-07
|
||||||
|
# build-and-publish.sh — сборка terraform-provider-sless и загрузка в S3.
|
||||||
|
# Аналог /home/naeel/remote_dev/terraform/registry-server-build/build-provider.sh
|
||||||
|
# но для провайдера sless (namespace=naeel, provider=sless).
|
||||||
|
#
|
||||||
|
# Использование:
|
||||||
|
# ./hack/build-and-publish.sh [VERSION]
|
||||||
|
# VERSION по умолчанию — из переменной окружения PROVIDER_VERSION или 0.1.0
|
||||||
|
#
|
||||||
|
# Требуемые env (или задать через .s3cfg_path):
|
||||||
|
# S3_ENDPOINT — например https://s3.msk-1.ngcloud.ru
|
||||||
|
# S3_ACCESS_KEY
|
||||||
|
# S3_SECRET_KEY
|
||||||
|
# GPG_KEY_FILE — путь к private_key.asc (default: ../../../terraform/secrets/private_key.asc)
|
||||||
|
#
|
||||||
|
# S3 путь: registry/terraform-registry/terra.k8c.ru/naeel/sless/{VERSION}/
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
PROVIDER_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||||
|
BUILD_DIR="${PROVIDER_DIR}/build"
|
||||||
|
|
||||||
|
REGISTRY_HOSTNAME="terra.k8c.ru"
|
||||||
|
NAMESPACE="naeel"
|
||||||
|
PROVIDER_NAME="sless"
|
||||||
|
S3_BUCKET="terraform-registry"
|
||||||
|
|
||||||
|
VERSION="${1:-${PROVIDER_VERSION:-0.1.0}}"
|
||||||
|
|
||||||
|
# GPG ключ — используем тот же что и для nubes провайдера
|
||||||
|
GPG_KEY_FILE="${GPG_KEY_FILE:-${PROVIDER_DIR}/../../../terraform/secrets/private_key.asc}"
|
||||||
|
|
||||||
|
# S3 credentials
|
||||||
|
S3_ENDPOINT="${S3_ENDPOINT:-}"
|
||||||
|
S3_ACCESS_KEY="${S3_ACCESS_KEY:-}"
|
||||||
|
S3_SECRET_KEY="${S3_SECRET_KEY:-}"
|
||||||
|
|
||||||
|
# Если S3 credentials не заданы — пробуем прочитать из .s3cfg_registry nubes проекта
|
||||||
|
S3CFG="${S3CFG:-${PROVIDER_DIR}/../../../terraform/secrets/.s3cfg_registry}"
|
||||||
|
if [[ -z "$S3_ENDPOINT" || -z "$S3_ACCESS_KEY" || -z "$S3_SECRET_KEY" ]]; then
|
||||||
|
if [[ -f "$S3CFG" ]]; then
|
||||||
|
echo "Загружаем S3 credentials из $S3CFG"
|
||||||
|
access_key=$(awk -F'=' '/^\s*access_key\s*=/{gsub(/^[ \t]+|[ \t]+$/,"",$2); print $2; exit}' "$S3CFG")
|
||||||
|
secret_key=$(awk -F'=' '/^\s*secret_key\s*=/{gsub(/^[ \t]+|[ \t]+$/,"",$2); print $2; exit}' "$S3CFG")
|
||||||
|
host_base=$(awk -F'=' '/^\s*host_base\s*=/{gsub(/^[ \t]+|[ \t]+$/,"",$2); print $2; exit}' "$S3CFG")
|
||||||
|
use_https=$(awk -F'=' '/^\s*use_https\s*=/{gsub(/^[ \t]+|[ \t]+$/,"",$2); print tolower($2); exit}' "$S3CFG")
|
||||||
|
|
||||||
|
[[ -z "${S3_ACCESS_KEY:-}" && -n "$access_key" ]] && export S3_ACCESS_KEY="$access_key"
|
||||||
|
[[ -z "${S3_SECRET_KEY:-}" && -n "$secret_key" ]] && export S3_SECRET_KEY="$secret_key"
|
||||||
|
if [[ -z "${S3_ENDPOINT:-}" && -n "$host_base" ]]; then
|
||||||
|
if [[ "$host_base" == http* ]]; then
|
||||||
|
export S3_ENDPOINT="$host_base"
|
||||||
|
elif [[ "$use_https" == "false" || "$use_https" == "no" ]]; then
|
||||||
|
export S3_ENDPOINT="http://${host_base}"
|
||||||
|
else
|
||||||
|
export S3_ENDPOINT="https://${host_base}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "${S3_ENDPOINT:-}" || -z "${S3_ACCESS_KEY:-}" || -z "${S3_SECRET_KEY:-}" ]]; then
|
||||||
|
echo "Error: требуются S3_ENDPOINT / S3_ACCESS_KEY / S3_SECRET_KEY" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ! -f "$GPG_KEY_FILE" ]]; then
|
||||||
|
echo "Error: GPG ключ не найден: $GPG_KEY_FILE" >&2
|
||||||
|
echo "Задайте GPG_KEY_FILE= или скопируйте private_key.asc из terraform/secrets/" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Добавить https:// если нет схемы
|
||||||
|
s3_url="$S3_ENDPOINT"
|
||||||
|
[[ "$s3_url" != http* ]] && s3_url="https://${s3_url}"
|
||||||
|
|
||||||
|
echo "=== Сборка terraform-provider-sless v${VERSION} ==="
|
||||||
|
|
||||||
|
rm -rf "$BUILD_DIR"
|
||||||
|
mkdir -p "$BUILD_DIR"
|
||||||
|
|
||||||
|
build_and_zip() {
|
||||||
|
local os="$1"
|
||||||
|
local arch="$2"
|
||||||
|
local binary="terraform-provider-sless_v${VERSION}"
|
||||||
|
local zip_name="terraform-provider-sless_${VERSION}_${os}_${arch}.zip"
|
||||||
|
|
||||||
|
[[ "$os" == "windows" ]] && binary="${binary}.exe"
|
||||||
|
|
||||||
|
echo " Building ${os}/${arch}..."
|
||||||
|
(cd "$PROVIDER_DIR" && CGO_ENABLED=0 GOOS="$os" GOARCH="$arch" go build -ldflags "-X main.version=${VERSION}" -o "${BUILD_DIR}/${binary}" .)
|
||||||
|
(cd "$BUILD_DIR" && python3 -m zipfile -c "$zip_name" "$binary")
|
||||||
|
rm -f "${BUILD_DIR:?}/${binary}"
|
||||||
|
}
|
||||||
|
|
||||||
|
build_and_zip linux amd64
|
||||||
|
build_and_zip darwin amd64
|
||||||
|
|
||||||
|
echo " Вычисляем SHA256SUMS..."
|
||||||
|
(cd "$BUILD_DIR" && sha256sum *.zip > "terraform-provider-sless_${VERSION}_SHA256SUMS")
|
||||||
|
|
||||||
|
echo " Подписываем GPG..."
|
||||||
|
GNUPGHOME="$(mktemp -d)"
|
||||||
|
export GNUPGHOME
|
||||||
|
trap 'rm -rf "$GNUPGHOME"' EXIT
|
||||||
|
|
||||||
|
gpg --batch --import "$GPG_KEY_FILE" >/dev/null 2>&1
|
||||||
|
key_id=$(gpg --list-keys --with-colons | awk -F: '/^pub/{print $5; exit}')
|
||||||
|
if [[ -z "$key_id" ]]; then
|
||||||
|
echo "Error: не удалось прочитать ключ из $GPG_KEY_FILE" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
gpg --batch --yes --detach-sign --default-key "$key_id" \
|
||||||
|
--output "${BUILD_DIR}/terraform-provider-sless_${VERSION}_SHA256SUMS.sig" \
|
||||||
|
"${BUILD_DIR}/terraform-provider-sless_${VERSION}_SHA256SUMS"
|
||||||
|
|
||||||
|
echo " Загружаем в S3..."
|
||||||
|
# Алиас mc включается в путь: <alias>/<bucket>/<path>
|
||||||
|
mc alias set sless-registry "$s3_url" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 >/dev/null
|
||||||
|
S3_PATH="sless-registry/${S3_BUCKET}/${REGISTRY_HOSTNAME}/${NAMESPACE}/${PROVIDER_NAME}/${VERSION}/"
|
||||||
|
|
||||||
|
mc cp "${BUILD_DIR}"/*.zip "${S3_PATH}"
|
||||||
|
mc cp "${BUILD_DIR}/terraform-provider-sless_${VERSION}_SHA256SUMS" "${S3_PATH}"
|
||||||
|
mc cp "${BUILD_DIR}/terraform-provider-sless_${VERSION}_SHA256SUMS.sig" "${S3_PATH}"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "=== Готово! Версия ${VERSION} опубликована ==="
|
||||||
|
echo " Проверить: curl -sk https://terra.k8c.ru/v1/providers/naeel/sless/versions"
|
||||||
@@ -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),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
// 2026-03-07
|
||||||
|
// main.go — точка входа Terraform провайдера sless.
|
||||||
|
// Address: terra.k8c.ru/naeel/sless — путь в реестре terra.k8c.ru.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"terraform-provider-sless/internal/provider"
|
||||||
|
|
||||||
|
"github.com/hashicorp/terraform-plugin-framework/providerserver"
|
||||||
|
)
|
||||||
|
|
||||||
|
// version задаётся ldflags при сборке: -ldflags "-X main.version=0.1.0"
|
||||||
|
var version string = "0.1.0"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
opts := providerserver.ServeOpts{
|
||||||
|
Address: "terra.k8c.ru/naeel/sless",
|
||||||
|
}
|
||||||
|
if err := providerserver.Serve(context.Background(), provider.New(version), opts); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user