llmgw_org, llmgw_team and llmgw_project rename and move in place; llmgw_key holds the key in a sensitive secret and is made again when revoked or expired outside Terraform; llmgw_membership puts a person in the tree. Tried with OpenTofu against the fake admin API, drift and import included. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
533 lines
21 KiB
Go
533 lines
21 KiB
Go
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/planmodifier"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
|
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
|
|
"github.com/hashicorp/terraform-plugin-framework/types"
|
|
|
|
"gitea.mynodes.xyz/ilker/llmgw/terraform-provider-llmgw/internal/client"
|
|
)
|
|
|
|
// Organizations, teams and projects: one resource each, written once. A
|
|
// team names the organization it is in and a project the team, by path or
|
|
// ID; changing that moves it, with everything under it, rather than
|
|
// replacing it, as `llmgw org move` does.
|
|
|
|
type tenancyResource struct {
|
|
c *client.Client
|
|
// level is the API's path for it; kind the resource's name; parent the
|
|
// attribute naming what it is in, empty for an organization.
|
|
level, kind, parent string
|
|
}
|
|
|
|
func newOrgResource() resource.Resource {
|
|
return &tenancyResource{level: client.LevelOrg, kind: "org"}
|
|
}
|
|
|
|
func newTeamResource() resource.Resource {
|
|
return &tenancyResource{level: client.LevelTeam, kind: "team", parent: "org"}
|
|
}
|
|
|
|
func newProjectResource() resource.Resource {
|
|
return &tenancyResource{level: client.LevelProject, kind: "project", parent: "team"}
|
|
}
|
|
|
|
func (r *tenancyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
|
resp.TypeName = req.ProviderTypeName + "_" + r.kind
|
|
}
|
|
|
|
func (r *tenancyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
|
keep := []planmodifier.String{stringplanmodifier.UseStateForUnknown()}
|
|
attrs := map[string]schema.Attribute{
|
|
"id": schema.StringAttribute{Computed: true, PlanModifiers: keep,
|
|
Description: "The " + r.kind + "'s ID. Import by it."},
|
|
"name": schema.StringAttribute{Required: true,
|
|
Description: "Its name; changing it renames it, keeping its ID and everything under it."},
|
|
}
|
|
desc := "An organization: the top of the tenancy tree. Removed only when it has no teams."
|
|
switch r.kind {
|
|
case "team":
|
|
desc = "A team in an organization. Removed only when it has no projects."
|
|
attrs["org"] = schema.StringAttribute{Required: true,
|
|
Description: "The organization it is in, by name or ID; changing it moves the team and its projects."}
|
|
attrs["org_id"] = schema.StringAttribute{Computed: true, Description: "The organization's ID."}
|
|
case "project":
|
|
desc = "A project in a team: where keys, people and spending meet. Removed only when it has no people and no collections, " +
|
|
"and has never had a key: a revoked key stays, because usage refers to it. Rename such a project rather than destroying it."
|
|
attrs["team"] = schema.StringAttribute{Required: true,
|
|
Description: "The team it is in, as ORG/TEAM or its ID; changing it moves the project."}
|
|
attrs["team_id"] = schema.StringAttribute{Computed: true, Description: "The team's ID."}
|
|
attrs["path"] = schema.StringAttribute{Computed: true, Description: "ORG/TEAM/PROJECT, by name."}
|
|
}
|
|
resp.Schema = schema.Schema{Description: desc, Attributes: attrs}
|
|
}
|
|
|
|
func (r *tenancyResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
|
|
if c, ok := clientFrom(req.ProviderData); ok {
|
|
r.c = c
|
|
}
|
|
}
|
|
|
|
// found is a node as the tree has it.
|
|
type found struct{ name, in, path string }
|
|
|
|
// lookup finds a node of this resource's level in the tree by ID.
|
|
func (r *tenancyResource) lookup(ctx context.Context, id string) (found, bool, error) {
|
|
tree, err := r.c.Tree(ctx)
|
|
if err != nil {
|
|
return found{}, false, err
|
|
}
|
|
for _, o := range tree {
|
|
if r.level == client.LevelOrg && o.ID == id {
|
|
return found{name: o.Name}, true, nil
|
|
}
|
|
for _, t := range o.Teams {
|
|
if r.level == client.LevelTeam && t.ID == id {
|
|
return found{name: t.Name, in: o.ID}, true, nil
|
|
}
|
|
for _, p := range t.Projects {
|
|
if r.level == client.LevelProject && p.ID == id {
|
|
return found{name: p.Name, in: t.ID, path: p.Path}, true, nil
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return found{}, false, nil
|
|
}
|
|
|
|
// set writes what the API says into the state: the computed attributes,
|
|
// and, when the API has moved on from what the state said, the configured
|
|
// ones too, so the next plan shows the difference.
|
|
func (r *tenancyResource) set(ctx context.Context, st *tfsdk.State, id string, f found, fromAPI bool) {
|
|
st.SetAttribute(ctx, path.Root("id"), types.StringValue(id))
|
|
if fromAPI {
|
|
st.SetAttribute(ctx, path.Root("name"), types.StringValue(f.name))
|
|
}
|
|
if r.parent == "" {
|
|
return
|
|
}
|
|
var was types.String
|
|
st.GetAttribute(ctx, path.Root(r.parent+"_id"), &was)
|
|
if fromAPI && was.ValueString() != f.in {
|
|
st.SetAttribute(ctx, path.Root(r.parent), types.StringValue(f.in))
|
|
}
|
|
st.SetAttribute(ctx, path.Root(r.parent+"_id"), types.StringValue(f.in))
|
|
if r.level == client.LevelProject {
|
|
st.SetAttribute(ctx, path.Root("path"), types.StringValue(f.path))
|
|
}
|
|
}
|
|
|
|
func (r *tenancyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
|
var name, in types.String
|
|
resp.Diagnostics.Append(req.Plan.GetAttribute(ctx, path.Root("name"), &name)...)
|
|
if r.parent != "" {
|
|
resp.Diagnostics.Append(req.Plan.GetAttribute(ctx, path.Root(r.parent), &in)...)
|
|
}
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
item, err := r.c.Create(ctx, r.level, client.TenancyCreateRequest{Name: name.ValueString(), In: in.ValueString()})
|
|
if err != nil {
|
|
resp.Diagnostics.AddError("Adding "+r.kind+" "+name.ValueString(), err.Error())
|
|
return
|
|
}
|
|
f, ok, err := r.lookup(ctx, item.ID)
|
|
if err != nil || !ok {
|
|
resp.Diagnostics.AddError("Reading back "+r.kind+" "+name.ValueString(), fmt.Sprint("not in the tree after adding it ", err))
|
|
return
|
|
}
|
|
resp.State.Raw = req.Plan.Raw
|
|
r.set(ctx, &resp.State, item.ID, f, false)
|
|
}
|
|
|
|
func (r *tenancyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
|
var id types.String
|
|
resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("id"), &id)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
f, ok, err := r.lookup(ctx, id.ValueString())
|
|
if err != nil {
|
|
resp.Diagnostics.AddError("Reading the tenancy tree", err.Error())
|
|
return
|
|
}
|
|
if !ok {
|
|
resp.State.RemoveResource(ctx)
|
|
return
|
|
}
|
|
r.set(ctx, &resp.State, id.ValueString(), f, true)
|
|
}
|
|
|
|
func (r *tenancyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
|
var id, name, wasName, in, wasIn types.String
|
|
resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("id"), &id)...)
|
|
resp.Diagnostics.Append(req.Plan.GetAttribute(ctx, path.Root("name"), &name)...)
|
|
resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("name"), &wasName)...)
|
|
if r.parent != "" {
|
|
resp.Diagnostics.Append(req.Plan.GetAttribute(ctx, path.Root(r.parent), &in)...)
|
|
resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root(r.parent), &wasIn)...)
|
|
}
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
var change client.TenancyChangeRequest
|
|
if !name.Equal(wasName) {
|
|
change.Name = name.ValueString()
|
|
}
|
|
if r.parent != "" && !in.Equal(wasIn) {
|
|
change.In = in.ValueString()
|
|
}
|
|
if change.Name != "" || change.In != "" {
|
|
if _, err := r.c.Change(ctx, r.level, id.ValueString(), change); err != nil {
|
|
resp.Diagnostics.AddError("Changing "+r.kind+" "+wasName.ValueString(), err.Error())
|
|
return
|
|
}
|
|
}
|
|
f, ok, err := r.lookup(ctx, id.ValueString())
|
|
if err != nil || !ok {
|
|
resp.Diagnostics.AddError("Reading back "+r.kind+" "+name.ValueString(), fmt.Sprint("not in the tree after changing it ", err))
|
|
return
|
|
}
|
|
resp.State.Raw = req.Plan.Raw
|
|
r.set(ctx, &resp.State, id.ValueString(), f, false)
|
|
}
|
|
|
|
func (r *tenancyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
|
var id, name types.String
|
|
resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("id"), &id)...)
|
|
resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("name"), &name)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
if err := r.c.Remove(ctx, r.level, id.ValueString()); err != nil && !client.IsNotFound(err) {
|
|
resp.Diagnostics.AddError("Removing "+r.kind+" "+name.ValueString(), err.Error())
|
|
}
|
|
}
|
|
|
|
func (r *tenancyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
|
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
|
|
}
|
|
|
|
// --- keys ---
|
|
|
|
// The key resource is an API key. Its secret is known only to the apply
|
|
// that made it, and kept in the state, marked sensitive: the gateway keeps
|
|
// only a hash. A key revoked or expired outside Terraform is made again.
|
|
|
|
type keyResource struct{ c *client.Client }
|
|
|
|
func newKeyResource() resource.Resource { return &keyResource{} }
|
|
|
|
type keyModel struct {
|
|
ID types.String `tfsdk:"id"`
|
|
Name types.String `tfsdk:"name"`
|
|
Project types.String `tfsdk:"project"`
|
|
User types.String `tfsdk:"user"`
|
|
Band types.String `tfsdk:"band"`
|
|
RoutingProfile types.String `tfsdk:"routing_profile"`
|
|
ExpiresIn types.String `tfsdk:"expires_in"`
|
|
Secret types.String `tfsdk:"secret"`
|
|
Prefix types.String `tfsdk:"prefix"`
|
|
ExpiresAt types.String `tfsdk:"expires_at"`
|
|
ProjectID types.String `tfsdk:"project_id"`
|
|
UserID types.String `tfsdk:"user_id"`
|
|
}
|
|
|
|
func (r *keyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
|
resp.TypeName = req.ProviderTypeName + "_key"
|
|
}
|
|
|
|
func (r *keyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
|
replace := []planmodifier.String{stringplanmodifier.RequiresReplace()}
|
|
keep := []planmodifier.String{stringplanmodifier.UseStateForUnknown()}
|
|
resp.Schema = schema.Schema{
|
|
Description: "An API key: a project's, a person's in a project they are a member of, or a person's own. " +
|
|
"Every change makes a new key; one revoked or expired outside Terraform is made again on the next apply.",
|
|
Attributes: map[string]schema.Attribute{
|
|
"id": schema.StringAttribute{Computed: true, PlanModifiers: keep,
|
|
Description: "The key's ID, not the key. Import by it; an imported key has no secret."},
|
|
"name": schema.StringAttribute{Required: true, PlanModifiers: replace},
|
|
"project": schema.StringAttribute{Optional: true, PlanModifiers: replace,
|
|
Description: "The project it belongs to, as ORG/TEAM/PROJECT or its ID."},
|
|
"user": schema.StringAttribute{Optional: true, PlanModifiers: replace,
|
|
Description: "The person it belongs to, by ID or email; with a project, they must be a member of it."},
|
|
"band": schema.StringAttribute{Optional: true, PlanModifiers: replace,
|
|
Description: "Admission band; inherited when unset."},
|
|
"routing_profile": schema.StringAttribute{Optional: true, PlanModifiers: replace,
|
|
Description: "Routing profile; inherited when unset."},
|
|
"expires_in": schema.StringAttribute{Optional: true, PlanModifiers: replace,
|
|
Description: "Lifetime, such as 720h; never, unless a scope above it limits how long keys live."},
|
|
"secret": schema.StringAttribute{Computed: true, Sensitive: true, PlanModifiers: keep,
|
|
Description: "The key itself."},
|
|
"prefix": schema.StringAttribute{Computed: true, PlanModifiers: keep, Description: "Its first characters, as listings show it."},
|
|
"expires_at": schema.StringAttribute{Computed: true, PlanModifiers: keep, Description: "When it stops working, RFC 3339; empty for never."},
|
|
"project_id": schema.StringAttribute{Computed: true, PlanModifiers: keep},
|
|
"user_id": schema.StringAttribute{Computed: true, PlanModifiers: keep},
|
|
},
|
|
}
|
|
}
|
|
|
|
func (r *keyResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
|
|
if c, ok := clientFrom(req.ProviderData); ok {
|
|
r.c = c
|
|
}
|
|
}
|
|
|
|
func (r *keyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
|
var plan keyModel
|
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
k, err := r.c.CreateKey(ctx, client.KeyCreateRequest{Name: plan.Name.ValueString(), Project: plan.Project.ValueString(),
|
|
User: plan.User.ValueString(), Band: plan.Band.ValueString(), RoutingProfile: plan.RoutingProfile.ValueString(),
|
|
ExpiresIn: plan.ExpiresIn.ValueString()})
|
|
if err != nil {
|
|
resp.Diagnostics.AddError("Issuing key "+plan.Name.ValueString(), err.Error())
|
|
return
|
|
}
|
|
plan.ID, plan.Secret, plan.Prefix = types.StringValue(k.ID), types.StringValue(k.Secret), types.StringValue(k.Prefix)
|
|
plan.ProjectID, plan.UserID = types.StringValue(k.Project), types.StringValue(k.User)
|
|
plan.ExpiresAt = types.StringValue("")
|
|
if !k.ExpiresAt.IsZero() {
|
|
plan.ExpiresAt = types.StringValue(k.ExpiresAt.Format("2006-01-02T15:04:05Z07:00"))
|
|
}
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
|
}
|
|
|
|
func (r *keyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
|
var st keyModel
|
|
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
k, err := r.c.Key(ctx, st.ID.ValueString())
|
|
if client.IsNotFound(err) || err == nil && k.State != "active" {
|
|
resp.State.RemoveResource(ctx)
|
|
return
|
|
}
|
|
if err != nil {
|
|
resp.Diagnostics.AddError("Reading key "+st.ID.ValueString(), err.Error())
|
|
return
|
|
}
|
|
if st.Name.IsNull() {
|
|
// Imported: what it was made with comes from the API.
|
|
st.Name, st.Project, st.User = types.StringValue(k.Name), strOrNull(k.Project), strOrNull(k.User)
|
|
st.Band, st.RoutingProfile = strOrNull(k.Band), strOrNull(k.RoutingProfile)
|
|
st.Prefix, st.ProjectID, st.UserID = types.StringValue(k.Prefix), types.StringValue(k.Project), types.StringValue(k.User)
|
|
st.ExpiresAt = types.StringValue("")
|
|
if !k.ExpiresAt.IsZero() {
|
|
st.ExpiresAt = types.StringValue(k.ExpiresAt.Format("2006-01-02T15:04:05Z07:00"))
|
|
}
|
|
}
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &st)...)
|
|
}
|
|
|
|
// Update is never called: every attribute replaces the key.
|
|
func (r *keyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
|
var plan keyModel
|
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
|
}
|
|
|
|
func (r *keyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
|
var st keyModel
|
|
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
if err := r.c.RevokeKey(ctx, st.ID.ValueString()); err != nil && !client.IsNotFound(err) {
|
|
resp.Diagnostics.AddError("Revoking key "+st.Name.ValueString(), err.Error())
|
|
}
|
|
}
|
|
|
|
func (r *keyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
|
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
|
|
}
|
|
|
|
// --- memberships ---
|
|
|
|
// The membership resource puts a person in an organization, team or
|
|
// project. People themselves are not made here: they sign up, are invited
|
|
// or come from the identity provider.
|
|
|
|
type membershipResource struct{ c *client.Client }
|
|
|
|
func newMembershipResource() resource.Resource { return &membershipResource{} }
|
|
|
|
type membershipModel struct {
|
|
ID types.String `tfsdk:"id"`
|
|
User types.String `tfsdk:"user"`
|
|
Target types.String `tfsdk:"target"`
|
|
Role types.String `tfsdk:"role"`
|
|
UserID types.String `tfsdk:"user_id"`
|
|
// Scope is the target resolved, scope:ID.
|
|
Scope types.String `tfsdk:"scope"`
|
|
}
|
|
|
|
func (r *membershipResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
|
resp.TypeName = req.ProviderTypeName + "_membership"
|
|
}
|
|
|
|
func (r *membershipResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
|
replace := []planmodifier.String{stringplanmodifier.RequiresReplace()}
|
|
keep := []planmodifier.String{stringplanmodifier.UseStateForUnknown()}
|
|
resp.Schema = schema.Schema{
|
|
Description: "A person's membership of an organization, team or project. Taking it away revokes their keys in projects they no longer reach.",
|
|
Attributes: map[string]schema.Attribute{
|
|
"id": schema.StringAttribute{Computed: true, PlanModifiers: keep,
|
|
Description: "USER-ID/scope:SCOPE-ID. Import by it."},
|
|
"user": schema.StringAttribute{Required: true, PlanModifiers: replace,
|
|
Description: "The person, by ID or email."},
|
|
"target": schema.StringAttribute{Required: true, PlanModifiers: replace,
|
|
Description: "org:NAME, team:ORG/TEAM or project:ORG/TEAM/PROJECT, or the ID after the colon."},
|
|
"role": schema.StringAttribute{Optional: true,
|
|
Description: "member or manager; member when unset."},
|
|
"user_id": schema.StringAttribute{Computed: true, PlanModifiers: keep},
|
|
"scope": schema.StringAttribute{Computed: true, PlanModifiers: keep, Description: "The target as scope:ID."},
|
|
},
|
|
}
|
|
}
|
|
|
|
func (r *membershipResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
|
|
if c, ok := clientFrom(req.ProviderData); ok {
|
|
r.c = c
|
|
}
|
|
}
|
|
|
|
// resolveTarget is a target as scope:ID, read from the tree.
|
|
func resolveTarget(ctx context.Context, c *client.Client, target string) (string, error) {
|
|
kind, what, ok := strings.Cut(strings.TrimSpace(target), ":")
|
|
if !ok || what == "" {
|
|
return "", fmt.Errorf("%q is not org:, team: or project: and a name or ID", target)
|
|
}
|
|
tree, err := c.Tree(ctx)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
same := func(a, b string) bool { return strings.EqualFold(strings.TrimSpace(a), strings.TrimSpace(b)) }
|
|
for _, o := range tree {
|
|
if kind == "org" && (o.ID == what || same(o.Name, what)) {
|
|
return "org:" + o.ID, nil
|
|
}
|
|
for _, t := range o.Teams {
|
|
if kind == "team" && (t.ID == what || same(o.Name+"/"+t.Name, what)) {
|
|
return "team:" + t.ID, nil
|
|
}
|
|
for _, p := range t.Projects {
|
|
if kind == "project" && (p.ID == what || same(p.Path, what)) {
|
|
return "project:" + p.ID, nil
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return "", fmt.Errorf("there is no %s %q", kind, what)
|
|
}
|
|
|
|
func roleOf(v types.String) string {
|
|
if v.IsNull() || v.ValueString() == "" {
|
|
return "member"
|
|
}
|
|
return v.ValueString()
|
|
}
|
|
|
|
func (r *membershipResource) join(ctx context.Context, m *membershipModel) error {
|
|
scope := m.Scope.ValueString()
|
|
if m.Scope.IsNull() || m.Scope.IsUnknown() {
|
|
var err error
|
|
if scope, err = resolveTarget(ctx, r.c, m.Target.ValueString()); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
u, err := r.c.Join(ctx, m.User.ValueString(), client.MembershipRequest{Target: scope, Role: roleOf(m.Role)})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
m.ID, m.UserID, m.Scope = types.StringValue(u.ID+"/"+scope), types.StringValue(u.ID), types.StringValue(scope)
|
|
return nil
|
|
}
|
|
|
|
func (r *membershipResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
|
var plan membershipModel
|
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
if err := r.join(ctx, &plan); err != nil {
|
|
resp.Diagnostics.AddError("Putting "+plan.User.ValueString()+" in "+plan.Target.ValueString(), err.Error())
|
|
return
|
|
}
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
|
}
|
|
|
|
func (r *membershipResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
|
var st membershipModel
|
|
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
u, err := r.c.User(ctx, st.UserID.ValueString())
|
|
if client.IsNotFound(err) {
|
|
resp.State.RemoveResource(ctx)
|
|
return
|
|
}
|
|
if err != nil {
|
|
resp.Diagnostics.AddError("Reading "+st.User.ValueString(), err.Error())
|
|
return
|
|
}
|
|
for _, m := range u.Memberships {
|
|
if m.Target == st.Scope.ValueString() {
|
|
// Unset stays unset while the role is the default.
|
|
if !(st.Role.IsNull() && m.Role == "member") {
|
|
st.Role = types.StringValue(m.Role)
|
|
}
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &st)...)
|
|
return
|
|
}
|
|
}
|
|
resp.State.RemoveResource(ctx)
|
|
}
|
|
|
|
func (r *membershipResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
|
var plan membershipModel
|
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
if err := r.join(ctx, &plan); err != nil {
|
|
resp.Diagnostics.AddError("Changing "+plan.User.ValueString()+"'s role in "+plan.Target.ValueString(), err.Error())
|
|
return
|
|
}
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
|
}
|
|
|
|
func (r *membershipResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
|
var st membershipModel
|
|
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
if err := r.c.Leave(ctx, st.UserID.ValueString(), st.Scope.ValueString()); err != nil && !client.IsNotFound(err) {
|
|
resp.Diagnostics.AddError("Taking "+st.User.ValueString()+" out of "+st.Target.ValueString(), err.Error())
|
|
}
|
|
}
|
|
|
|
func (r *membershipResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
|
user, scope, ok := strings.Cut(req.ID, "/")
|
|
if !ok || !strings.Contains(scope, ":") {
|
|
resp.Diagnostics.AddError("Not a membership ID", fmt.Sprintf("%q is not USER-ID/scope:SCOPE-ID, as id shows it", req.ID))
|
|
return
|
|
}
|
|
st := membershipModel{ID: types.StringValue(req.ID), User: types.StringValue(user), Target: types.StringValue(scope),
|
|
Role: types.StringNull(), UserID: types.StringValue(user), Scope: types.StringValue(scope)}
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &st)...)
|
|
}
|