feat(provider): add fission_mq_trigger, fission_cron_trigger, fission_iot_device + weather-demo example
This commit is contained in:
@@ -0,0 +1,208 @@
|
||||
package resources
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"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"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
|
||||
"terraform-provider-fission/internal/client"
|
||||
)
|
||||
|
||||
var _ resource.Resource = &CronTriggerResource{}
|
||||
|
||||
// CronTriggerResource управляет Fission TimeTrigger (CRON).
|
||||
type CronTriggerResource struct {
|
||||
client *client.Client
|
||||
}
|
||||
|
||||
type cronTriggerResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Namespace types.String `tfsdk:"namespace"`
|
||||
Function types.String `tfsdk:"function"`
|
||||
Cron types.String `tfsdk:"cron"`
|
||||
UID types.String `tfsdk:"uid"`
|
||||
}
|
||||
|
||||
func NewCronTriggerResource() resource.Resource {
|
||||
return &CronTriggerResource{}
|
||||
}
|
||||
|
||||
func (r *CronTriggerResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_cron_trigger"
|
||||
}
|
||||
|
||||
func (r *CronTriggerResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Fission TimeTrigger — запускает функцию по CRON-расписанию.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "Идентификатор ресурса (namespace/name).",
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "Имя TimeTrigger.",
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"namespace": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Description: "Kubernetes namespace.",
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"function": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "Имя Fission Function для запуска.",
|
||||
},
|
||||
"cron": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "CRON-расписание, например \"*/10 * * * *\".",
|
||||
},
|
||||
"uid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "UID объекта в Kubernetes.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *CronTriggerResource) 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("Неверный тип провайдера", fmt.Sprintf("ожидался *client.Client, получен %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = c
|
||||
}
|
||||
|
||||
func (r *CronTriggerResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan cronTriggerResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ns := plan.Namespace.ValueString()
|
||||
if ns == "" {
|
||||
ns = r.client.Namespace
|
||||
}
|
||||
|
||||
obj := buildTimeTrigger(plan.Name.ValueString(), ns, plan.Function.ValueString(), plan.Cron.ValueString())
|
||||
created, err := r.client.CreateTimeTrigger(ctx, obj)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка создания CRON trigger", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
plan.ID = types.StringValue(ns + "/" + plan.Name.ValueString())
|
||||
plan.Namespace = types.StringValue(ns)
|
||||
plan.UID = types.StringValue(string(created.GetUID()))
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *CronTriggerResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state cronTriggerResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
obj, err := r.client.GetTimeTrigger(ctx, state.Namespace.ValueString(), state.Name.ValueString())
|
||||
if err != nil {
|
||||
if client.IsNotFound(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Ошибка чтения CRON trigger", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
spec, _, _ := unstructured.NestedMap(obj.Object, "spec")
|
||||
if cron, ok := spec["cron"].(string); ok {
|
||||
state.Cron = types.StringValue(cron)
|
||||
}
|
||||
if fnRef, ok := spec["functionref"].(map[string]any); ok {
|
||||
if name, ok := fnRef["name"].(string); ok {
|
||||
state.Function = types.StringValue(name)
|
||||
}
|
||||
}
|
||||
state.UID = types.StringValue(string(obj.GetUID()))
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *CronTriggerResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan cronTriggerResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
existing, err := r.client.GetTimeTrigger(ctx, plan.Namespace.ValueString(), plan.Name.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка получения CRON trigger для обновления", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := unstructured.SetNestedField(existing.Object, plan.Cron.ValueString(), "spec", "cron"); err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка обновления cron", err.Error())
|
||||
return
|
||||
}
|
||||
if err := unstructured.SetNestedField(existing.Object, plan.Function.ValueString(), "spec", "functionref", "name"); err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка обновления function", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
updated, err := r.client.UpdateTimeTrigger(ctx, existing)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка обновления CRON trigger", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
plan.UID = types.StringValue(string(updated.GetUID()))
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *CronTriggerResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state cronTriggerResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
if err := r.client.DeleteTimeTrigger(ctx, state.Namespace.ValueString(), state.Name.ValueString()); err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка удаления CRON trigger", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func buildTimeTrigger(name, ns, functionName, cron string) *unstructured.Unstructured {
|
||||
return &unstructured.Unstructured{
|
||||
Object: map[string]any{
|
||||
"apiVersion": "fission.io/v1",
|
||||
"kind": "TimeTrigger",
|
||||
"metadata": map[string]any{
|
||||
"name": name,
|
||||
"namespace": ns,
|
||||
},
|
||||
"spec": map[string]any{
|
||||
"cron": cron,
|
||||
"functionref": map[string]any{
|
||||
"type": "name",
|
||||
"name": functionName,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package resources
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/mapdefault"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
|
||||
"terraform-provider-fission/internal/client"
|
||||
)
|
||||
|
||||
var _ resource.Resource = &IoTDeviceResource{}
|
||||
|
||||
// IoTDeviceResource управляет CRD IoTDevice (iot.kube5s.ru/v1alpha1).
|
||||
type IoTDeviceResource struct {
|
||||
client *client.Client
|
||||
}
|
||||
|
||||
type iotDeviceResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Namespace types.String `tfsdk:"namespace"`
|
||||
DeviceID types.String `tfsdk:"device_id"`
|
||||
Enabled types.Bool `tfsdk:"enabled"`
|
||||
Metadata types.Map `tfsdk:"metadata"`
|
||||
Phase types.String `tfsdk:"phase"`
|
||||
MQTTUsername types.String `tfsdk:"mqtt_username"`
|
||||
SecretName types.String `tfsdk:"secret_name"`
|
||||
TopicPrefix types.String `tfsdk:"topic_prefix"`
|
||||
}
|
||||
|
||||
func NewIoTDeviceResource() resource.Resource {
|
||||
return &IoTDeviceResource{}
|
||||
}
|
||||
|
||||
func (r *IoTDeviceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_iot_device"
|
||||
}
|
||||
|
||||
func (r *IoTDeviceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "IoT-устройство, зарегистрированное в платформе sless (CRD iot.kube5s.ru/v1alpha1/IoTDevice).",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "Идентификатор ресурса (namespace/name).",
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "Имя IoTDevice.",
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"namespace": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: stringdefault.StaticString("sless"),
|
||||
Description: "Namespace IoTDevice. По умолчанию sless.",
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"device_id": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "Уникальный ID устройства внутри namespace (строчные буквы, цифры, дефис).",
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"enabled": schema.BoolAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: booldefault.StaticBool(true),
|
||||
Description: "Активно ли устройство.",
|
||||
},
|
||||
"metadata": schema.MapAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
Default: mapdefault.StaticValue(types.MapValueMust(types.StringType, map[string]attr.Value{})),
|
||||
Description: "Произвольные метаданные устройства (модель, локация и т.д.).",
|
||||
},
|
||||
// Computed (заполняет iot-operator)
|
||||
"phase": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "Текущая фаза: Active, Disabled, Pending, Error.",
|
||||
},
|
||||
"mqtt_username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "MQTT username, выданный iot-operator.",
|
||||
},
|
||||
"secret_name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "Имя K8s Secret с MQTT credentials.",
|
||||
},
|
||||
"topic_prefix": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "MQTT topic prefix для публикации.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *IoTDeviceResource) 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("Неверный тип провайдера", fmt.Sprintf("ожидался *client.Client, получен %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = c
|
||||
}
|
||||
|
||||
func (r *IoTDeviceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan iotDeviceResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ns := plan.Namespace.ValueString()
|
||||
meta := map[string]string{}
|
||||
if !plan.Metadata.IsNull() && !plan.Metadata.IsUnknown() {
|
||||
elems := plan.Metadata.Elements()
|
||||
for k, v := range elems {
|
||||
if sv, ok := v.(types.String); ok {
|
||||
meta[k] = sv.ValueString()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info, err := r.client.CreateIoTDevice(ctx, plan.Name.ValueString(), ns, plan.DeviceID.ValueString(), meta)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка создания IoT device", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
plan.ID = types.StringValue(ns + "/" + plan.Name.ValueString())
|
||||
plan.Phase = types.StringValue(info.Phase)
|
||||
plan.MQTTUsername = types.StringValue(info.MQTTUsername)
|
||||
plan.SecretName = types.StringValue(info.SecretName)
|
||||
plan.TopicPrefix = types.StringValue(info.TopicPrefix)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *IoTDeviceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state iotDeviceResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
info, err := r.client.GetIoTDevice(ctx, state.Namespace.ValueString(), state.Name.ValueString())
|
||||
if err != nil {
|
||||
if client.IsNotFound(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Ошибка чтения IoT device", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state.Phase = types.StringValue(info.Phase)
|
||||
state.MQTTUsername = types.StringValue(info.MQTTUsername)
|
||||
state.SecretName = types.StringValue(info.SecretName)
|
||||
state.TopicPrefix = types.StringValue(info.TopicPrefix)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *IoTDeviceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
// name/namespace/device_id — RequiresReplace, значит Update только для enabled/metadata.
|
||||
// Для простоты: пересоздаём объект.
|
||||
var plan iotDeviceResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ns := plan.Namespace.ValueString()
|
||||
name := plan.Name.ValueString()
|
||||
|
||||
if err := r.client.DeleteIoTDevice(ctx, ns, name); err != nil && !client.IsNotFound(err) {
|
||||
resp.Diagnostics.AddError("Ошибка удаления IoT device при обновлении", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
meta := map[string]string{}
|
||||
if !plan.Metadata.IsNull() && !plan.Metadata.IsUnknown() {
|
||||
elems := plan.Metadata.Elements()
|
||||
for k, v := range elems {
|
||||
if sv, ok := v.(types.String); ok {
|
||||
meta[k] = sv.ValueString()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info, err := r.client.CreateIoTDevice(ctx, name, ns, plan.DeviceID.ValueString(), meta)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка создания IoT device при обновлении", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
plan.Phase = types.StringValue(info.Phase)
|
||||
plan.MQTTUsername = types.StringValue(info.MQTTUsername)
|
||||
plan.SecretName = types.StringValue(info.SecretName)
|
||||
plan.TopicPrefix = types.StringValue(info.TopicPrefix)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *IoTDeviceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state iotDeviceResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
if err := r.client.DeleteIoTDevice(ctx, state.Namespace.ValueString(), state.Name.ValueString()); err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка удаления IoT device", err.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package resources
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"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/stringdefault"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
|
||||
"terraform-provider-fission/internal/client"
|
||||
)
|
||||
|
||||
var _ resource.Resource = &MQTriggerResource{}
|
||||
|
||||
// MQTriggerResource управляет MQ-триггером через K8s Deployment+Secret (sqs-consumer).
|
||||
type MQTriggerResource struct {
|
||||
client *client.Client
|
||||
}
|
||||
|
||||
type mqTriggerResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Namespace types.String `tfsdk:"namespace"`
|
||||
Function types.String `tfsdk:"function"`
|
||||
Queue types.String `tfsdk:"queue"`
|
||||
AccessKey types.String `tfsdk:"access_key"`
|
||||
SecretKey types.String `tfsdk:"secret_key"`
|
||||
SQSEndpoint types.String `tfsdk:"sqs_endpoint"`
|
||||
}
|
||||
|
||||
func NewMQTriggerResource() resource.Resource {
|
||||
return &MQTriggerResource{}
|
||||
}
|
||||
|
||||
func (r *MQTriggerResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_mq_trigger"
|
||||
}
|
||||
|
||||
func (r *MQTriggerResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "MQ-триггер через K8s Deployment (sqs-consumer) + Secret с SQS credentials.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "Идентификатор ресурса (namespace/name).",
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "Имя MQ trigger.",
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"namespace": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Description: "Kubernetes namespace.",
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"function": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "Имя Fission Function, к которой направляются сообщения из очереди.",
|
||||
},
|
||||
"queue": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "Имя SQS очереди.",
|
||||
},
|
||||
"access_key": schema.StringAttribute{
|
||||
Required: true,
|
||||
Sensitive: true,
|
||||
Description: "SQS Access Key.",
|
||||
},
|
||||
"secret_key": schema.StringAttribute{
|
||||
Required: true,
|
||||
Sensitive: true,
|
||||
Description: "SQS Secret Key.",
|
||||
},
|
||||
"sqs_endpoint": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: stringdefault.StaticString("http://shared-sqs.shared-sqs.svc.cluster.local:4100"),
|
||||
Description: "SQS endpoint URL. По умолчанию — внутренний shared-sqs.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *MQTriggerResource) 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("Неверный тип провайдера", fmt.Sprintf("ожидался *client.Client, получен %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = c
|
||||
}
|
||||
|
||||
func (r *MQTriggerResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan mqTriggerResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ns := plan.Namespace.ValueString()
|
||||
if ns == "" {
|
||||
ns = r.client.Namespace
|
||||
}
|
||||
|
||||
info, err := r.client.CreateMQTrigger(
|
||||
ctx,
|
||||
plan.Name.ValueString(),
|
||||
ns,
|
||||
plan.Function.ValueString(),
|
||||
plan.Queue.ValueString(),
|
||||
plan.SQSEndpoint.ValueString(),
|
||||
plan.AccessKey.ValueString(),
|
||||
plan.SecretKey.ValueString(),
|
||||
)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка создания MQ trigger", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
plan.ID = types.StringValue(ns + "/" + plan.Name.ValueString())
|
||||
plan.Namespace = types.StringValue(ns)
|
||||
plan.SQSEndpoint = types.StringValue(info.SQSEndpoint)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *MQTriggerResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state mqTriggerResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ns := state.Namespace.ValueString()
|
||||
info, err := r.client.GetMQTrigger(ctx, ns, state.Name.ValueString())
|
||||
if err != nil {
|
||||
if client.IsNotFound(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Ошибка чтения MQ trigger", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state.Function = types.StringValue(info.Function)
|
||||
state.Queue = types.StringValue(info.Queue)
|
||||
state.SQSEndpoint = types.StringValue(info.SQSEndpoint)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *MQTriggerResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan mqTriggerResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ns := plan.Namespace.ValueString()
|
||||
name := plan.Name.ValueString()
|
||||
|
||||
// Удаляем старый и создаём заново с новыми параметрами.
|
||||
if err := r.client.DeleteMQTrigger(ctx, ns, name); err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка удаления MQ trigger при обновлении", err.Error())
|
||||
return
|
||||
}
|
||||
info, err := r.client.CreateMQTrigger(
|
||||
ctx, name, ns,
|
||||
plan.Function.ValueString(),
|
||||
plan.Queue.ValueString(),
|
||||
plan.SQSEndpoint.ValueString(),
|
||||
plan.AccessKey.ValueString(),
|
||||
plan.SecretKey.ValueString(),
|
||||
)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка создания MQ trigger при обновлении", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
plan.SQSEndpoint = types.StringValue(info.SQSEndpoint)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *MQTriggerResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state mqTriggerResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.client.DeleteMQTrigger(ctx, state.Namespace.ValueString(), state.Name.ValueString()); err != nil {
|
||||
resp.Diagnostics.AddError("Ошибка удаления MQ trigger", err.Error())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user