From 9d204a7ba3ffa8373fab652b61eef6a91d935782 Mon Sep 17 00:00:00 2001 From: Graham McIntire Date: Wed, 11 Mar 2026 14:01:37 -0500 Subject: [PATCH] feat: add schedule and escalation policy resources Add towerops_schedule and towerops_escalation_policy Terraform resources with client CRUD methods, resource models, and provider registration. --- internal/provider/client.go | 124 +++++++++ .../provider/escalation_policy_resource.go | 250 ++++++++++++++++++ internal/provider/provider.go | 2 + internal/provider/schedule_resource.go | 225 ++++++++++++++++ 4 files changed, 601 insertions(+) create mode 100644 internal/provider/escalation_policy_resource.go create mode 100644 internal/provider/schedule_resource.go diff --git a/internal/provider/client.go b/internal/provider/client.go index 227f99e..c4a66ff 100644 --- a/internal/provider/client.go +++ b/internal/provider/client.go @@ -243,6 +243,130 @@ func (c *Client) DeleteDevice(id string) error { return err } +// OnCallSchedule represents a TowerOps on-call schedule. +type OnCallSchedule struct { + ID string `json:"id,omitempty"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` + Timezone string `json:"timezone"` + InsertedAt string `json:"inserted_at,omitempty"` +} + +// CreateSchedule creates a new on-call schedule. +func (c *Client) CreateSchedule(schedule OnCallSchedule) (*OnCallSchedule, error) { + body := map[string]OnCallSchedule{"schedule": schedule} + respBody, err := c.doRequest(http.MethodPost, "/api/v1/schedules", body) + if err != nil { + return nil, err + } + + var result OnCallSchedule + if err := json.Unmarshal(respBody, &result); err != nil { + return nil, fmt.Errorf("failed to unmarshal response: %w", err) + } + + return &result, nil +} + +// GetSchedule retrieves an on-call schedule by ID. +func (c *Client) GetSchedule(id string) (*OnCallSchedule, error) { + respBody, err := c.doRequest(http.MethodGet, "/api/v1/schedules/"+id, nil) + if err != nil { + return nil, err + } + + var result OnCallSchedule + if err := json.Unmarshal(respBody, &result); err != nil { + return nil, fmt.Errorf("failed to unmarshal response: %w", err) + } + + return &result, nil +} + +// UpdateSchedule updates an existing on-call schedule. +func (c *Client) UpdateSchedule(id string, schedule OnCallSchedule) (*OnCallSchedule, error) { + body := map[string]OnCallSchedule{"schedule": schedule} + respBody, err := c.doRequest(http.MethodPatch, "/api/v1/schedules/"+id, body) + if err != nil { + return nil, err + } + + var result OnCallSchedule + if err := json.Unmarshal(respBody, &result); err != nil { + return nil, fmt.Errorf("failed to unmarshal response: %w", err) + } + + return &result, nil +} + +// DeleteSchedule deletes an on-call schedule. +func (c *Client) DeleteSchedule(id string) error { + _, err := c.doRequest(http.MethodDelete, "/api/v1/schedules/"+id, nil) + return err +} + +// EscalationPolicyAPI represents a TowerOps escalation policy. +type EscalationPolicyAPI struct { + ID string `json:"id,omitempty"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` + RepeatCount *int `json:"repeat_count,omitempty"` + InsertedAt string `json:"inserted_at,omitempty"` +} + +// CreateEscalationPolicy creates a new escalation policy. +func (c *Client) CreateEscalationPolicy(policy EscalationPolicyAPI) (*EscalationPolicyAPI, error) { + body := map[string]EscalationPolicyAPI{"escalation_policy": policy} + respBody, err := c.doRequest(http.MethodPost, "/api/v1/escalation_policies", body) + if err != nil { + return nil, err + } + + var result EscalationPolicyAPI + if err := json.Unmarshal(respBody, &result); err != nil { + return nil, fmt.Errorf("failed to unmarshal response: %w", err) + } + + return &result, nil +} + +// GetEscalationPolicy retrieves an escalation policy by ID. +func (c *Client) GetEscalationPolicy(id string) (*EscalationPolicyAPI, error) { + respBody, err := c.doRequest(http.MethodGet, "/api/v1/escalation_policies/"+id, nil) + if err != nil { + return nil, err + } + + var result EscalationPolicyAPI + if err := json.Unmarshal(respBody, &result); err != nil { + return nil, fmt.Errorf("failed to unmarshal response: %w", err) + } + + return &result, nil +} + +// UpdateEscalationPolicy updates an existing escalation policy. +func (c *Client) UpdateEscalationPolicy(id string, policy EscalationPolicyAPI) (*EscalationPolicyAPI, error) { + body := map[string]EscalationPolicyAPI{"escalation_policy": policy} + respBody, err := c.doRequest(http.MethodPatch, "/api/v1/escalation_policies/"+id, body) + if err != nil { + return nil, err + } + + var result EscalationPolicyAPI + if err := json.Unmarshal(respBody, &result); err != nil { + return nil, fmt.Errorf("failed to unmarshal response: %w", err) + } + + return &result, nil +} + +// DeleteEscalationPolicy deletes an escalation policy. +func (c *Client) DeleteEscalationPolicy(id string) error { + _, err := c.doRequest(http.MethodDelete, "/api/v1/escalation_policies/"+id, nil) + return err +} + // GetOrganization retrieves the current organization settings. func (c *Client) GetOrganization() (*Organization, error) { respBody, err := c.doRequest(http.MethodGet, "/api/v1/organization", nil) diff --git a/internal/provider/escalation_policy_resource.go b/internal/provider/escalation_policy_resource.go new file mode 100644 index 0000000..cacb4da --- /dev/null +++ b/internal/provider/escalation_policy_resource.go @@ -0,0 +1,250 @@ +package provider + +import ( + "context" + "errors" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier" + "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 = &EscalationPolicyResource{} +var _ resource.ResourceWithImportState = &EscalationPolicyResource{} + +// EscalationPolicyResource defines the resource implementation. +type EscalationPolicyResource struct { + client *Client +} + +// EscalationPolicyResourceModel describes the resource data model. +type EscalationPolicyResourceModel struct { + ID types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + Description types.String `tfsdk:"description"` + RepeatCount types.Int64 `tfsdk:"repeat_count"` + InsertedAt types.String `tfsdk:"inserted_at"` +} + +// NewEscalationPolicyResource creates a new escalation policy resource. +func NewEscalationPolicyResource() resource.Resource { + return &EscalationPolicyResource{} +} + +func (r *EscalationPolicyResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_escalation_policy" +} + +func (r *EscalationPolicyResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + Description: "Manages a TowerOps escalation policy.", + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + Description: "The unique identifier of the escalation policy.", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "name": schema.StringAttribute{ + Description: "The name of the escalation policy.", + Required: true, + }, + "description": schema.StringAttribute{ + Description: "A description of the escalation policy.", + Optional: true, + }, + "repeat_count": schema.Int64Attribute{ + Description: "Number of times to repeat the escalation cycle. Defaults to 3.", + Optional: true, + Computed: true, + PlanModifiers: []planmodifier.Int64{ + int64planmodifier.UseStateForUnknown(), + }, + }, + "inserted_at": schema.StringAttribute{ + Description: "The timestamp when the escalation policy was created.", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + }, + } +} + +func (r *EscalationPolicyResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + client, ok := req.ProviderData.(*Client) + if !ok { + resp.Diagnostics.AddError( + "Unexpected Resource Configure Type", + fmt.Sprintf("Expected *Client, got: %T", req.ProviderData), + ) + return + } + + r.client = client +} + +func (r *EscalationPolicyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data EscalationPolicyResourceModel + + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + policy := EscalationPolicyAPI{ + Name: data.Name.ValueString(), + } + + if !data.Description.IsNull() { + desc := data.Description.ValueString() + policy.Description = &desc + } + + if !data.RepeatCount.IsNull() && !data.RepeatCount.IsUnknown() { + rc := int(data.RepeatCount.ValueInt64()) + policy.RepeatCount = &rc + } + + created, err := r.client.CreateEscalationPolicy(policy) + if err != nil { + resp.Diagnostics.AddError("Failed to create escalation policy", err.Error()) + return + } + + data.ID = types.StringValue(created.ID) + data.InsertedAt = types.StringValue(created.InsertedAt) + + if created.Description != nil { + data.Description = types.StringValue(*created.Description) + } + if created.RepeatCount != nil { + data.RepeatCount = types.Int64Value(int64(*created.RepeatCount)) + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *EscalationPolicyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var data EscalationPolicyResourceModel + + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + policy, err := r.client.GetEscalationPolicy(data.ID.ValueString()) + if err != nil { + if errors.Is(err, ErrNotFound) { + resp.State.RemoveResource(ctx) + return + } + resp.Diagnostics.AddError("Failed to read escalation policy", err.Error()) + return + } + + data.Name = types.StringValue(policy.Name) + data.InsertedAt = types.StringValue(policy.InsertedAt) + + if policy.Description != nil { + data.Description = types.StringValue(*policy.Description) + } else { + data.Description = types.StringNull() + } + + if policy.RepeatCount != nil { + data.RepeatCount = types.Int64Value(int64(*policy.RepeatCount)) + } else { + data.RepeatCount = types.Int64Null() + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *EscalationPolicyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var data EscalationPolicyResourceModel + + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + policy := EscalationPolicyAPI{ + Name: data.Name.ValueString(), + } + + if !data.Description.IsNull() { + desc := data.Description.ValueString() + policy.Description = &desc + } + + if !data.RepeatCount.IsNull() && !data.RepeatCount.IsUnknown() { + rc := int(data.RepeatCount.ValueInt64()) + policy.RepeatCount = &rc + } + + updated, err := r.client.UpdateEscalationPolicy(data.ID.ValueString(), policy) + if err != nil { + if errors.Is(err, ErrNotFound) { + created, createErr := r.client.CreateEscalationPolicy(policy) + if createErr != nil { + resp.Diagnostics.AddError("Failed to create escalation policy (after 404 on update)", createErr.Error()) + return + } + data.ID = types.StringValue(created.ID) + data.InsertedAt = types.StringValue(created.InsertedAt) + data.Name = types.StringValue(created.Name) + if created.Description != nil { + data.Description = types.StringValue(*created.Description) + } + if created.RepeatCount != nil { + data.RepeatCount = types.Int64Value(int64(*created.RepeatCount)) + } + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) + return + } + resp.Diagnostics.AddError("Failed to update escalation policy", err.Error()) + return + } + + data.Name = types.StringValue(updated.Name) + + if updated.Description != nil { + data.Description = types.StringValue(*updated.Description) + } + if updated.RepeatCount != nil { + data.RepeatCount = types.Int64Value(int64(*updated.RepeatCount)) + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *EscalationPolicyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var data EscalationPolicyResourceModel + + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + err := r.client.DeleteEscalationPolicy(data.ID.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Failed to delete escalation policy", err.Error()) + return + } +} + +func (r *EscalationPolicyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 6d42503..0b49772 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -89,6 +89,8 @@ func (p *ToweropsProvider) Resources(ctx context.Context) []func() resource.Reso NewOrganizationResource, NewSiteResource, NewDeviceResource, + NewScheduleResource, + NewEscalationPolicyResource, } } diff --git a/internal/provider/schedule_resource.go b/internal/provider/schedule_resource.go new file mode 100644 index 0000000..eb289e0 --- /dev/null +++ b/internal/provider/schedule_resource.go @@ -0,0 +1,225 @@ +package provider + +import ( + "context" + "errors" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/path" + "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" +) + +var _ resource.Resource = &ScheduleResource{} +var _ resource.ResourceWithImportState = &ScheduleResource{} + +// ScheduleResource defines the resource implementation. +type ScheduleResource struct { + client *Client +} + +// ScheduleResourceModel describes the resource data model. +type ScheduleResourceModel struct { + ID types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + Description types.String `tfsdk:"description"` + Timezone types.String `tfsdk:"timezone"` + InsertedAt types.String `tfsdk:"inserted_at"` +} + +// NewScheduleResource creates a new schedule resource. +func NewScheduleResource() resource.Resource { + return &ScheduleResource{} +} + +func (r *ScheduleResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_schedule" +} + +func (r *ScheduleResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + Description: "Manages a TowerOps on-call schedule.", + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + Description: "The unique identifier of the schedule.", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "name": schema.StringAttribute{ + Description: "The name of the on-call schedule.", + Required: true, + }, + "description": schema.StringAttribute{ + Description: "A description of the schedule.", + Optional: true, + }, + "timezone": schema.StringAttribute{ + Description: "The timezone for the schedule (e.g. America/Chicago).", + Required: true, + }, + "inserted_at": schema.StringAttribute{ + Description: "The timestamp when the schedule was created.", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + }, + } +} + +func (r *ScheduleResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + client, ok := req.ProviderData.(*Client) + if !ok { + resp.Diagnostics.AddError( + "Unexpected Resource Configure Type", + fmt.Sprintf("Expected *Client, got: %T", req.ProviderData), + ) + return + } + + r.client = client +} + +func (r *ScheduleResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data ScheduleResourceModel + + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + schedule := OnCallSchedule{ + Name: data.Name.ValueString(), + Timezone: data.Timezone.ValueString(), + } + + if !data.Description.IsNull() { + desc := data.Description.ValueString() + schedule.Description = &desc + } + + created, err := r.client.CreateSchedule(schedule) + if err != nil { + resp.Diagnostics.AddError("Failed to create schedule", err.Error()) + return + } + + data.ID = types.StringValue(created.ID) + data.InsertedAt = types.StringValue(created.InsertedAt) + + if created.Description != nil { + data.Description = types.StringValue(*created.Description) + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ScheduleResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var data ScheduleResourceModel + + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + schedule, err := r.client.GetSchedule(data.ID.ValueString()) + if err != nil { + if errors.Is(err, ErrNotFound) { + resp.State.RemoveResource(ctx) + return + } + resp.Diagnostics.AddError("Failed to read schedule", err.Error()) + return + } + + data.Name = types.StringValue(schedule.Name) + data.Timezone = types.StringValue(schedule.Timezone) + data.InsertedAt = types.StringValue(schedule.InsertedAt) + + if schedule.Description != nil { + data.Description = types.StringValue(*schedule.Description) + } else { + data.Description = types.StringNull() + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ScheduleResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var data ScheduleResourceModel + + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + schedule := OnCallSchedule{ + Name: data.Name.ValueString(), + Timezone: data.Timezone.ValueString(), + } + + if !data.Description.IsNull() { + desc := data.Description.ValueString() + schedule.Description = &desc + } + + updated, err := r.client.UpdateSchedule(data.ID.ValueString(), schedule) + if err != nil { + if errors.Is(err, ErrNotFound) { + created, createErr := r.client.CreateSchedule(schedule) + if createErr != nil { + resp.Diagnostics.AddError("Failed to create schedule (after 404 on update)", createErr.Error()) + return + } + data.ID = types.StringValue(created.ID) + data.InsertedAt = types.StringValue(created.InsertedAt) + data.Name = types.StringValue(created.Name) + data.Timezone = types.StringValue(created.Timezone) + if created.Description != nil { + data.Description = types.StringValue(*created.Description) + } + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) + return + } + resp.Diagnostics.AddError("Failed to update schedule", err.Error()) + return + } + + data.Name = types.StringValue(updated.Name) + data.Timezone = types.StringValue(updated.Timezone) + + if updated.Description != nil { + data.Description = types.StringValue(*updated.Description) + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ScheduleResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var data ScheduleResourceModel + + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + err := r.client.DeleteSchedule(data.ID.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Failed to delete schedule", err.Error()) + return + } +} + +func (r *ScheduleResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +}