Initial terraform-provider-ranchervaultsecret scaffold

Terraform provider (plugin-framework) for the vault-plugin-secrets-rancher
secrets engine, modeled on terraform-provider-litellmvaultsecret.

Resources:
- rancher_secret_backend: mount the engine + write config (rancher_url, ca_cert,
  tls_skip_verify, request_timeout_seconds).
- rancher_secret_backend_service_account: seed an auto-rotated Rancher token
  (write-only token; token_ttl / rotation_period; computed token_name,
  last_rotated).
- rancher_secret_backend_role: minting role (service_account, cluster_name,
  ttl, max_ttl, description).

Source address git.unkin.net/unkin/ranchervaultsecret, resources prefixed
rancher_. Ports the litellm Woodpecker terraform-registry release + nfpm-less
zip packaging, examples, and a provider e2e (Vault + mock Rancher from the
sibling plugin repo). Unit tests cover the coercion/import-ID helpers.
This commit is contained in:
Ben Vincent
2026-07-15 22:20:03 +10:00
commit c69b27826d
25 changed files with 1778 additions and 0 deletions
+134
View File
@@ -0,0 +1,134 @@
package provider
import (
"context"
"errors"
"fmt"
"strings"
vault "github.com/hashicorp/vault/api"
)
// vaultClient wraps the Vault/OpenBao API client with the operations this
// provider needs to manage the Rancher secrets engine.
type vaultClient struct {
api *vault.Client
}
func newVaultClient(address, token string) (*vaultClient, error) {
cfg := vault.DefaultConfig()
if cfg.Error != nil {
return nil, cfg.Error
}
if address != "" {
cfg.Address = address
}
c, err := vault.NewClient(cfg)
if err != nil {
return nil, err
}
if token != "" {
c.SetToken(token)
}
return &vaultClient{api: c}, nil
}
// mountConfig holds the tunable options applied when enabling the engine.
type mountConfig struct {
DefaultLeaseTTL string
MaxLeaseTTL string
}
// enableMount mounts the secrets engine of the given plugin type at path.
func (c *vaultClient) enableMount(ctx context.Context, path, pluginType, description string, cfg mountConfig) error {
input := &vault.MountInput{
Type: pluginType,
Description: description,
Config: vault.MountConfigInput{
DefaultLeaseTTL: cfg.DefaultLeaseTTL,
MaxLeaseTTL: cfg.MaxLeaseTTL,
},
}
return c.api.Sys().MountWithContext(ctx, path, input)
}
// tuneMount updates tunable options of an existing mount (e.g. description).
func (c *vaultClient) tuneMount(ctx context.Context, path, description string, cfg mountConfig) error {
input := vault.MountConfigInput{
Description: &description,
DefaultLeaseTTL: cfg.DefaultLeaseTTL,
MaxLeaseTTL: cfg.MaxLeaseTTL,
}
return c.api.Sys().TuneMountWithContext(ctx, path, input)
}
// mountInfo returns the mount at the given path, or nil if it does not exist.
func (c *vaultClient) mountInfo(ctx context.Context, path string) (*vault.MountOutput, error) {
mounts, err := c.api.Sys().ListMountsWithContext(ctx)
if err != nil {
return nil, err
}
key := strings.TrimRight(path, "/") + "/"
if m, ok := mounts[key]; ok {
return m, nil
}
return nil, nil
}
// disableMount unmounts the secrets engine at path.
func (c *vaultClient) disableMount(ctx context.Context, path string) error {
return c.api.Sys().UnmountWithContext(ctx, path)
}
// write writes data to an arbitrary path under the backend mount.
func (c *vaultClient) write(ctx context.Context, path string, data map[string]interface{}) error {
_, err := c.api.Logical().WriteWithContext(ctx, path, data)
return err
}
// read reads an arbitrary path under the backend mount, returning nil if absent.
func (c *vaultClient) read(ctx context.Context, path string) (map[string]interface{}, error) {
secret, err := c.api.Logical().ReadWithContext(ctx, path)
if err != nil {
return nil, err
}
if secret == nil {
return nil, nil
}
return secret.Data, nil
}
// delete removes an arbitrary path under the backend mount.
func (c *vaultClient) delete(ctx context.Context, path string) error {
_, err := c.api.Logical().DeleteWithContext(ctx, path)
return err
}
func configPath(backend string) string {
return fmt.Sprintf("%s/config", strings.TrimRight(backend, "/"))
}
func serviceAccountPath(backend, name string) string {
return fmt.Sprintf("%s/service-accounts/%s", strings.TrimRight(backend, "/"), name)
}
func rolePath(backend, name string) string {
return fmt.Sprintf("%s/roles/%s", strings.TrimRight(backend, "/"), name)
}
// isMountAlreadyExists reports whether the error is Vault's "path is already in
// use" response, so callers can surface a friendlier message.
func isMountAlreadyExists(err error) bool {
if err == nil {
return false
}
var respErr *vault.ResponseError
if errors.As(err, &respErr) {
for _, e := range respErr.Errors {
if strings.Contains(e, "path is already in use") {
return true
}
}
}
return false
}
+47
View File
@@ -0,0 +1,47 @@
package provider
import (
"encoding/json"
"strings"
)
// toInt64 coerces the numeric shapes Vault returns (json.Number, float64, int)
// into an int64.
func toInt64(v interface{}) (int64, bool) {
switch n := v.(type) {
case json.Number:
i, err := n.Int64()
if err != nil {
f, ferr := n.Float64()
if ferr != nil {
return 0, false
}
return int64(f), true
}
return i, true
case float64:
return int64(n), true
case int64:
return n, true
case int:
return int64(n), true
default:
return 0, false
}
}
// splitBackendName splits an import ID of the form "<backend>/<marker>/<name>"
// (e.g. "rancher/roles/ci") into its backend and name parts.
func splitBackendName(id, marker string) (backend, name string, ok bool) {
sep := "/" + marker + "/"
idx := strings.LastIndex(id, sep)
if idx <= 0 {
return "", "", false
}
backend = id[:idx]
name = id[idx+len(sep):]
if backend == "" || name == "" {
return "", "", false
}
return backend, name, true
}
+48
View File
@@ -0,0 +1,48 @@
package provider
import (
"encoding/json"
"testing"
)
func TestToInt64(t *testing.T) {
cases := []struct {
in interface{}
want int64
ok bool
}{
{json.Number("42"), 42, true},
{json.Number("3.0"), 3, true},
{float64(7), 7, true},
{int(9), 9, true},
{int64(11), 11, true},
{"nope", 0, false},
{nil, 0, false},
}
for _, c := range cases {
got, ok := toInt64(c.in)
if ok != c.ok || got != c.want {
t.Errorf("toInt64(%v) = (%d,%v), want (%d,%v)", c.in, got, ok, c.want, c.ok)
}
}
}
func TestSplitBackendName(t *testing.T) {
cases := []struct {
id, marker, backend, name string
ok bool
}{
{"rancher/roles/ci", "roles", "rancher", "ci", true},
{"team/rancher/service-accounts/admin", "service-accounts", "team/rancher", "admin", true},
{"rancher/roles/", "roles", "", "", false},
{"/roles/ci", "roles", "", "", false},
{"nomarker", "roles", "", "", false},
}
for _, c := range cases {
b, n, ok := splitBackendName(c.id, c.marker)
if ok != c.ok || b != c.backend || n != c.name {
t.Errorf("splitBackendName(%q,%q) = (%q,%q,%v), want (%q,%q,%v)",
c.id, c.marker, b, n, ok, c.backend, c.name, c.ok)
}
}
}
+101
View File
@@ -0,0 +1,101 @@
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 = &rancherProvider{}
type rancherProvider struct {
version string
}
type rancherProviderModel struct {
Address types.String `tfsdk:"address"`
Token types.String `tfsdk:"token"`
}
func New(version string) func() provider.Provider {
return func() provider.Provider {
return &rancherProvider{version: version}
}
}
func (p *rancherProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
// The provider's source address is git.unkin.net/unkin/ranchervaultsecret,
// but its resources are prefixed "rancher_" (declare it in required_providers
// under the local name "rancher"), mirroring how google-beta ships google_*.
resp.TypeName = "rancher"
resp.Version = p.version
}
func (p *rancherProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manage the Rancher token secrets engine (config, service accounts, and roles) on HashiCorp Vault or OpenBao.",
Attributes: map[string]schema.Attribute{
"address": schema.StringAttribute{
Description: "Address of the Vault/OpenBao server. Falls back to the VAULT_ADDR environment variable.",
Optional: true,
},
"token": schema.StringAttribute{
Description: "Token used to authenticate to Vault/OpenBao. Falls back to the VAULT_TOKEN environment variable.",
Optional: true,
Sensitive: true,
},
},
}
}
func (p *rancherProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
var config rancherProviderModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
address := os.Getenv("VAULT_ADDR")
if !config.Address.IsNull() && config.Address.ValueString() != "" {
address = config.Address.ValueString()
}
token := os.Getenv("VAULT_TOKEN")
if !config.Token.IsNull() && config.Token.ValueString() != "" {
token = config.Token.ValueString()
}
if address == "" {
resp.Diagnostics.AddError(
"missing Vault address",
"Set the provider \"address\" attribute or the VAULT_ADDR environment variable.",
)
return
}
client, err := newVaultClient(address, token)
if err != nil {
resp.Diagnostics.AddError("failed to create Vault client", err.Error())
return
}
resp.DataSourceData = client
resp.ResourceData = client
}
func (p *rancherProvider) Resources(_ context.Context) []func() resource.Resource {
return []func() resource.Resource{
NewSecretBackendResource,
NewSecretBackendServiceAccountResource,
NewSecretBackendRoleResource,
}
}
func (p *rancherProvider) DataSources(_ context.Context) []func() datasource.DataSource {
return nil
}
@@ -0,0 +1,239 @@
package provider
import (
"context"
"fmt"
"strings"
"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/booldefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &secretBackendResource{}
_ resource.ResourceWithImportState = &secretBackendResource{}
)
const defaultPluginType = "vault-plugin-secrets-rancher"
type secretBackendResource struct {
client *vaultClient
}
type secretBackendModel struct {
Path types.String `tfsdk:"path"`
Plugin types.String `tfsdk:"plugin"`
Description types.String `tfsdk:"description"`
RancherURL types.String `tfsdk:"rancher_url"`
CACert types.String `tfsdk:"ca_cert"`
TLSSkipVerify types.Bool `tfsdk:"tls_skip_verify"`
RequestTimeoutSeconds types.Int64 `tfsdk:"request_timeout_seconds"`
}
func NewSecretBackendResource() resource.Resource {
return &secretBackendResource{}
}
func (r *secretBackendResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_secret_backend"
}
func (r *secretBackendResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Mounts the Rancher secrets engine and writes its connection config.",
Attributes: map[string]schema.Attribute{
"path": schema.StringAttribute{
Description: "Mount path for the Rancher secrets engine (e.g. \"rancher\").",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"plugin": schema.StringAttribute{
Description: "Registered plugin name/type to mount.",
Optional: true,
Computed: true,
Default: stringdefault.StaticString(defaultPluginType),
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"description": schema.StringAttribute{
Description: "Human-readable description of the mount.",
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
},
"rancher_url": schema.StringAttribute{
Description: "Base URL of the Rancher server (e.g. https://rancher.example.com).",
Required: true,
},
"ca_cert": schema.StringAttribute{
Description: "PEM CA certificate that signed the Rancher server's TLS certificate.",
Optional: true,
},
"tls_skip_verify": schema.BoolAttribute{
Description: "Skip TLS verification of the Rancher server (not recommended).",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
},
"request_timeout_seconds": schema.Int64Attribute{
Description: "HTTP timeout in seconds for calls from the plugin to Rancher.",
Optional: true,
Computed: true,
Default: int64default.StaticInt64(30),
},
},
}
}
func (r *secretBackendResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*vaultClient)
if !ok {
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
return
}
r.client = client
}
func (r *secretBackendResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan secretBackendModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
mountPath := strings.Trim(plan.Path.ValueString(), "/")
err := r.client.enableMount(ctx, mountPath, plan.Plugin.ValueString(), plan.Description.ValueString(), mountConfig{})
if err != nil {
if isMountAlreadyExists(err) {
resp.Diagnostics.AddError(
"mount path already in use",
fmt.Sprintf("A secrets engine is already mounted at %q. Import it or choose another path.", mountPath),
)
return
}
resp.Diagnostics.AddError("failed to enable rancher secrets engine", err.Error())
return
}
if err := r.client.write(ctx, configPath(mountPath), r.configData(plan)); err != nil {
// Roll back the mount so we don't leave a half-configured engine.
_ = r.client.disableMount(ctx, mountPath)
resp.Diagnostics.AddError("failed to write rancher config", err.Error())
return
}
plan.Path = types.StringValue(mountPath)
resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
}
func (r *secretBackendResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state secretBackendModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
mountPath := strings.Trim(state.Path.ValueString(), "/")
mount, err := r.client.mountInfo(ctx, mountPath)
if err != nil {
resp.Diagnostics.AddError("failed to read mount", err.Error())
return
}
if mount == nil {
resp.State.RemoveResource(ctx)
return
}
state.Description = types.StringValue(mount.Description)
if mount.Type != "" {
state.Plugin = types.StringValue(mount.Type)
}
cfg, err := r.client.read(ctx, configPath(mountPath))
if err != nil {
resp.Diagnostics.AddError("failed to read rancher config", err.Error())
return
}
if cfg != nil {
if v, ok := cfg["rancher_url"].(string); ok {
state.RancherURL = types.StringValue(v)
}
if v, ok := cfg["tls_skip_verify"].(bool); ok {
state.TLSSkipVerify = types.BoolValue(v)
}
if n, ok := toInt64(cfg["request_timeout_seconds"]); ok {
state.RequestTimeoutSeconds = types.Int64Value(n)
}
}
// ca_cert is not returned by the backend; preserve the state value.
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
func (r *secretBackendResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan, state secretBackendModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
mountPath := strings.Trim(state.Path.ValueString(), "/")
if !plan.Description.Equal(state.Description) {
if err := r.client.tuneMount(ctx, mountPath, plan.Description.ValueString(), mountConfig{}); err != nil {
resp.Diagnostics.AddError("failed to tune mount description", err.Error())
return
}
}
if err := r.client.write(ctx, configPath(mountPath), r.configData(plan)); err != nil {
resp.Diagnostics.AddError("failed to update rancher config", err.Error())
return
}
plan.Path = types.StringValue(mountPath)
resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
}
func (r *secretBackendResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state secretBackendModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.disableMount(ctx, strings.Trim(state.Path.ValueString(), "/")); err != nil {
resp.Diagnostics.AddError("failed to disable rancher secrets engine", err.Error())
return
}
}
func (r *secretBackendResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("path"), req, resp)
}
func (r *secretBackendResource) configData(m secretBackendModel) map[string]interface{} {
data := map[string]interface{}{
"rancher_url": m.RancherURL.ValueString(),
"tls_skip_verify": m.TLSSkipVerify.ValueBool(),
"request_timeout_seconds": m.RequestTimeoutSeconds.ValueInt64(),
}
if !m.CACert.IsNull() && !m.CACert.IsUnknown() {
data["ca_cert"] = m.CACert.ValueString()
}
return data
}
@@ -0,0 +1,233 @@
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/types"
)
var (
_ resource.Resource = &secretBackendRoleResource{}
_ resource.ResourceWithImportState = &secretBackendRoleResource{}
)
type secretBackendRoleResource struct {
client *vaultClient
}
type secretBackendRoleModel struct {
Backend types.String `tfsdk:"backend"`
Name types.String `tfsdk:"name"`
ServiceAccount types.String `tfsdk:"service_account"`
ClusterName types.String `tfsdk:"cluster_name"`
Description types.String `tfsdk:"description"`
TTL types.Int64 `tfsdk:"ttl"`
MaxTTL types.Int64 `tfsdk:"max_ttl"`
}
func NewSecretBackendRoleResource() resource.Resource {
return &secretBackendRoleResource{}
}
func (r *secretBackendRoleResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_secret_backend_role"
}
func (r *secretBackendRoleResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a role on the Rancher secrets engine that mints short-lived tokens from a service account.",
Attributes: map[string]schema.Attribute{
"backend": schema.StringAttribute{
Description: "Mount path of the Rancher secrets engine.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"name": schema.StringAttribute{
Description: "Name of the role.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"service_account": schema.StringAttribute{
Description: "Service account (seeded token) used to mint credentials. Its user's RBAC is inherited by minted tokens.",
Required: true,
},
"cluster_name": schema.StringAttribute{
Description: "Downstream cluster to scope minted tokens to (empty = full Rancher-server scope).",
Optional: true,
},
"description": schema.StringAttribute{
Description: "Description applied to each minted Rancher token.",
Optional: true,
},
"ttl": schema.Int64Attribute{
Description: "Default lease TTL in seconds for tokens minted from this role.",
Optional: true,
},
"max_ttl": schema.Int64Attribute{
Description: "Maximum lease TTL in seconds for tokens minted from this role.",
Optional: true,
},
},
}
}
func (r *secretBackendRoleResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*vaultClient)
if !ok {
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
return
}
r.client = client
}
func (r *secretBackendRoleResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan secretBackendRoleModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.write(ctx, rolePath(plan.Backend.ValueString(), plan.Name.ValueString()), roleData(plan)); err != nil {
resp.Diagnostics.AddError("failed to create rancher role", err.Error())
return
}
resp.Diagnostics.Append(r.readInto(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
}
func (r *secretBackendRoleResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state secretBackendRoleModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
role, err := r.client.read(ctx, rolePath(state.Backend.ValueString(), state.Name.ValueString()))
if err != nil {
resp.Diagnostics.AddError("failed to read rancher role", err.Error())
return
}
if role == nil {
resp.State.RemoveResource(ctx)
return
}
applyRoleData(&state, role)
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
func (r *secretBackendRoleResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan secretBackendRoleModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.write(ctx, rolePath(plan.Backend.ValueString(), plan.Name.ValueString()), roleData(plan)); err != nil {
resp.Diagnostics.AddError("failed to update rancher role", err.Error())
return
}
resp.Diagnostics.Append(r.readInto(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
}
func (r *secretBackendRoleResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state secretBackendRoleModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.delete(ctx, rolePath(state.Backend.ValueString(), state.Name.ValueString())); err != nil {
resp.Diagnostics.AddError("failed to delete rancher role", err.Error())
return
}
}
func (r *secretBackendRoleResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
backend, name, ok := splitBackendName(req.ID, "roles")
if !ok {
resp.Diagnostics.AddError(
"invalid import ID",
fmt.Sprintf("expected \"<backend>/roles/<name>\", got %q", req.ID),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("backend"), backend)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
}
func (r *secretBackendRoleResource) readInto(ctx context.Context, m *secretBackendRoleModel) diag.Diagnostics {
var diags diag.Diagnostics
role, err := r.client.read(ctx, rolePath(m.Backend.ValueString(), m.Name.ValueString()))
if err != nil {
diags.AddError("failed to read back rancher role", err.Error())
return diags
}
if role == nil {
diags.AddError("role missing after write", "the role was not found immediately after being written")
return diags
}
applyRoleData(m, role)
return diags
}
func roleData(m secretBackendRoleModel) map[string]interface{} {
data := map[string]interface{}{
"service_account": m.ServiceAccount.ValueString(),
}
if !m.ClusterName.IsNull() && !m.ClusterName.IsUnknown() {
data["cluster_name"] = m.ClusterName.ValueString()
}
if !m.Description.IsNull() && !m.Description.IsUnknown() {
data["description"] = m.Description.ValueString()
}
if !m.TTL.IsNull() && !m.TTL.IsUnknown() {
data["ttl"] = m.TTL.ValueInt64()
}
if !m.MaxTTL.IsNull() && !m.MaxTTL.IsUnknown() {
data["max_ttl"] = m.MaxTTL.ValueInt64()
}
return data
}
func applyRoleData(m *secretBackendRoleModel, role map[string]interface{}) {
if v, ok := role["service_account"].(string); ok {
m.ServiceAccount = types.StringValue(v)
}
if v, ok := role["cluster_name"].(string); ok && v != "" {
m.ClusterName = types.StringValue(v)
} else if m.ClusterName.IsUnknown() {
m.ClusterName = types.StringNull()
}
if v, ok := role["description"].(string); ok && v != "" {
m.Description = types.StringValue(v)
} else if m.Description.IsUnknown() {
m.Description = types.StringNull()
}
if n, ok := toInt64(role["ttl"]); ok && n != 0 {
m.TTL = types.Int64Value(n)
} else if m.TTL.IsUnknown() {
m.TTL = types.Int64Null()
}
if n, ok := toInt64(role["max_ttl"]); ok && n != 0 {
m.MaxTTL = types.Int64Value(n)
} else if m.MaxTTL.IsUnknown() {
m.MaxTTL = types.Int64Null()
}
}
@@ -0,0 +1,218 @@
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/types"
)
var (
_ resource.Resource = &secretBackendServiceAccountResource{}
_ resource.ResourceWithImportState = &secretBackendServiceAccountResource{}
)
type secretBackendServiceAccountResource struct {
client *vaultClient
}
type secretBackendServiceAccountModel struct {
Backend types.String `tfsdk:"backend"`
Name types.String `tfsdk:"name"`
Token types.String `tfsdk:"token"`
TokenName types.String `tfsdk:"token_name"`
TokenTTL types.Int64 `tfsdk:"token_ttl"`
RotationPeriod types.Int64 `tfsdk:"rotation_period"`
LastRotated types.String `tfsdk:"last_rotated"`
}
func NewSecretBackendServiceAccountResource() resource.Resource {
return &secretBackendServiceAccountResource{}
}
func (r *secretBackendServiceAccountResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_secret_backend_service_account"
}
func (r *secretBackendServiceAccountResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Seeds a Rancher service-account token that the engine auto-rotates before Rancher's TTL cap.",
Attributes: map[string]schema.Attribute{
"backend": schema.StringAttribute{
Description: "Mount path of the Rancher secrets engine.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"name": schema.StringAttribute{
Description: "Name of the service account.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"token": schema.StringAttribute{
Description: "Rancher API token to seed with. Write-only; the engine rotates it from here on and never returns it.",
Required: true,
Sensitive: true,
},
"token_name": schema.StringAttribute{
Description: "ext.cattle.io Token resource name (metadata.name) of the seed token, so the engine can delete it after the first rotation.",
Optional: true,
Computed: true,
},
"token_ttl": schema.Int64Attribute{
Description: "Lifetime in seconds requested for each rotated replacement token (default 90d). Must not exceed Rancher's auth-token-max-ttl-minutes.",
Optional: true,
Computed: true,
},
"rotation_period": schema.Int64Attribute{
Description: "Seconds a token is used before rotation (default 45d). Must be less than token_ttl.",
Optional: true,
Computed: true,
},
"last_rotated": schema.StringAttribute{
Description: "RFC3339 timestamp of the current token's issuance (computed).",
Computed: true,
},
},
}
}
func (r *secretBackendServiceAccountResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*vaultClient)
if !ok {
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
return
}
r.client = client
}
func (r *secretBackendServiceAccountResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan secretBackendServiceAccountModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(r.writeAndRead(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
}
func (r *secretBackendServiceAccountResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan secretBackendServiceAccountModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(r.writeAndRead(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
}
// writeAndRead writes the service account then refreshes computed fields from
// the backend.
func (r *secretBackendServiceAccountResource) writeAndRead(ctx context.Context, plan *secretBackendServiceAccountModel) diag.Diagnostics {
var diags diag.Diagnostics
data := map[string]interface{}{"token": plan.Token.ValueString()}
if !plan.TokenName.IsNull() && !plan.TokenName.IsUnknown() {
data["token_name"] = plan.TokenName.ValueString()
}
if !plan.TokenTTL.IsNull() && !plan.TokenTTL.IsUnknown() {
data["token_ttl"] = plan.TokenTTL.ValueInt64()
}
if !plan.RotationPeriod.IsNull() && !plan.RotationPeriod.IsUnknown() {
data["rotation_period"] = plan.RotationPeriod.ValueInt64()
}
if err := r.client.write(ctx, serviceAccountPath(plan.Backend.ValueString(), plan.Name.ValueString()), data); err != nil {
diags.AddError("failed to write rancher service account", err.Error())
return diags
}
sa, err := r.client.read(ctx, serviceAccountPath(plan.Backend.ValueString(), plan.Name.ValueString()))
if err != nil {
diags.AddError("failed to read back rancher service account", err.Error())
return diags
}
if sa == nil {
diags.AddError("service account missing after write", "not found immediately after being written")
return diags
}
applyServiceAccount(plan, sa)
return diags
}
func (r *secretBackendServiceAccountResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state secretBackendServiceAccountModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
sa, err := r.client.read(ctx, serviceAccountPath(state.Backend.ValueString(), state.Name.ValueString()))
if err != nil {
resp.Diagnostics.AddError("failed to read rancher service account", err.Error())
return
}
if sa == nil {
resp.State.RemoveResource(ctx)
return
}
applyServiceAccount(&state, sa)
// token is never returned by the backend; preserve the state value.
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
func (r *secretBackendServiceAccountResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state secretBackendServiceAccountModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.delete(ctx, serviceAccountPath(state.Backend.ValueString(), state.Name.ValueString())); err != nil {
resp.Diagnostics.AddError("failed to delete rancher service account", err.Error())
return
}
}
func (r *secretBackendServiceAccountResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
backend, name, ok := splitBackendName(req.ID, "service-accounts")
if !ok {
resp.Diagnostics.AddError(
"invalid import ID",
fmt.Sprintf("expected \"<backend>/service-accounts/<name>\", got %q", req.ID),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("backend"), backend)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
}
func applyServiceAccount(m *secretBackendServiceAccountModel, sa map[string]interface{}) {
if v, ok := sa["token_name"].(string); ok {
m.TokenName = types.StringValue(v)
}
if n, ok := toInt64(sa["token_ttl"]); ok {
m.TokenTTL = types.Int64Value(n)
}
if n, ok := toInt64(sa["rotation_period"]); ok {
m.RotationPeriod = types.Int64Value(n)
}
if v, ok := sa["last_rotated"].(string); ok {
m.LastRotated = types.StringValue(v)
}
}