Merge pull request 'initial implementation: terraform-provider-encapi' (#1) from benvin/initial-implementation into main
ci/woodpecker/tag/release Pipeline was successful

Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
2026-07-05 00:10:54 +10:00
27 changed files with 1525 additions and 1 deletions
+15
View File
@@ -0,0 +1,15 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/dnephin/pre-commit-golang
rev: v0.5.1
hooks:
- id: go-fmt
- id: go-vet
- id: go-mod-tidy
+18
View File
@@ -0,0 +1,18 @@
when:
- event: pull_request
steps:
- name: build
image: golang:1.25
commands:
- make build
backend_options:
kubernetes:
serviceAccountName: default
resources:
requests:
memory: 512Mi
cpu: 1
limits:
memory: 2Gi
cpu: 2
+18
View File
@@ -0,0 +1,18 @@
when:
- event: pull_request
steps:
- name: pre-commit
image: git.unkin.net/unkin/almalinux9-gobuilder:20260606
commands:
- uvx pre-commit run --all-files
backend_options:
kubernetes:
serviceAccountName: default
resources:
requests:
memory: 512Mi
cpu: 1
limits:
memory: 2Gi
cpu: 2
+40
View File
@@ -0,0 +1,40 @@
when:
- event: tag
steps:
- name: package
image: git.unkin.net/unkin/almalinux9-gobuilder:20260606
commands:
- make package VERSION=${CI_COMMIT_TAG}
backend_options:
kubernetes:
serviceAccountName: default
resources:
requests:
memory: 512Mi
cpu: 1
limits:
memory: 2Gi
cpu: 2
- name: upload
image: git.unkin.net/unkin/almalinux9-base:20260606
commands:
- |
VERSION=$$(echo ${CI_COMMIT_TAG} | sed 's/^v//')
FILE="terraform-provider-encapi_$${VERSION}_linux_amd64.zip"
curl -f -X PUT \
"https://artifactapi.k8s.syd1.au.unkin.net/api/v2/remotes/terraform-unkin/files/unkin/encapi/$${FILE}" \
-H "Content-Type: application/zip" \
--data-binary @"$${FILE}"
depends_on: [package]
backend_options:
kubernetes:
serviceAccountName: default
resources:
requests:
memory: 128Mi
cpu: 100m
limits:
memory: 512Mi
cpu: 500m
+33
View File
@@ -0,0 +1,33 @@
when:
- event: pull_request
steps:
- name: lint
image: golang:1.25
commands:
- make lint
backend_options:
kubernetes:
serviceAccountName: default
resources:
requests:
memory: 512Mi
cpu: 1
limits:
memory: 2Gi
cpu: 2
- name: test
image: golang:1.25
commands:
- make test
backend_options:
kubernetes:
serviceAccountName: default
resources:
requests:
memory: 512Mi
cpu: 1
limits:
memory: 2Gi
cpu: 2
+61
View File
@@ -0,0 +1,61 @@
.PHONY: build install test lint fmt clean tidy package patch minor major
BINARY := terraform-provider-encapi
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "0.0.0-dev")
OS_ARCH := linux_amd64
INSTALL_VERSION := $(shell echo $(VERSION) | sed 's/^v//')
INSTALL_DIR := ~/.terraform.d/plugins/git.unkin.net/unkin/encapi/$(INSTALL_VERSION)/$(OS_ARCH)
ZIP := $(BINARY)_$(INSTALL_VERSION)_$(OS_ARCH).zip
GO_VERSION_REQUIRED := 1.23
GO_VERSION_ACTUAL := $(shell go version | sed 's/go version go\([0-9]*\.[0-9]*\).*/\1/')
check-go:
@if [ "$$(printf '%s\n%s' "$(GO_VERSION_REQUIRED)" "$(GO_VERSION_ACTUAL)" | sort -V | head -1)" != "$(GO_VERSION_REQUIRED)" ]; then \
echo "ERROR: Go >= $(GO_VERSION_REQUIRED) required, found $(GO_VERSION_ACTUAL)"; exit 1; \
fi
build: check-go tidy
go build -ldflags="-s -w -X main.version=$(VERSION)" -o $(BINARY)
install: build
mkdir -p $(INSTALL_DIR)
cp $(BINARY) $(INSTALL_DIR)/
test: check-go
go test -race -count=1 ./...
lint: check-go
go vet ./...
fmt: check-go
gofmt -w .
package: build
cp $(BINARY) $(BINARY)_v$(INSTALL_VERSION)
python3 -c "import zipfile,sys; z=zipfile.ZipFile(sys.argv[1],'w',zipfile.ZIP_DEFLATED); z.write(sys.argv[2]); z.close()" $(ZIP) $(BINARY)_v$(INSTALL_VERSION)
rm $(BINARY)_v$(INSTALL_VERSION)
clean:
rm -f $(BINARY) *.zip
tidy:
go mod tidy
_LATEST := $(shell git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$$' | head -1)
_BASE := $(if $(_LATEST),$(_LATEST),v0.0.0)
_MAJ := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f1)
_MIN := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f2)
_PAT := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f3)
patch:
@NEW=v$(_MAJ).$(_MIN).$(shell expr $(_PAT) + 1); \
git tag $$NEW && echo "Tagged $$NEW" && git push origin $$NEW
minor:
@NEW=v$(_MAJ).$(shell expr $(_MIN) + 1).0; \
git tag $$NEW && echo "Tagged $$NEW" && git push origin $$NEW
major:
@NEW=v$(shell expr $(_MAJ) + 1).0.0; \
git tag $$NEW && echo "Tagged $$NEW" && git push origin $$NEW
+63 -1
View File
@@ -1,3 +1,65 @@
# terraform-provider-encapi
Terraform provider for encapi: manage Puppet ENC roles, statuses, and node assignments.
Terraform / OpenTofu provider for [encapi](https://git.unkin.net/unkin/encapi),
the Puppet External Node Classifier that replaces Cobbler.
It manages three resources and two data sources over the encapi HTTP API.
## Provider configuration
```hcl
terraform {
required_providers {
encapi = {
source = "git.unkin.net/unkin/encapi"
version = "0.0.1"
}
}
}
provider "encapi" {
endpoint = "https://encapi.k8s.syd1.au.unkin.net"
# token = "..." # defaults to $ENCAPI_WRITE_TOKEN
}
```
Reads are unauthenticated; writes require the token. Set it out-of-band via the
`ENCAPI_WRITE_TOKEN` environment variable (managed in Vault) rather than in HCL.
## Resources
| Resource | Purpose |
|------------------|----------------------------------------------------------------|
| `encapi_status` | A Puppet environment (Cobbler "status"): testing, production… |
| `encapi_role` | A class assignment target with inheritable `default_params`. |
| `encapi_node` | Assigns a host (certname) to a role + environment, with `params`. |
## Data sources
| Data source | Purpose |
|------------------|------------------------------------------|
| `encapi_node` | Look up a node's role/environment/params. |
| `encapi_role` | Look up a role and its default params. |
## Parameters
`default_params` (role) and `params` (node) are JSON-object strings. Use
`jsonencode({...})` so numbers, bools, lists, and nested objects keep their
types in the rendered ENC document:
```hcl
resource "encapi_role" "minio" {
name = "roles::infra::storage::minio"
default_params = jsonencode({ minio_pool = "pool1", replicas = 4, tls = true })
}
```
Node `params` override the role's `default_params` on key collisions.
## Releases
Tagging `vX.Y.Z` builds `terraform-provider-encapi_X.Y.Z_linux_amd64.zip` and
uploads it to the ArtifactAPI Terraform registry (`terraform-unkin` remote,
namespace `unkin/encapi`), which serves it as a GPG-signed provider registry.
See `examples/` for full usage.
+11
View File
@@ -0,0 +1,11 @@
data "encapi_node" "web0" {
certname = "ausyd1nxvm2000.main.unkin.net"
}
output "web0_role" {
value = data.encapi_node.web0.role
}
output "web0_environment" {
value = data.encapi_node.web0.environment
}
+82
View File
@@ -0,0 +1,82 @@
terraform {
required_providers {
encapi = {
source = "git.unkin.net/unkin/encapi"
version = "0.0.1"
}
}
}
provider "encapi" {
endpoint = "https://encapi.k8s.syd1.au.unkin.net"
# token defaults to the ENCAPI_WRITE_TOKEN environment variable
}
# ---------------------------------------------------------------------------
# Statuses (Puppet environments / Cobbler "status")
# ---------------------------------------------------------------------------
resource "encapi_status" "testing" {
name = "testing"
description = "Implicit environment; dropped from ENC output so agents use their default."
}
resource "encapi_status" "production" {
name = "production"
}
resource "encapi_status" "development" {
name = "development"
}
# ---------------------------------------------------------------------------
# Roles, with inheritable default params (use jsonencode to keep value types)
# ---------------------------------------------------------------------------
resource "encapi_role" "vault" {
name = "roles::infra::storage::vault"
description = "HashiCorp Vault cluster member"
}
resource "encapi_role" "minio" {
name = "roles::infra::storage::minio"
description = "MinIO object storage node"
default_params = jsonencode({
minio_pool = "pool1"
replicas = 4
})
}
# ---------------------------------------------------------------------------
# Node assignments
# ---------------------------------------------------------------------------
resource "encapi_node" "vault0" {
certname = "ausyd1nxvm2000.main.unkin.net"
role = encapi_role.vault.name
environment = encapi_status.testing.name
}
resource "encapi_node" "minio0" {
certname = "ausyd1nxvm2100.main.unkin.net"
role = encapi_role.minio.name
environment = encapi_status.production.name
# per-node override of the role default
params = jsonencode({
minio_pool = "pool2"
})
}
# ---------------------------------------------------------------------------
# Data sources
# ---------------------------------------------------------------------------
data "encapi_node" "vault0" {
certname = encapi_node.vault0.certname
}
output "vault0_role" {
value = data.encapi_node.vault0.role
}
+10
View File
@@ -0,0 +1,10 @@
resource "encapi_node" "example" {
certname = "ausyd1nxvm2000.main.unkin.net"
role = "roles::infra::storage::vault"
environment = "testing"
# Optional per-node overrides (win over the role's default_params).
params = jsonencode({
vault_role = "leader"
})
}
+12
View File
@@ -0,0 +1,12 @@
resource "encapi_role" "minio" {
name = "roles::infra::storage::minio"
description = "MinIO object storage node"
# Inheritable defaults, merged into every node with this role.
# Use jsonencode so numbers/bools keep their type in the ENC output.
default_params = jsonencode({
minio_pool = "pool1"
replicas = 4
tls = true
})
}
+14
View File
@@ -0,0 +1,14 @@
# Statuses map to Puppet environments. Define as many as your estate uses;
# a node can only be pinned to one that exists.
resource "encapi_status" "testing" {
name = "testing"
}
resource "encapi_status" "production" {
name = "production"
description = "Production environment"
}
resource "encapi_status" "development" {
name = "development"
}
+30
View File
@@ -0,0 +1,30 @@
module git.unkin.net/unkin/terraform-provider-encapi
go 1.25.9
require github.com/hashicorp/terraform-plugin-framework v1.15.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.3 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/hashicorp/terraform-plugin-go v0.27.0 // indirect
github.com/hashicorp/terraform-plugin-log v0.9.0 // indirect
github.com/hashicorp/terraform-registry-address v0.2.5 // 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.17 // 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.39.0 // indirect
golang.org/x/sys v0.32.0 // indirect
golang.org/x/text v0.24.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a // indirect
google.golang.org/grpc v1.72.1 // indirect
google.golang.org/protobuf v1.36.6 // indirect
)
+91
View File
@@ -0,0 +1,91 @@
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/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
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.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
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.3 h1:xgHB+ZUSYeuJi96WtxEjzi23uh7YQpznjGh0U0UUrwg=
github.com/hashicorp/go-plugin v1.6.3/go.mod h1:MRobyh+Wc/nYy1V4KAXUiYfzxoYhs7V1mlH1Z7iY2h0=
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.15.0 h1:LQ2rsOfmDLxcn5EeIwdXFtr03FVsNktbbBci8cOKdb4=
github.com/hashicorp/terraform-plugin-framework v1.15.0/go.mod h1:hxrNI/GY32KPISpWqlCoTLM9JZsGH3CyYlir09bD/fI=
github.com/hashicorp/terraform-plugin-go v0.27.0 h1:ujykws/fWIdsi6oTUT5Or4ukvEan4aN9lY+LOxVP8EE=
github.com/hashicorp/terraform-plugin-go v0.27.0/go.mod h1:FDa2Bb3uumkTGSkTFpWSOwWJDwA7bf3vdP3ltLDTH6o=
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.5 h1:2GTftHqmUhVOeuu9CW3kwDkRe4pcBDq0uuK5VJngU1M=
github.com/hashicorp/terraform-registry-address v0.2.5/go.mod h1:PpzXWINwB5kuVS5CA7m1+eO2f1jKb5ZDIxrOPfpnGkg=
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/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
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/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
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=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY=
go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI=
go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ=
go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE=
go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A=
go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU=
go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk=
go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w=
go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k=
go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE=
golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
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.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a h1:51aaUVRocpvUOSQKM6Q7VuoaktNIaMCLuhZB6DKksq4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a/go.mod h1:uRxBH1mhmO8PGhU89cMcHaXKZqO+OfakD8QQO0oYwlQ=
google.golang.org/grpc v1.72.1 h1:HR03wO6eyZ7lknl75XlxABNVLLFc2PAb6mHlYh756mA=
google.golang.org/grpc v1.72.1/go.mod h1:wH5Aktxcg25y1I3w7H69nHfXdOG3UiadoBtjh3izSDM=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
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=
+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)
}
+31
View File
@@ -0,0 +1,31 @@
// Command terraform-provider-encapi is the Terraform/OpenTofu provider for
// encapi: it manages Puppet ENC roles, statuses (environments), and per-node
// role assignments.
package main
import (
"context"
"flag"
"log"
"github.com/hashicorp/terraform-plugin-framework/providerserver"
"git.unkin.net/unkin/terraform-provider-encapi/internal/provider"
)
var version = "0.0.1"
func main() {
var debug bool
flag.BoolVar(&debug, "debug", false, "enable debug mode")
flag.Parse()
opts := providerserver.ServeOpts{
Address: "git.unkin.net/unkin/encapi",
Debug: debug,
}
if err := providerserver.Serve(context.Background(), provider.New(version), opts); err != nil {
log.Fatal(err)
}
}