Files
coder/enterprise/cli/provisionerkeys.go
T
Nick VigilanteandJeremy Ruppel 3def3bf5a3 feat: add JSON output to coder provisioner keys create (#30152)
Uses the `cliui` output helpers from #30508.

`coder provisioner keys create` printed the new key's secret as prose,
so scripts provisioning external provisioners had to scrape it and look
up the key's ID and tags separately.

It now accepts `-o text|json`.
JSON is the key as `provisioner keys list` shows it (ID, name,
organization, tags, created at) plus the one-time `key`.

**Behavior change:** Additive.
Default text output is unchanged.
The command now fetches the new key's metadata with the returned secret
(`GET /api/v2/provisionerkeys/{key}`). If that fails, it prints a
warning to stderr, falls back to the name, organization and tags it sent
(leaving `id` and `created_at` unset), and still outputs the secret.

<details>
<summary>Decisions</summary>

- `CreateProvisionerKey` only returns the secret, so the key's metadata
comes from `GetProvisionerKey(secret)`, the same lookup `coder
provisioner start` uses. This replaced an earlier list-and-match-by-name
approach, per review.
- A failed lookup never fails the command, because the key already
exists and the secret can't be shown again.

</details>

Closes [CLI-36](https://linear.app/codercom/issue/CLI-36)

_This PR was generated by Coder Agents on behalf of @nickvigilante._

---------

Co-authored-by: Jeremy Ruppel <jeremyruppel@users.noreply.github.com>
2026-11-12 08:58:37 -05:00

222 lines
5.6 KiB
Go

package cli
import (
"fmt"
"strings"
"golang.org/x/xerrors"
agpl "github.com/coder/coder/v2/cli"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/pretty"
"github.com/coder/serpent"
)
func (r *RootCmd) provisionerKeys() *serpent.Command {
cmd := &serpent.Command{
Use: "keys",
Short: "Manage provisioner keys",
Handler: func(inv *serpent.Invocation) error {
return inv.Command.HelpHandler(inv)
},
Aliases: []string{"key"},
Children: []*serpent.Command{
r.provisionerKeysCreate(),
r.provisionerKeysList(),
r.provisionerKeysDelete(),
},
}
return cmd
}
// createProvisionerKeyResponse includes the one-time secret, which is only
// available at creation time.
type createProvisionerKeyResponse struct {
codersdk.ProvisionerKey
Key string `json:"key"`
}
func (r *RootCmd) provisionerKeysCreate() *serpent.Command {
var (
orgContext = agpl.NewOrganizationContext()
rawTags []string
formatter = cliui.NewOutputFormatter(
cliui.TextFormatFunc(func(resp createProvisionerKeyResponse) (string, error) {
return fmt.Sprintf(
"Successfully created provisioner key %s! Save this authentication token, it will not be shown again.\n\n%s",
pretty.Sprint(cliui.DefaultStyles.Keyword, strings.ToLower(resp.Name)),
pretty.Sprint(cliui.DefaultStyles.Keyword, resp.Key),
), nil
}),
cliui.JSONFormat(),
)
)
cmd := &serpent.Command{
Use: "create <name>",
Short: "Create a new provisioner key",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
org, err := orgContext.Selected(inv, client)
if err != nil {
return xerrors.Errorf("current organization: %w", err)
}
tags, err := agpl.ParseProvisionerTags(rawTags)
if err != nil {
return err
}
res, err := client.CreateProvisionerKey(ctx, org.ID, codersdk.CreateProvisionerKeyRequest{
Name: inv.Args[0],
Tags: tags,
})
if err != nil {
return xerrors.Errorf("create provisioner key: %w", err)
}
// CreateProvisionerKey only returns the secret, so use it to fetch the
// key's metadata. The key already exists, so never fail here and lose
// the one-time secret. If the lookup fails, fall back to the values
// this command sent.
key, err := client.GetProvisionerKey(ctx, res.Key)
if err != nil {
key = codersdk.ProvisionerKey{Name: inv.Args[0], OrganizationID: org.ID, Tags: tags}
cliui.Warnf(inv.Stderr, "Could not fetch metadata for the created provisioner key, so its id and created_at are unset: %s", err)
}
return formatter.WriteLine(ctx, inv.Stdout, createProvisionerKeyResponse{
ProvisionerKey: key,
Key: res.Key,
})
},
}
cmd.Options = serpent.OptionSet{
{
Flag: "tag",
FlagShorthand: "t",
Env: "CODER_PROVISIONERD_TAGS",
Description: "Tags to filter provisioner jobs by.",
Value: serpent.StringArrayOf(&rawTags),
},
}
orgContext.AttachOptions(cmd)
formatter.AttachOptions(&cmd.Options)
return cmd
}
func (r *RootCmd) provisionerKeysList() *serpent.Command {
var (
orgContext = agpl.NewOrganizationContext()
formatter = cliui.NewOutputFormatter(
cliui.TableFormat([]codersdk.ProvisionerKey{}, []string{"created at", "name", "tags"}),
cliui.JSONFormat(),
)
)
cmd := &serpent.Command{
Use: "list",
Short: "List provisioner keys in an organization",
Aliases: []string{"ls"},
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
org, err := orgContext.Selected(inv, client)
if err != nil {
return xerrors.Errorf("current organization: %w", err)
}
keys, err := client.ListProvisionerKeys(ctx, org.ID)
if err != nil {
return xerrors.Errorf("list provisioner keys: %w", err)
}
out, err := formatter.Format(inv.Context(), keys)
if err != nil {
return xerrors.Errorf("display provisioner keys: %w", err)
}
if out == "" {
cliui.Infof(inv.Stderr, "No provisioner keys found.")
return nil
}
_, _ = fmt.Fprintln(inv.Stdout, out)
return nil
},
}
orgContext.AttachOptions(cmd)
formatter.AttachOptions(&cmd.Options)
return cmd
}
func (r *RootCmd) provisionerKeysDelete() *serpent.Command {
orgContext := agpl.NewOrganizationContext()
cmd := &serpent.Command{
Use: "delete <name>",
Short: "Delete a provisioner key",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
org, err := orgContext.Selected(inv, client)
if err != nil {
return xerrors.Errorf("current organization: %w", err)
}
_, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: fmt.Sprintf("Are you sure you want to delete provisioner key %s?", pretty.Sprint(cliui.DefaultStyles.Keyword, inv.Args[0])),
IsConfirm: true,
})
if err != nil {
return err
}
err = client.DeleteProvisionerKey(ctx, org.ID, inv.Args[0])
if err != nil {
return xerrors.Errorf("delete provisioner key: %w", err)
}
_, _ = fmt.Fprintf(inv.Stdout, "Successfully deleted provisioner key %s!\n", pretty.Sprint(cliui.DefaultStyles.Keyword, strings.ToLower(inv.Args[0])))
return nil
},
}
cmd.Options = serpent.OptionSet{
cliui.SkipPromptOption(),
}
orgContext.AttachOptions(cmd)
return cmd
}