feat: provider v0.1.9 — namespace hardcoded in client, removed from provider schema and all examples

This commit is contained in:
“Naeel”
2026-03-09 15:27:55 +04:00
parent 17d32fcb39
commit 5faec45a04
9 changed files with 23 additions and 41 deletions
+1
View File
@@ -100,6 +100,7 @@
| # | Компонент | Статус | Заметки | | # | Компонент | Статус | Заметки |
|---|-----------|--------|---------| |---|-----------|--------|---------|
| 1 | RabbitMQ event triggers | ⏳ | | | 1 | RabbitMQ event triggers | ⏳ | |
| 0 | Изоляция пользователей по namespace | ⏳ | Каждый токен → свой k8s namespace. API: GET /v1/whoami → {namespace}. Провайдер получает ns при Configure(), юзер не видит. Сейчас: хардкод "default" для демо. |
| 2 | Облачный auth (nubes.ru token validation) | ⏳ | v1 — статический токен | | 2 | Облачный auth (nubes.ru token validation) | ⏳ | v1 — статический токен |
| 3 | Метрики → Victoria Metrics | ⏳ | | | 3 | Метрики → Victoria Metrics | ⏳ | |
| 4 | Managed PostgreSQL от провайдера | ⏳ | сейчас postgres в k8s | | 4 | Managed PostgreSQL от провайдера | ⏳ | сейчас postgres в k8s |
+2 -3
View File
@@ -18,8 +18,7 @@ terraform {
} }
provider "sless" { provider "sless" {
endpoint = "https://sless-api.kube5s.ru" endpoint = "https://sless-api.kube5s.ru"
token = "dev-token-change-me" token = "dev-token-change-me"
namespace = "default"
} }
+2 -3
View File
@@ -27,7 +27,6 @@ terraform {
# sless провайдер подключается к API кластера. # sless провайдер подключается к API кластера.
# В продакшне token следует передавать через TF_VAR или secrets. # В продакшне token следует передавать через TF_VAR или secrets.
provider "sless" { provider "sless" {
endpoint = "https://sless-api.kube5s.ru" endpoint = "https://sless-api.kube5s.ru"
token = "dev-token-change-me" token = "dev-token-change-me"
namespace = "default"
} }
+2 -3
View File
@@ -16,7 +16,6 @@ terraform {
} }
provider "sless" { provider "sless" {
endpoint = "https://sless-api.kube5s.ru" endpoint = "https://sless-api.kube5s.ru"
token = "dev-token-change-me" token = "dev-token-change-me"
namespace = "default"
} }
+3 -5
View File
@@ -13,8 +13,7 @@
# напишите логику в джоб, а результат передайте через env_vars. # напишите логику в джоб, а результат передайте через env_vars.
# Например: получить токен, версию схемы БД, время деплоя и т.д. # Например: получить токен, версию схемы БД, время деплоя и т.д.
# #
# namespace задаётся один раз здесь, в блоке provider. # namespace захардкодирован внутри провайдера, здесь ничего указывать.
# В ресурсах (sless_function, sless_trigger, sless_job) namespace НЕ указывается.
terraform { terraform {
required_providers { required_providers {
@@ -30,7 +29,6 @@ terraform {
} }
provider "sless" { provider "sless" {
endpoint = "https://sless-api.kube5s.ru" endpoint = "https://sless-api.kube5s.ru"
token = "dev-token-change-me" token = "dev-token-change-me"
namespace = "default"
} }
+3 -5
View File
@@ -12,8 +12,7 @@
# напишите логику в джоб, а результат передайте через env_vars. # напишите логику в джоб, а результат передайте через env_vars.
# Например: получить токен, версию схемы БД, время деплоя и т.д. # Например: получить токен, версию схемы БД, время деплоя и т.д.
# #
# namespace задаётся один раз здесь, в блоке provider. # namespace захардкодирован внутри провайдера, здесь ничего указывать.
# В ресурсах (sless_function, sless_trigger, sless_job) namespace НЕ указывается.
terraform { terraform {
required_providers { required_providers {
@@ -29,7 +28,6 @@ terraform {
} }
provider "sless" { provider "sless" {
endpoint = "https://sless-api.kube5s.ru" endpoint = "https://sless-api.kube5s.ru"
token = "dev-token-change-me" token = "dev-token-change-me"
namespace = "default"
} }
+6 -3
View File
@@ -23,16 +23,19 @@ type Client struct {
httpClient *http.Client httpClient *http.Client
endpoint string endpoint string
token string token string
Namespace string // берётся из provider {}, пользователь не касается // Namespace захардкодено = "default".
// TODO: изоляция пользователей — каждый токен привязан к своему namespace,
// провайдер получает его через GET /v1/whoami. Сейчас всё в одном ns для демо.
Namespace string
} }
// New создаёт клиент. endpoint — базовый URL оператора (без trailing slash). // New создаёт клиент. endpoint — базовый URL оператора (без trailing slash).
func New(endpoint, token, namespace string) *Client { func New(endpoint, token string) *Client {
return &Client{ return &Client{
httpClient: &http.Client{Timeout: 30 * time.Second}, httpClient: &http.Client{Timeout: 30 * time.Second},
endpoint: endpoint, endpoint: endpoint,
token: token, token: token,
Namespace: namespace, Namespace: "default",
} }
} }
@@ -28,9 +28,8 @@ type SlessProvider struct {
// SlessProviderModel — конфигурация блока provider {} в .tf файле. // SlessProviderModel — конфигурация блока provider {} в .tf файле.
type SlessProviderModel struct { type SlessProviderModel struct {
Endpoint types.String `tfsdk:"endpoint"` Endpoint types.String `tfsdk:"endpoint"`
Token types.String `tfsdk:"token"` Token types.String `tfsdk:"token"`
Namespace types.String `tfsdk:"namespace"`
} }
// New возвращает фабрику провайдера — точная копия паттерна nubes. // New возвращает фабрику провайдера — точная копия паттерна nubes.
@@ -57,12 +56,6 @@ func (p *SlessProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp
Optional: true, Optional: true,
Sensitive: true, Sensitive: true,
}, },
// namespace — окружение/проект в кластере. Задаётся один раз здесь.
// В ресурсах (sless_function, sless_trigger, sless_job) namespace НЕ указывается.
"namespace": schema.StringAttribute{
MarkdownDescription: "Пространство имён (окружение). Задаётся один раз для всех ресурсов.",
Required: true,
},
}, },
} }
} }
@@ -94,9 +87,7 @@ func (p *SlessProvider) Configure(ctx context.Context, req provider.ConfigureReq
} }
} }
namespace := config.Namespace.ValueString() c := client.New(endpoint, token)
c := client.New(endpoint, token, namespace)
resp.ResourceData = c resp.ResourceData = c
resp.DataSourceData = c resp.DataSourceData = c
} }
@@ -25,7 +25,6 @@ import (
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator" "github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema" "github.com/hashicorp/terraform-plugin-framework/resource/schema"
@@ -323,12 +322,7 @@ func mapToStringMap(ctx context.Context, m types.Map) (map[string]string, diag.D
result := make(map[string]string, len(elements)) result := make(map[string]string, len(elements))
var diags diag.Diagnostics var diags diag.Diagnostics
for k, v := range elements { for k, v := range elements {
sv, ok := v.(attr.Value) strVal, ok := v.(types.String)
if !ok {
diags.AddError("env_vars conversion", fmt.Sprintf("unexpected type for key %q", k))
continue
}
strVal, ok := sv.(types.String)
if !ok { if !ok {
diags.AddError("env_vars conversion", fmt.Sprintf("value for key %q is not a string", k)) diags.AddError("env_vars conversion", fmt.Sprintf("value for key %q is not a string", k))
continue continue