initial implementation: terraform-provider-encapi

Terraform/OpenTofu provider for encapi (the Puppet ENC replacing Cobbler).
- resources: encapi_role (jsonencode default_params), encapi_status, encapi_node
- data sources: encapi_node, encapi_role
- client with bearer-token auth; unit tests; examples
- Makefile (package->zip), Woodpecker CI publishing to the artifactapi
  terraform-unkin registry on tag
This commit is contained in:
unkinben
2026-07-04 23:45:30 +10:00
parent 493ac92e32
commit 77049f4c3d
27 changed files with 1525 additions and 1 deletions
+91
View File
@@ -0,0 +1,91 @@
package provider
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
type apiClient struct {
baseURL string
token string
httpClient *http.Client
}
func newAPIClient(baseURL, token string) *apiClient {
return &apiClient{
baseURL: baseURL,
token: token,
httpClient: &http.Client{},
}
}
func (c *apiClient) get(ctx context.Context, path string, out any) error {
return c.do(ctx, http.MethodGet, path, nil, out)
}
func (c *apiClient) put(ctx context.Context, path string, body, out any) error {
return c.do(ctx, http.MethodPut, path, body, out)
}
func (c *apiClient) del(ctx context.Context, path string) error {
return c.do(ctx, http.MethodDelete, path, nil, nil)
}
func (c *apiClient) do(ctx context.Context, method, path string, body, out any) error {
var bodyReader io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal request: %w", err)
}
bodyReader = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, bodyReader)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("http request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return &notFoundError{path: path}
}
if resp.StatusCode >= 400 {
b, _ := io.ReadAll(resp.Body)
return fmt.Errorf("api error %d: %s", resp.StatusCode, string(b))
}
if out != nil && resp.StatusCode != http.StatusNoContent {
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
return fmt.Errorf("decode response: %w", err)
}
}
return nil
}
// pathEscape escapes a path segment (role/status names contain "::").
func pathEscape(s string) string { return url.PathEscape(s) }
type notFoundError struct{ path string }
func (e *notFoundError) Error() string { return fmt.Sprintf("not found: %s", e.path) }
func isNotFound(err error) bool {
_, ok := err.(*notFoundError)
return ok
}
+71
View File
@@ -0,0 +1,71 @@
package provider
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
func TestClientSendsBearerToken(t *testing.T) {
var gotAuth string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get("Authorization")
_, _ = w.Write([]byte(`{"name":"roles::base"}`))
}))
defer srv.Close()
c := newAPIClient(srv.URL, "tok")
var out roleAPI
if err := c.put(context.Background(), "/api/v1/roles/roles::base", roleAPI{Name: "roles::base"}, &out); err != nil {
t.Fatal(err)
}
if gotAuth != "Bearer tok" {
t.Errorf("auth = %q, want Bearer tok", gotAuth)
}
}
func TestClientNoTokenNoHeader(t *testing.T) {
var hadAuth bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, hadAuth = r.Header["Authorization"]
_, _ = w.Write([]byte(`{}`))
}))
defer srv.Close()
c := newAPIClient(srv.URL, "")
if err := c.get(context.Background(), "/api/v1/roles/x", &roleAPI{}); err != nil {
t.Fatal(err)
}
if hadAuth {
t.Error("no Authorization header expected when token empty")
}
}
func TestClientNotFound(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer srv.Close()
err := newAPIClient(srv.URL, "").get(context.Background(), "/api/v1/nodes/ghost", &nodeAPI{})
if !isNotFound(err) {
t.Errorf("err = %v, want notFound", err)
}
}
func TestClientAPIError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"role and environment are required"}`))
}))
defer srv.Close()
err := newAPIClient(srv.URL, "t").put(context.Background(), "/api/v1/nodes/h", nodeAPI{}, &nodeAPI{})
if err == nil {
t.Fatal("expected api error")
}
if isNotFound(err) {
t.Errorf("400 should not be a notFound error, got %v", err)
}
}
+65
View File
@@ -0,0 +1,65 @@
package provider
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var _ datasource.DataSource = &nodeDataSource{}
type nodeDataSource struct {
client *apiClient
}
func NewNodeDataSource() datasource.DataSource { return &nodeDataSource{} }
func (d *nodeDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_node"
}
func (d *nodeDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Looks up the role/environment/params assigned to a Puppet node.",
Attributes: map[string]schema.Attribute{
"certname": schema.StringAttribute{Required: true, Description: "Puppet certname (fqdn)."},
"role": schema.StringAttribute{Computed: true, Description: "Assigned role."},
"environment": schema.StringAttribute{Computed: true, Description: "Assigned environment/status."},
"params": schema.StringAttribute{Computed: true, Description: "Per-node params as JSON."},
},
}
}
func (d *nodeDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*apiClient)
if !ok {
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
return
}
d.client = client
}
func (d *nodeDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var cfg nodeResourceModel
resp.Diagnostics.Append(req.Config.Get(ctx, &cfg)...)
if resp.Diagnostics.HasError() {
return
}
var out nodeAPI
if err := d.client.get(ctx, "/api/v1/nodes/"+pathEscape(cfg.Certname.ValueString()), &out); err != nil {
resp.Diagnostics.AddError("read node failed", err.Error())
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, nodeResourceModel{
Certname: types.StringValue(out.Certname),
Role: types.StringValue(out.Role),
Environment: types.StringValue(out.Environment),
Params: paramsToJSON(out.Params),
})...)
}
+58
View File
@@ -0,0 +1,58 @@
package provider
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
)
var _ datasource.DataSource = &roleDataSource{}
type roleDataSource struct {
client *apiClient
}
func NewRoleDataSource() datasource.DataSource { return &roleDataSource{} }
func (d *roleDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_role"
}
func (d *roleDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Looks up a role and its inheritable default params.",
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{Required: true, Description: "Role/class name."},
"description": schema.StringAttribute{Computed: true, Description: "Description."},
"default_params": schema.StringAttribute{Computed: true, Description: "Default params as JSON."},
},
}
}
func (d *roleDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*apiClient)
if !ok {
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
return
}
d.client = client
}
func (d *roleDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var cfg roleResourceModel
resp.Diagnostics.Append(req.Config.Get(ctx, &cfg)...)
if resp.Diagnostics.HasError() {
return
}
var out roleAPI
if err := d.client.get(ctx, "/api/v1/roles/"+pathEscape(cfg.Name.ValueString()), &out); err != nil {
resp.Diagnostics.AddError("read role failed", err.Error())
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, roleAPIToModel(out))...)
}
+46
View File
@@ -0,0 +1,46 @@
package provider
import (
"encoding/json"
"github.com/hashicorp/terraform-plugin-framework/types"
)
// paramsToJSON renders an API params map to a canonical JSON string for
// Terraform state. Go's json.Marshal emits object keys in sorted order, which
// matches Terraform's jsonencode(), so a config written with jsonencode()
// round-trips without spurious diffs. An empty/nil map becomes a null string.
func paramsToJSON(m map[string]any) types.String {
if len(m) == 0 {
return types.StringNull()
}
b, err := json.Marshal(m)
if err != nil {
return types.StringNull()
}
return types.StringValue(string(b))
}
// jsonToParams parses a JSON-object string attribute into an API params map. A
// null/empty value yields nil. Invalid JSON yields an error the caller surfaces.
func jsonToParams(s types.String) (map[string]any, error) {
if s.IsNull() || s.IsUnknown() || s.ValueString() == "" {
return nil, nil
}
m := map[string]any{}
if err := json.Unmarshal([]byte(s.ValueString()), &m); err != nil {
return nil, err
}
return m, nil
}
// normalizeParamsJSON canonicalizes a user-supplied JSON string so plan and
// state compare equal regardless of key order or whitespace. Returns the input
// unchanged if it does not parse (validation happens elsewhere).
func normalizeParamsJSON(s types.String) types.String {
m, err := jsonToParams(s)
if err != nil {
return s
}
return paramsToJSON(m)
}
+61
View File
@@ -0,0 +1,61 @@
package provider
import (
"testing"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func TestParamsToJSONEmptyIsNull(t *testing.T) {
if v := paramsToJSON(nil); !v.IsNull() {
t.Errorf("nil map -> %v, want null", v)
}
if v := paramsToJSON(map[string]any{}); !v.IsNull() {
t.Errorf("empty map -> %v, want null", v)
}
}
func TestParamsToJSONSortedKeys(t *testing.T) {
// Go's json.Marshal sorts keys, matching Terraform's jsonencode().
v := paramsToJSON(map[string]any{"b": 2, "a": 1})
if v.ValueString() != `{"a":1,"b":2}` {
t.Errorf("got %q, want sorted compact JSON", v.ValueString())
}
}
func TestJSONToParamsRoundTrip(t *testing.T) {
in := types.StringValue(`{"epel":"9","replicas":3,"enabled":true}`)
m, err := jsonToParams(in)
if err != nil {
t.Fatal(err)
}
if m["epel"] != "9" || m["replicas"] != float64(3) || m["enabled"] != true {
t.Errorf("params = %#v", m)
}
}
func TestJSONToParamsNull(t *testing.T) {
m, err := jsonToParams(types.StringNull())
if err != nil || m != nil {
t.Errorf("got %v, %v; want nil, nil", m, err)
}
}
func TestJSONToParamsInvalid(t *testing.T) {
if _, err := jsonToParams(types.StringValue("not json")); err == nil {
t.Error("expected error for invalid JSON")
}
}
func TestNormalizeParamsJSON(t *testing.T) {
// reordered + whitespace should canonicalize to sorted compact form
got := normalizeParamsJSON(types.StringValue(`{ "b": 2, "a": 1 }`))
if got.ValueString() != `{"a":1,"b":2}` {
t.Errorf("normalize = %q", got.ValueString())
}
// invalid JSON returns input unchanged
bad := types.StringValue("{invalid")
if normalizeParamsJSON(bad).ValueString() != "{invalid" {
t.Error("invalid JSON should pass through unchanged")
}
}
+22
View File
@@ -0,0 +1,22 @@
package provider
// API wire types, mirroring git.unkin.net/unkin/encapi/pkg/models. They are
// duplicated here to keep the provider's dependency surface small.
type roleAPI struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
DefaultParams map[string]any `json:"default_params,omitempty"`
}
type statusAPI struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
}
type nodeAPI struct {
Certname string `json:"certname"`
Role string `json:"role"`
Environment string `json:"environment"`
Params map[string]any `json:"params,omitempty"`
}
+84
View File
@@ -0,0 +1,84 @@
package provider
import (
"context"
"os"
"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 = &encapiProvider{}
type encapiProvider struct {
version string
}
type encapiProviderModel struct {
Endpoint types.String `tfsdk:"endpoint"`
Token types.String `tfsdk:"token"`
}
// New returns the provider constructor.
func New(version string) func() provider.Provider {
return func() provider.Provider {
return &encapiProvider{version: version}
}
}
func (p *encapiProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "encapi"
resp.Version = p.version
}
func (p *encapiProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manage the Puppet External Node Classifier (encapi): roles, statuses (environments), and node role assignments.",
Attributes: map[string]schema.Attribute{
"endpoint": schema.StringAttribute{
Description: "The encapi server base URL (e.g. https://encapi.k8s.syd1.au.unkin.net).",
Required: true,
},
"token": schema.StringAttribute{
Description: "Write token (bearer) for mutating operations. Defaults to the ENCAPI_WRITE_TOKEN environment variable.",
Optional: true,
Sensitive: true,
},
},
}
}
func (p *encapiProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
var config encapiProviderModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
token := config.Token.ValueString()
if token == "" {
token = os.Getenv("ENCAPI_WRITE_TOKEN")
}
client := newAPIClient(config.Endpoint.ValueString(), token)
resp.DataSourceData = client
resp.ResourceData = client
}
func (p *encapiProvider) Resources(_ context.Context) []func() resource.Resource {
return []func() resource.Resource{
NewRoleResource,
NewStatusResource,
NewNodeResource,
}
}
func (p *encapiProvider) DataSources(_ context.Context) []func() datasource.DataSource {
return []func() datasource.DataSource{
NewNodeDataSource,
NewRoleDataSource,
}
}
+54
View File
@@ -0,0 +1,54 @@
package provider
import (
"context"
"testing"
"github.com/hashicorp/terraform-plugin-framework/provider"
"github.com/hashicorp/terraform-plugin-framework/resource"
)
func TestProviderSchema(t *testing.T) {
p := New("test")()
resp := &provider.SchemaResponse{}
p.Schema(context.Background(), provider.SchemaRequest{}, resp)
if resp.Diagnostics.HasError() {
t.Fatalf("schema diagnostics: %v", resp.Diagnostics)
}
if _, ok := resp.Schema.Attributes["endpoint"]; !ok {
t.Error("missing endpoint attribute")
}
if _, ok := resp.Schema.Attributes["token"]; !ok {
t.Error("missing token attribute")
}
}
func TestProviderMetadata(t *testing.T) {
p := New("1.2.3")()
resp := &provider.MetadataResponse{}
p.Metadata(context.Background(), provider.MetadataRequest{}, resp)
if resp.TypeName != "encapi" || resp.Version != "1.2.3" {
t.Errorf("metadata = %+v", resp)
}
}
func TestProviderRegistersResourcesAndDataSources(t *testing.T) {
p := New("test")()
if len(p.Resources(context.Background())) != 3 {
t.Error("expected 3 resources (role, status, node)")
}
if len(p.DataSources(context.Background())) != 2 {
t.Error("expected 2 data sources (node, role)")
}
}
// TestResourceSchemas validates each resource's schema compiles cleanly.
func TestResourceSchemas(t *testing.T) {
for _, ctor := range []func() resource.Resource{NewRoleResource, NewStatusResource, NewNodeResource} {
resp := &resource.SchemaResponse{}
ctor().Schema(context.Background(), resource.SchemaRequest{}, resp)
if resp.Diagnostics.HasError() {
t.Errorf("resource schema error: %v", resp.Diagnostics)
}
}
}
+157
View File
@@ -0,0 +1,157 @@
package provider
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/diag"
"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/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &nodeResource{}
_ resource.ResourceWithImportState = &nodeResource{}
)
type nodeResource struct {
client *apiClient
}
type nodeResourceModel struct {
Certname types.String `tfsdk:"certname"`
Role types.String `tfsdk:"role"`
Environment types.String `tfsdk:"environment"`
Params types.String `tfsdk:"params"`
}
func NewNodeResource() resource.Resource { return &nodeResource{} }
func (r *nodeResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_node"
}
func (r *nodeResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Assigns a Puppet node (by certname) to a role and environment, with optional per-node parameter overrides.",
Attributes: map[string]schema.Attribute{
"certname": schema.StringAttribute{
Description: "Puppet certname (fqdn) of the host.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"role": schema.StringAttribute{
Description: "Role/class to assign. Must reference an existing encapi_role.",
Required: true,
},
"environment": schema.StringAttribute{
Description: "Environment/status. Must reference an existing encapi_status.",
Required: true,
},
"params": schema.StringAttribute{
Description: "Per-node parameter overrides as a JSON object. Use jsonencode({...}) to preserve value types. These override the role's default_params.",
Optional: true,
},
},
}
}
func (r *nodeResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*apiClient)
if !ok {
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
return
}
r.client = client
}
func (r *nodeResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan nodeResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
r.upsert(ctx, plan, &resp.Diagnostics, &resp.State)
}
func (r *nodeResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan nodeResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
r.upsert(ctx, plan, &resp.Diagnostics, &resp.State)
}
func (r *nodeResource) upsert(ctx context.Context, plan nodeResourceModel, diags *diag.Diagnostics, state *tfsdk.State) {
params, err := jsonToParams(plan.Params)
if err != nil {
diags.AddError("invalid params", "params must be a JSON object: "+err.Error())
return
}
body := nodeAPI{
Certname: plan.Certname.ValueString(),
Role: plan.Role.ValueString(),
Environment: plan.Environment.ValueString(),
Params: params,
}
var out nodeAPI
if err := r.client.put(ctx, "/api/v1/nodes/"+pathEscape(body.Certname), body, &out); err != nil {
diags.AddError("upsert node failed", err.Error())
return
}
diags.Append(state.Set(ctx, nodeAPIToModel(out))...)
}
func (r *nodeResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state nodeResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var out nodeAPI
if err := r.client.get(ctx, "/api/v1/nodes/"+pathEscape(state.Certname.ValueString()), &out); err != nil {
if isNotFound(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("read node failed", err.Error())
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, nodeAPIToModel(out))...)
}
func (r *nodeResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state nodeResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.del(ctx, "/api/v1/nodes/"+pathEscape(state.Certname.ValueString())); err != nil {
resp.Diagnostics.AddError("delete node failed", err.Error())
return
}
}
func (r *nodeResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("certname"), req, resp)
}
func nodeAPIToModel(api nodeAPI) nodeResourceModel {
return nodeResourceModel{
Certname: types.StringValue(api.Certname),
Role: types.StringValue(api.Role),
Environment: types.StringValue(api.Environment),
Params: paramsToJSON(api.Params),
}
}
+150
View File
@@ -0,0 +1,150 @@
package provider
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/diag"
"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/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &roleResource{}
_ resource.ResourceWithImportState = &roleResource{}
)
type roleResource struct {
client *apiClient
}
type roleResourceModel struct {
Name types.String `tfsdk:"name"`
Description types.String `tfsdk:"description"`
DefaultParams types.String `tfsdk:"default_params"`
}
func NewRoleResource() resource.Resource { return &roleResource{} }
func (r *roleResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_role"
}
func (r *roleResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "A Puppet class assignment target (e.g. roles::infra::storage::vault) with inheritable default parameters.",
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Description: "Fully-qualified role/class name, e.g. roles::infra::storage::vault.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"description": schema.StringAttribute{
Description: "Human-readable description.",
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
},
"default_params": schema.StringAttribute{
Description: "Inheritable default parameters as a JSON object. Use jsonencode({...}) to preserve value types. Merged into every node carrying this role; node params win on collisions.",
Optional: true,
},
},
}
}
func (r *roleResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*apiClient)
if !ok {
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
return
}
r.client = client
}
func (r *roleResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan roleResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
r.upsert(ctx, plan, &resp.Diagnostics, &resp.State)
}
func (r *roleResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan roleResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
r.upsert(ctx, plan, &resp.Diagnostics, &resp.State)
}
// upsert PUTs the role and writes the returned state. Shared by Create/Update.
func (r *roleResource) upsert(ctx context.Context, plan roleResourceModel, diags *diag.Diagnostics, state *tfsdk.State) {
params, err := jsonToParams(plan.DefaultParams)
if err != nil {
diags.AddError("invalid default_params", "default_params must be a JSON object: "+err.Error())
return
}
body := roleAPI{Name: plan.Name.ValueString(), Description: plan.Description.ValueString(), DefaultParams: params}
var out roleAPI
if err := r.client.put(ctx, "/api/v1/roles/"+pathEscape(body.Name), body, &out); err != nil {
diags.AddError("upsert role failed", err.Error())
return
}
diags.Append(state.Set(ctx, roleAPIToModel(out))...)
}
func (r *roleResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state roleResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var out roleAPI
if err := r.client.get(ctx, "/api/v1/roles/"+pathEscape(state.Name.ValueString()), &out); err != nil {
if isNotFound(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("read role failed", err.Error())
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, roleAPIToModel(out))...)
}
func (r *roleResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state roleResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.del(ctx, "/api/v1/roles/"+pathEscape(state.Name.ValueString())); err != nil {
resp.Diagnostics.AddError("delete role failed", err.Error())
return
}
}
func (r *roleResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
}
func roleAPIToModel(api roleAPI) roleResourceModel {
return roleResourceModel{
Name: types.StringValue(api.Name),
Description: types.StringValue(api.Description),
DefaultParams: paramsToJSON(api.DefaultParams),
}
}
+137
View File
@@ -0,0 +1,137 @@
package provider
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/diag"
"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/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &statusResource{}
_ resource.ResourceWithImportState = &statusResource{}
)
type statusResource struct {
client *apiClient
}
type statusResourceModel struct {
Name types.String `tfsdk:"name"`
Description types.String `tfsdk:"description"`
}
func NewStatusResource() resource.Resource { return &statusResource{} }
func (r *statusResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_status"
}
func (r *statusResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "A Puppet environment (Cobbler \"status\", e.g. testing, production, development). Nodes may only reference a status that exists.",
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Description: "Status/environment name.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"description": schema.StringAttribute{
Description: "Human-readable description.",
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
},
},
}
}
func (r *statusResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*apiClient)
if !ok {
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
return
}
r.client = client
}
func (r *statusResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan statusResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
r.upsert(ctx, plan, &resp.Diagnostics, &resp.State)
}
func (r *statusResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan statusResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
r.upsert(ctx, plan, &resp.Diagnostics, &resp.State)
}
func (r *statusResource) upsert(ctx context.Context, plan statusResourceModel, diags *diag.Diagnostics, state *tfsdk.State) {
body := statusAPI{Name: plan.Name.ValueString(), Description: plan.Description.ValueString()}
var out statusAPI
if err := r.client.put(ctx, "/api/v1/statuses/"+pathEscape(body.Name), body, &out); err != nil {
diags.AddError("upsert status failed", err.Error())
return
}
diags.Append(state.Set(ctx, statusResourceModel{
Name: types.StringValue(out.Name),
Description: types.StringValue(out.Description),
})...)
}
func (r *statusResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state statusResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var out statusAPI
if err := r.client.get(ctx, "/api/v1/statuses/"+pathEscape(state.Name.ValueString()), &out); err != nil {
if isNotFound(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("read status failed", err.Error())
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, statusResourceModel{
Name: types.StringValue(out.Name),
Description: types.StringValue(out.Description),
})...)
}
func (r *statusResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state statusResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.del(ctx, "/api/v1/statuses/"+pathEscape(state.Name.ValueString())); err != nil {
resp.Diagnostics.AddError("delete status failed", err.Error())
return
}
}
func (r *statusResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
}