Skip to content

chore: create workspaces and templates for multiple orgs #13866

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 76 additions & 10 deletions cli/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"strings"
"time"

"github.com/google/uuid"
Expand All @@ -29,7 +30,9 @@ func (r *RootCmd) create() *serpent.Command {
parameterFlags workspaceParameterFlags
autoUpdates string
copyParametersFrom string
orgContext = NewOrganizationContext()
// Organization context is only required if more than 1 template
// shares the same name across multiple organizations.
orgContext = NewOrganizationContext()
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Expand All @@ -44,11 +47,7 @@ func (r *RootCmd) create() *serpent.Command {
),
Middleware: serpent.Chain(r.InitClient(client)),
Handler: func(inv *serpent.Invocation) error {
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}

var err error
workspaceOwner := codersdk.Me
if len(inv.Args) >= 1 {
workspaceOwner, workspaceName, err = splitNamedWorkspace(inv.Args[0])
Expand Down Expand Up @@ -99,7 +98,7 @@ func (r *RootCmd) create() *serpent.Command {
if templateName == "" {
_, _ = fmt.Fprintln(inv.Stdout, pretty.Sprint(cliui.DefaultStyles.Wrap, "Select a template below to preview the provisioned infrastructure:"))

templates, err := client.TemplatesByOrganization(inv.Context(), organization.ID)
templates, err := client.Templates(inv.Context(), codersdk.TemplateFilter{})
if err != nil {
return err
}
Expand All @@ -111,13 +110,28 @@ func (r *RootCmd) create() *serpent.Command {
templateNames := make([]string, 0, len(templates))
templateByName := make(map[string]codersdk.Template, len(templates))

// If more than 1 organization exists in the list of templates,
// then include the organization name in the select options.
uniqueOrganizations := make(map[uuid.UUID]bool)
for _, template := range templates {
uniqueOrganizations[template.OrganizationID] = true
}

for _, template := range templates {
templateName := template.Name
if len(uniqueOrganizations) > 1 {
templateName += cliui.Placeholder(
fmt.Sprintf(
" (%s)",
template.OrganizationName,
),
)
}

if template.ActiveUserCount > 0 {
templateName += cliui.Placeholder(
fmt.Sprintf(
" (used by %s)",
" used by %s",
formatActiveDevelopers(template.ActiveUserCount),
),
)
Expand Down Expand Up @@ -145,13 +159,65 @@ func (r *RootCmd) create() *serpent.Command {
}
templateVersionID = sourceWorkspace.LatestBuild.TemplateVersionID
} else {
template, err = client.TemplateByName(inv.Context(), organization.ID, templateName)
templates, err := client.Templates(inv.Context(), codersdk.TemplateFilter{
ExactName: templateName,
})
if err != nil {
return xerrors.Errorf("get template by name: %w", err)
}
if len(templates) == 0 {
return xerrors.Errorf("no template found with the name %q", templateName)
}

if len(templates) > 1 {
templateOrgs := []string{}
for _, tpl := range templates {
templateOrgs = append(templateOrgs, tpl.OrganizationName)
}

selectedOrg, err := orgContext.Selected(inv, client)
if err != nil {
return xerrors.Errorf("multiple templates found with the name %q, use `--org=<organization_name>` to specify which template by that name to use. Organizations available: %s", templateName, strings.Join(templateOrgs, ", "))
}

index := slices.IndexFunc(templates, func(i codersdk.Template) bool {
return i.OrganizationID == selectedOrg.ID
})
if index == -1 {
return xerrors.Errorf("no templates found with the name %q in the organization %q. Templates by that name exist in organizations: %s. Use --org=<organization_name> to select one.", templateName, selectedOrg.Name, strings.Join(templateOrgs, ", "))
}

// remake the list with the only template selected
templates = []codersdk.Template{templates[index]}
}

template = templates[0]
templateVersionID = template.ActiveVersionID
}

// If the user specified an organization via a flag or env var, the template **must**
// be in that organization. Otherwise, we should throw an error.
orgValue, orgValueSource := orgContext.ValueSource(inv)
if orgValue != "" && !(orgValueSource == serpent.ValueSourceDefault || orgValueSource == serpent.ValueSourceNone) {
selectedOrg, err := orgContext.Selected(inv, client)
if err != nil {
return err
}

if template.OrganizationID != selectedOrg.ID {
orgNameFormat := "'--org=%q'"
if orgValueSource == serpent.ValueSourceEnv {
orgNameFormat = "CODER_ORGANIZATION=%q"
}

return xerrors.Errorf("template is in organization %q, but %s was specified. Use %s to use this template",
template.OrganizationName,
fmt.Sprintf(orgNameFormat, selectedOrg.Name),
fmt.Sprintf(orgNameFormat, template.OrganizationName),
)
}
}

var schedSpec *string
if startAt != "" {
sched, err := parseCLISchedule(startAt)
Expand Down Expand Up @@ -207,7 +273,7 @@ func (r *RootCmd) create() *serpent.Command {
ttlMillis = ptr.Ref(stopAfter.Milliseconds())
}

workspace, err := client.CreateWorkspace(inv.Context(), organization.ID, workspaceOwner, codersdk.CreateWorkspaceRequest{
workspace, err := client.CreateWorkspace(inv.Context(), template.OrganizationID, workspaceOwner, codersdk.CreateWorkspaceRequest{
TemplateVersionID: templateVersionID,
Name: workspaceName,
AutostartSchedule: schedSpec,
Expand Down
11 changes: 10 additions & 1 deletion cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -641,9 +641,10 @@ func NewOrganizationContext() *OrganizationContext {
return &OrganizationContext{}
}

func (*OrganizationContext) optionName() string { return "Organization" }
func (o *OrganizationContext) AttachOptions(cmd *serpent.Command) {
cmd.Options = append(cmd.Options, serpent.Option{
Name: "Organization",
Name: o.optionName(),
Description: "Select which organization (uuid or name) to use.",
// Only required if the user is a part of more than 1 organization.
// Otherwise, we can assume a default value.
Expand All @@ -655,6 +656,14 @@ func (o *OrganizationContext) AttachOptions(cmd *serpent.Command) {
})
}

func (o *OrganizationContext) ValueSource(inv *serpent.Invocation) (string, serpent.ValueSource) {
opt := inv.Command.Options.ByName(o.optionName())
if opt == nil {
return o.FlagSelect, serpent.ValueSourceNone
}
return o.FlagSelect, opt.ValueSource
}

func (o *OrganizationContext) Selected(inv *serpent.Invocation, client *codersdk.Client) (codersdk.Organization, error) {
// Fetch the set of organizations the user is a member of.
orgs, err := client.OrganizationsByUser(inv.Context(), codersdk.Me)
Expand Down
5 changes: 3 additions & 2 deletions cli/templatecreate.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {
RequireActiveVersion: requireActiveVersion,
}

_, err = client.CreateTemplate(inv.Context(), organization.ID, createReq)
template, err := client.CreateTemplate(inv.Context(), organization.ID, createReq)
if err != nil {
return err
}
Expand All @@ -171,7 +171,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {
pretty.Sprint(cliui.DefaultStyles.DateTimeStamp, time.Now().Format(time.Stamp))+"! "+
"Developers can provision a workspace with this template using:")+"\n")

_, _ = fmt.Fprintln(inv.Stdout, " "+pretty.Sprint(cliui.DefaultStyles.Code, fmt.Sprintf("coder create --template=%q [workspace name]", templateName)))
_, _ = fmt.Fprintln(inv.Stdout, " "+pretty.Sprint(cliui.DefaultStyles.Code, fmt.Sprintf("coder create --template=%q --org=%q [workspace name]", templateName, template.OrganizationName)))
_, _ = fmt.Fprintln(inv.Stdout)

return nil
Expand Down Expand Up @@ -244,6 +244,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {

cliui.SkipPromptOption(),
}
orgContext.AttachOptions(cmd)
cmd.Options = append(cmd.Options, uploadFlags.options()...)
return cmd
}
3 changes: 3 additions & 0 deletions cli/testdata/coder_templates_create_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ USAGE:
flag

OPTIONS:
-O, --org string, $CODER_ORGANIZATION
Select which organization (uuid or name) to use.

--default-ttl duration (default: 24h)
Specify a default TTL for workspaces created from this template. It is
the default time before shutdown - workspaces created from this
Expand Down
5 changes: 2 additions & 3 deletions coderd/searchquery/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,8 @@ func Templates(ctx context.Context, db database.Store, query string) (database.G

parser := httpapi.NewQueryParamParser()
filter := database.GetTemplatesWithFilterParams{
Deleted: parser.Boolean(values, false, "deleted"),
// TODO: Should name be a fuzzy search?
ExactName: parser.String(values, "", "name"),
Deleted: parser.Boolean(values, false, "deleted"),
ExactName: parser.String(values, "", "exact_name"),
IDs: parser.UUIDs(values, []uuid.UUID{}, "ids"),
Deprecated: parser.NullableBoolean(values, sql.NullBool{}, "deprecated"),
}
Expand Down
5 changes: 5 additions & 0 deletions codersdk/organizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ func (c *Client) TemplatesByOrganization(ctx context.Context, organizationID uui

type TemplateFilter struct {
OrganizationID uuid.UUID
ExactName string
}

// asRequestOption returns a function that can be used in (*Client).Request.
Expand All @@ -378,6 +379,10 @@ func (f TemplateFilter) asRequestOption() RequestOption {
params = append(params, fmt.Sprintf("organization:%q", f.OrganizationID.String()))
}

if f.ExactName != "" {
params = append(params, fmt.Sprintf("exact_name:%q", f.ExactName))
}

q := r.URL.Query()
q.Set("q", strings.Join(params, " "))
r.URL.RawQuery = q.Encode()
Expand Down
9 changes: 9 additions & 0 deletions docs/cli/templates_create.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading