2022-02-12 13:34:04 -06:00
package cli
import (
2023-02-27 10:18:19 -06:00
"context"
2025-07-28 14:46:04 +01:00
"errors"
2022-02-12 13:34:04 -06:00
"fmt"
2022-09-22 13:26:05 -05:00
"io"
2025-03-03 21:46:49 +08:00
"slices"
2024-07-12 10:47:28 -10:00
"strings"
2022-02-12 13:34:04 -06:00
"time"
2023-04-04 14:22:46 +02:00
"github.com/google/uuid"
2022-02-12 13:34:04 -06:00
"golang.org/x/xerrors"
2023-09-07 17:28:22 -04:00
"github.com/coder/pretty"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/cli/cliui"
2024-12-02 20:54:32 +00:00
"github.com/coder/coder/v2/cli/cliutil"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/util/ptr"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/codersdk"
2024-03-15 11:24:38 -05:00
"github.com/coder/serpent"
2022-02-12 13:34:04 -06:00
)
2025-07-28 14:46:04 +01:00
// PresetNone represents the special preset value "none".
// It is used when a user runs `create --preset none`,
// indicating that the CLI should not apply any preset.
const PresetNone = "none"
var ErrNoPresetFound = xerrors . New ( "no preset found" )
2024-03-17 09:45:26 -05:00
func ( r * RootCmd ) create () * serpent . Command {
2022-03-22 13:17:50 -06:00
var (
2024-10-11 18:30:11 +05:30
templateName string
templateVersion string
2025-07-28 14:46:04 +01:00
presetName string
2024-10-11 18:30:11 +05:30
startAt string
stopAfter time . Duration
workspaceName string
2023-08-09 13:00:25 +02:00
2023-11-09 19:22:47 +01:00
parameterFlags workspaceParameterFlags
autoUpdates string
copyParametersFrom string
2024-07-12 10:47:28 -10:00
// Organization context is only required if more than 1 template
// shares the same name across multiple organizations.
orgContext = NewOrganizationContext ()
2022-03-22 13:17:50 -06:00
)
2023-03-23 17:42:20 -05:00
client := new ( codersdk . Client )
2024-03-17 09:45:26 -05:00
cmd := & serpent . Command {
2022-05-09 17:42:02 -05:00
Annotations : workspaceCommand ,
2024-12-05 02:32:52 +01:00
Use : "create [workspace]" ,
2022-09-19 11:36:18 -05:00
Short : "Create a workspace" ,
2024-05-21 13:26:34 -05:00
Long : FormatExamples (
Example {
2023-07-14 09:48:02 -04:00
Description : "Create a workspace for another user (if you have permission)" ,
Command : "coder create <username>/<workspace_name>" ,
},
),
2024-03-15 11:24:38 -05:00
Middleware : serpent . Chain ( r . InitClient ( client )),
Handler : func ( inv * serpent . Invocation ) error {
2024-07-12 10:47:28 -10:00
var err error
2023-07-14 09:48:02 -04:00
workspaceOwner := codersdk . Me
2023-03-23 17:42:20 -05:00
if len ( inv . Args ) >= 1 {
2023-07-14 09:48:02 -04:00
workspaceOwner , workspaceName , err = splitNamedWorkspace ( inv . Args [ 0 ])
if err != nil {
return err
}
2022-02-12 13:34:04 -06:00
}
2022-04-11 18:54:30 -05:00
if workspaceName == "" {
2023-03-23 17:42:20 -05:00
workspaceName , err = cliui . Prompt ( inv , cliui . PromptOptions {
2022-04-11 18:54:30 -05:00
Text : "Specify a name for your workspace:" ,
Validate : func ( workspaceName string ) error {
2024-09-04 18:34:39 +10:00
err = codersdk . NameValid ( workspaceName )
if err != nil {
return xerrors . Errorf ( "workspace name %q is invalid: %w" , workspaceName , err )
}
_ , err = client . WorkspaceByOwnerAndName ( inv . Context (), workspaceOwner , workspaceName , codersdk . WorkspaceOptions {})
2022-04-11 18:54:30 -05:00
if err == nil {
2024-09-04 18:34:39 +10:00
return xerrors . Errorf ( "a workspace already exists named %q" , workspaceName )
2022-04-11 18:54:30 -05:00
}
return nil
},
})
if err != nil {
return err
}
}
2024-09-04 18:34:39 +10:00
err = codersdk . NameValid ( workspaceName )
if err != nil {
return xerrors . Errorf ( "workspace name %q is invalid: %w" , workspaceName , err )
}
2023-07-14 09:48:02 -04:00
_ , err = client . WorkspaceByOwnerAndName ( inv . Context (), workspaceOwner , workspaceName , codersdk . WorkspaceOptions {})
2022-03-22 13:17:50 -06:00
if err == nil {
2024-09-04 18:34:39 +10:00
return xerrors . Errorf ( "a workspace already exists named %q" , workspaceName )
2022-02-12 13:34:04 -06:00
}
2022-03-22 13:17:50 -06:00
2023-11-09 19:22:47 +01:00
var sourceWorkspace codersdk . Workspace
if copyParametersFrom != "" {
sourceWorkspaceOwner , sourceWorkspaceName , err := splitNamedWorkspace ( copyParametersFrom )
if err != nil {
return err
}
sourceWorkspace , err = client . WorkspaceByOwnerAndName ( inv . Context (), sourceWorkspaceOwner , sourceWorkspaceName , codersdk . WorkspaceOptions {})
if err != nil {
return xerrors . Errorf ( "get source workspace: %w" , err )
}
_ , _ = fmt . Fprintf ( inv . Stdout , "Coder will use the same template %q as the source workspace.\n" , sourceWorkspace . TemplateName )
templateName = sourceWorkspace . TemplateName
}
2022-04-14 13:23:20 -04:00
var template codersdk . Template
2023-11-09 19:22:47 +01:00
var templateVersionID uuid . UUID
2025-03-26 01:56:39 -05:00
switch {
case templateName == "" :
2023-09-07 17:28:22 -04:00
_ , _ = fmt . Fprintln ( inv . Stdout , pretty . Sprint ( cliui . DefaultStyles . Wrap , "Select a template below to preview the provisioned infrastructure:" ))
2022-04-14 13:23:20 -04:00
2024-07-12 10:47:28 -10:00
templates , err := client . Templates ( inv . Context (), codersdk . TemplateFilter {})
2022-04-14 13:23:20 -04:00
if err != nil {
return err
}
2023-08-09 14:50:26 -05:00
slices . SortFunc ( templates , func ( a , b codersdk . Template ) int {
return slice . Descending ( a . ActiveUserCount , b . ActiveUserCount )
2022-04-14 13:23:20 -04:00
})
templateNames := make ([] string , 0 , len ( templates ))
templateByName := make ( map [ string ] codersdk . Template , len ( templates ))
2024-07-12 10:47:28 -10:00
// 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
}
2022-04-14 13:23:20 -04:00
for _ , template := range templates {
templateName := template . Name
2024-07-12 10:47:28 -10:00
if len ( uniqueOrganizations ) > 1 {
templateName += cliui . Placeholder (
fmt . Sprintf (
" (%s)" ,
template . OrganizationName ,
),
)
}
2022-04-14 13:23:20 -04:00
2022-09-09 14:30:31 -05:00
if template . ActiveUserCount > 0 {
2023-09-07 17:28:22 -04:00
templateName += cliui . Placeholder (
2022-09-09 14:30:31 -05:00
fmt . Sprintf (
2024-07-12 10:47:28 -10:00
" used by %s" ,
2022-09-09 14:30:31 -05:00
formatActiveDevelopers ( template . ActiveUserCount ),
),
)
2022-04-14 13:23:20 -04:00
}
templateNames = append ( templateNames , templateName )
templateByName [ templateName ] = template
}
// Move the cursor up a single line for nicer display!
2023-03-23 17:42:20 -05:00
option , err := cliui . Select ( inv , cliui . SelectOptions {
2022-04-14 13:23:20 -04:00
Options : templateNames ,
HideSearch : true ,
})
if err != nil {
return err
}
template = templateByName [ option ]
2023-11-09 19:22:47 +01:00
templateVersionID = template . ActiveVersionID
2025-03-26 01:56:39 -05:00
case sourceWorkspace . LatestBuild . TemplateVersionID != uuid . Nil :
2023-11-09 19:22:47 +01:00
template , err = client . Template ( inv . Context (), sourceWorkspace . TemplateID )
if err != nil {
return xerrors . Errorf ( "get template by name: %w" , err )
}
templateVersionID = sourceWorkspace . LatestBuild . TemplateVersionID
2025-03-26 01:56:39 -05:00
default :
2024-07-12 10:47:28 -10:00
templates , err := client . Templates ( inv . Context (), codersdk . TemplateFilter {
ExactName : templateName ,
})
2022-04-14 13:23:20 -04:00
if err != nil {
return xerrors . Errorf ( "get template by name: %w" , err )
}
2024-07-12 10:47:28 -10:00
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 ]
2023-11-09 19:22:47 +01:00
templateVersionID = template . ActiveVersionID
2022-04-14 13:23:20 -04:00
}
2024-10-11 18:30:11 +05:30
if len ( templateVersion ) > 0 {
version , err := client . TemplateVersionByName ( inv . Context (), template . ID , templateVersion )
if err != nil {
return xerrors . Errorf ( "get template version by name: %w" , err )
}
templateVersionID = version . ID
}
2024-07-12 10:47:28 -10:00
// 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 ),
)
}
}
2022-06-17 21:38:10 +01:00
var schedSpec * string
if startAt != "" {
sched , err := parseCLISchedule ( startAt )
if err != nil {
return err
}
schedSpec = ptr . Ref ( sched . String ())
2022-06-07 13:37:45 +01:00
}
2023-11-09 19:22:47 +01:00
cliBuildParameters , err := asWorkspaceBuildParameters ( parameterFlags . richParameters )
2023-08-09 13:00:25 +02:00
if err != nil {
return xerrors . Errorf ( "can't parse given parameter values: %w" , err )
}
2024-04-29 11:23:54 -07:00
cliBuildParameterDefaults , err := asWorkspaceBuildParameters ( parameterFlags . richParameterDefaults )
if err != nil {
return xerrors . Errorf ( "can't parse given parameter defaults: %w" , err )
}
2023-11-09 19:22:47 +01:00
var sourceWorkspaceParameters [] codersdk . WorkspaceBuildParameter
if copyParametersFrom != "" {
sourceWorkspaceParameters , err = client . WorkspaceBuildParameters ( inv . Context (), sourceWorkspace . LatestBuild . ID )
if err != nil {
return xerrors . Errorf ( "get source workspace build parameters: %w" , err )
}
}
2025-07-28 14:46:04 +01:00
// Get presets for the template version
tvPresets , err := client . TemplateVersionPresets ( inv . Context (), templateVersionID )
if err != nil {
return xerrors . Errorf ( "failed to get presets: %w" , err )
}
var preset * codersdk . Preset
var presetParameters [] codersdk . WorkspaceBuildParameter
// If the template has no presets, or the user explicitly used --preset none,
// skip applying a preset
if len ( tvPresets ) > 0 && strings . ToLower ( presetName ) != PresetNone {
// Attempt to resolve which preset to use
preset , err = resolvePreset ( tvPresets , presetName )
if err != nil {
if ! errors . Is ( err , ErrNoPresetFound ) {
return xerrors . Errorf ( "unable to resolve preset: %w" , err )
}
// If no preset found, prompt the user to choose a preset
if preset , err = promptPresetSelection ( inv , tvPresets ); err != nil {
return xerrors . Errorf ( "unable to prompt user for preset: %w" , err )
}
}
// Convert preset parameters into workspace build parameters
presetParameters = presetParameterAsWorkspaceBuildParameters ( preset . Parameters )
// Inform the user which preset was applied and its parameters
displayAppliedPreset ( inv , preset , presetParameters )
} else {
// Inform the user that no preset was applied
_ , _ = fmt . Fprintf ( inv . Stdout , "%s" , cliui . Bold ( "No preset applied." ))
}
2023-08-09 13:00:25 +02:00
richParameters , err := prepWorkspaceBuild ( inv , client , prepWorkspaceBuildArgs {
2023-11-02 14:41:34 -05:00
Action : WorkspaceCreate ,
2023-11-09 19:22:47 +01:00
TemplateVersionID : templateVersionID ,
2023-11-02 14:41:34 -05:00
NewWorkspaceName : workspaceName ,
2023-08-09 13:00:25 +02:00
2025-07-28 14:46:04 +01:00
PresetParameters : presetParameters ,
2024-04-29 11:23:54 -07:00
RichParameterFile : parameterFlags . richParameterFile ,
RichParameters : cliBuildParameters ,
RichParameterDefaults : cliBuildParameterDefaults ,
2023-11-09 19:22:47 +01:00
SourceWorkspaceParameters : sourceWorkspaceParameters ,
2022-04-11 18:54:30 -05:00
})
2022-02-12 13:34:04 -06:00
if err != nil {
2023-03-23 17:42:20 -05:00
return xerrors . Errorf ( "prepare build: %w" , err )
2022-02-12 13:34:04 -06:00
}
2023-03-23 17:42:20 -05:00
_ , err = cliui . Prompt ( inv , cliui . PromptOptions {
2022-04-11 18:54:30 -05:00
Text : "Confirm create?" ,
2022-02-12 13:34:04 -06:00
IsConfirm : true ,
})
if err != nil {
return err
}
2023-03-17 18:14:46 +01:00
var ttlMillis * int64
if stopAfter > 0 {
ttlMillis = ptr . Ref ( stopAfter . Milliseconds ())
}
2025-07-28 14:46:04 +01:00
req := codersdk . CreateWorkspaceRequest {
2023-11-09 19:22:47 +01:00
TemplateVersionID : templateVersionID ,
2023-01-23 15:01:22 +01:00
Name : workspaceName ,
AutostartSchedule : schedSpec ,
2023-03-17 18:14:46 +01:00
TTLMillis : ttlMillis ,
2023-08-09 13:00:25 +02:00
RichParameterValues : richParameters ,
2023-10-06 13:27:12 +04:00
AutomaticUpdates : codersdk . AutomaticUpdates ( autoUpdates ),
2025-07-28 14:46:04 +01:00
}
// If a preset exists, update the create workspace request's preset ID
if preset != nil {
req . TemplateVersionPresetID = preset . ID
}
workspace , err := client . CreateUserWorkspace ( inv . Context (), workspaceOwner , req )
2022-02-12 13:34:04 -06:00
if err != nil {
2023-03-23 17:42:20 -05:00
return xerrors . Errorf ( "create workspace: %w" , err )
2022-02-12 13:34:04 -06:00
}
2022-04-14 13:23:20 -04:00
2024-12-02 20:54:32 +00:00
cliutil . WarnMatchedProvisioners ( inv . Stderr , workspace . LatestBuild . MatchedProvisioners , workspace . LatestBuild . Job )
2023-03-23 17:42:20 -05:00
err = cliui . WorkspaceBuild ( inv . Context (), inv . Stdout , client , workspace . LatestBuild . ID )
2022-04-11 18:54:30 -05:00
if err != nil {
2023-03-23 17:42:20 -05:00
return xerrors . Errorf ( "watch build: %w" , err )
2022-04-11 18:54:30 -05:00
}
2022-04-14 13:23:20 -04:00
2023-09-07 17:28:22 -04:00
_ , _ = fmt . Fprintf (
inv . Stdout ,
"\nThe %s workspace has been created at %s!\n" ,
cliui . Keyword ( workspace . Name ),
cliui . Timestamp ( time . Now ()),
)
2022-04-11 18:54:30 -05:00
return nil
2022-02-12 13:34:04 -06:00
},
}
2023-03-23 17:42:20 -05:00
cmd . Options = append ( cmd . Options ,
2024-03-15 11:24:38 -05:00
serpent . Option {
2023-03-23 17:42:20 -05:00
Flag : "template" ,
FlagShorthand : "t" ,
Env : "CODER_TEMPLATE_NAME" ,
Description : "Specify a template name." ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & templateName ),
2023-03-23 17:42:20 -05:00
},
2024-10-11 18:30:11 +05:30
serpent . Option {
Flag : "template-version" ,
Env : "CODER_TEMPLATE_VERSION" ,
Description : "Specify a template version name." ,
Value : serpent . StringOf ( & templateVersion ),
},
2025-07-28 14:46:04 +01:00
serpent . Option {
Flag : "preset" ,
Env : "CODER_PRESET_NAME" ,
Description : "Specify the name of a template version preset. Use 'none' to explicitly indicate that no preset should be used." ,
Value : serpent . StringOf ( & presetName ),
},
2024-03-15 11:24:38 -05:00
serpent . Option {
2023-03-23 17:42:20 -05:00
Flag : "start-at" ,
Env : "CODER_WORKSPACE_START_AT" ,
Description : "Specify the workspace autostart schedule. Check coder schedule start --help for the syntax." ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & startAt ),
2023-03-23 17:42:20 -05:00
},
2024-03-15 11:24:38 -05:00
serpent . Option {
2023-03-23 17:42:20 -05:00
Flag : "stop-after" ,
Env : "CODER_WORKSPACE_STOP_AFTER" ,
Description : "Specify a duration after which the workspace should shut down (e.g. 8h)." ,
2024-03-15 11:24:38 -05:00
Value : serpent . DurationOf ( & stopAfter ),
2023-03-23 17:42:20 -05:00
},
2024-03-15 11:24:38 -05:00
serpent . Option {
2023-10-06 13:27:12 +04:00
Flag : "automatic-updates" ,
Env : "CODER_WORKSPACE_AUTOMATIC_UPDATES" ,
Description : "Specify automatic updates setting for the workspace (accepts 'always' or 'never')." ,
Default : string ( codersdk . AutomaticUpdatesNever ),
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & autoUpdates ),
2023-10-06 13:27:12 +04:00
},
2024-03-15 11:24:38 -05:00
serpent . Option {
2023-11-09 19:22:47 +01:00
Flag : "copy-parameters-from" ,
Env : "CODER_WORKSPACE_COPY_PARAMETERS_FROM" ,
Description : "Specify the source workspace name to copy parameters from." ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & copyParametersFrom ),
2023-11-09 19:22:47 +01:00
},
2023-03-23 17:42:20 -05:00
cliui . SkipPromptOption (),
)
2023-08-09 13:00:25 +02:00
cmd . Options = append ( cmd . Options , parameterFlags . cliParameters () ... )
2024-04-29 11:23:54 -07:00
cmd . Options = append ( cmd . Options , parameterFlags . cliParameterDefaults () ... )
2024-07-01 11:04:45 -10:00
orgContext . AttachOptions ( cmd )
2022-02-12 13:34:04 -06:00
return cmd
}
2022-06-27 11:19:10 -05:00
type prepWorkspaceBuildArgs struct {
2023-11-02 14:41:34 -05:00
Action WorkspaceCLIAction
TemplateVersionID uuid . UUID
NewWorkspaceName string
2023-01-23 15:01:22 +01:00
2023-11-09 19:22:47 +01:00
LastBuildParameters [] codersdk . WorkspaceBuildParameter
SourceWorkspaceParameters [] codersdk . WorkspaceBuildParameter
2023-01-23 15:01:22 +01:00
2024-10-16 23:54:12 +02:00
PromptEphemeralParameters bool
EphemeralParameters [] codersdk . WorkspaceBuildParameter
2023-08-09 13:00:25 +02:00
2025-07-28 14:46:04 +01:00
PresetParameters [] codersdk . WorkspaceBuildParameter
2024-04-29 11:23:54 -07:00
PromptRichParameters bool
RichParameters [] codersdk . WorkspaceBuildParameter
RichParameterFile string
RichParameterDefaults [] codersdk . WorkspaceBuildParameter
2022-06-27 11:19:10 -05:00
}
2025-07-28 14:46:04 +01:00
// resolvePreset returns the preset matching the given presetName (if specified),
// or the default preset (if any).
// Returns ErrNoPresetFound if no matching or default preset is found.
func resolvePreset ( presets [] codersdk . Preset , presetName string ) ( * codersdk . Preset , error ) {
// If preset name is specified, find it
if presetName != "" {
for _ , p := range presets {
if p . Name == presetName {
return & p , nil
}
}
return nil , xerrors . Errorf ( "preset %q not found" , presetName )
}
// No preset name specified, search for the default preset
for _ , p := range presets {
if p . Default {
return & p , nil
}
}
// No preset found
return nil , ErrNoPresetFound
}
// promptPresetSelection shows a CLI selection menu of the presets defined in the template version.
// Returns the selected preset
func promptPresetSelection ( inv * serpent . Invocation , presets [] codersdk . Preset ) ( * codersdk . Preset , error ) {
presetMap := make ( map [ string ] * codersdk . Preset )
var presetOptions [] string
for _ , preset := range presets {
2025-07-29 16:59:26 +01:00
var option string
if preset . Description == "" {
option = preset . Name
} else {
option = fmt . Sprintf ( "%s: %s" , preset . Name , preset . Description )
}
2025-07-28 14:46:04 +01:00
presetOptions = append ( presetOptions , option )
presetMap [ option ] = & preset
}
// Show selection UI
_ , _ = fmt . Fprintln ( inv . Stdout , pretty . Sprint ( cliui . DefaultStyles . Wrap , "Select a preset below:" ))
selected , err := cliui . Select ( inv , cliui . SelectOptions {
Options : presetOptions ,
HideSearch : true ,
})
if err != nil {
return nil , xerrors . Errorf ( "failed to select preset: %w" , err )
}
return presetMap [ selected ], nil
}
// displayAppliedPreset shows the user which preset was applied and its parameters
func displayAppliedPreset ( inv * serpent . Invocation , preset * codersdk . Preset , parameters [] codersdk . WorkspaceBuildParameter ) {
label := fmt . Sprintf ( "Preset '%s'" , preset . Name )
if preset . Default {
label += " (default)"
}
_ , _ = fmt . Fprintf ( inv . Stdout , "%s applied:\n" , cliui . Bold ( label ))
for _ , param := range parameters {
_ , _ = fmt . Fprintf ( inv . Stdout , " %s: '%s'\n" , cliui . Bold ( param . Name ), param . Value )
}
}
2022-06-27 11:19:10 -05:00
// prepWorkspaceBuild will ensure a workspace build will succeed on the latest template version.
2023-08-09 13:00:25 +02:00
// Any missing params will be prompted to the user. It supports rich parameters.
2024-03-15 11:24:38 -05:00
func prepWorkspaceBuild ( inv * serpent . Invocation , client * codersdk . Client , args prepWorkspaceBuildArgs ) ([] codersdk . WorkspaceBuildParameter , error ) {
2023-03-23 17:42:20 -05:00
ctx := inv . Context ()
2023-02-02 16:44:57 +01:00
2023-11-02 14:41:34 -05:00
templateVersion , err := client . TemplateVersion ( ctx , args . TemplateVersionID )
2022-06-27 11:19:10 -05:00
if err != nil {
2023-08-09 13:00:25 +02:00
return nil , xerrors . Errorf ( "get template version: %w" , err )
2022-06-27 11:19:10 -05:00
}
2023-01-23 15:01:22 +01:00
2023-03-23 17:42:20 -05:00
templateVersionParameters , err := client . TemplateVersionRichParameters ( inv . Context (), templateVersion . ID )
2023-01-23 15:01:22 +01:00
if err != nil {
return nil , xerrors . Errorf ( "get template version rich parameters: %w" , err )
}
2023-08-09 13:00:25 +02:00
parameterFile := map [ string ] string {}
2023-01-23 15:01:22 +01:00
if args . RichParameterFile != "" {
2023-08-09 13:00:25 +02:00
parameterFile , err = parseParameterMapFile ( args . RichParameterFile )
2023-01-23 15:01:22 +01:00
if err != nil {
2023-08-09 13:00:25 +02:00
return nil , xerrors . Errorf ( "can't parse parameter map file: %w" , err )
2023-01-23 15:01:22 +01:00
}
}
2023-07-13 12:56:02 +02:00
2023-08-09 13:00:25 +02:00
resolver := new ( ParameterResolver ).
WithLastBuildParameters ( args . LastBuildParameters ).
2023-11-09 19:22:47 +01:00
WithSourceWorkspaceParameters ( args . SourceWorkspaceParameters ).
2024-10-16 23:54:12 +02:00
WithPromptEphemeralParameters ( args . PromptEphemeralParameters ).
WithEphemeralParameters ( args . EphemeralParameters ).
2025-07-28 14:46:04 +01:00
WithPresetParameters ( args . PresetParameters ).
2023-08-09 13:00:25 +02:00
WithPromptRichParameters ( args . PromptRichParameters ).
WithRichParameters ( args . RichParameters ).
2024-04-29 11:23:54 -07:00
WithRichParametersFile ( parameterFile ).
WithRichParametersDefaults ( args . RichParameterDefaults )
2023-08-09 13:00:25 +02:00
buildParameters , err := resolver . Resolve ( inv , args . Action , templateVersionParameters )
if err != nil {
return nil , err
2023-01-23 15:01:22 +01:00
}
2022-06-27 11:19:10 -05:00
2023-10-03 09:04:39 -05:00
err = cliui . ExternalAuth ( ctx , inv . Stdout , cliui . ExternalAuthOptions {
2023-09-29 14:13:20 -05:00
Fetch : func ( ctx context . Context ) ([] codersdk . TemplateVersionExternalAuth , error ) {
return client . TemplateVersionExternalAuth ( ctx , templateVersion . ID )
2023-02-27 10:18:19 -06:00
},
})
if err != nil {
return nil , xerrors . Errorf ( "template version git auth: %w" , err )
}
2022-06-27 11:19:10 -05:00
// Run a dry-run with the given parameters to check correctness
2023-03-23 17:42:20 -05:00
dryRun , err := client . CreateTemplateVersionDryRun ( inv . Context (), templateVersion . ID , codersdk . CreateTemplateVersionDryRunRequest {
2023-01-23 15:01:22 +01:00
WorkspaceName : args . NewWorkspaceName ,
2023-08-09 13:00:25 +02:00
RichParameterValues : buildParameters ,
2022-06-27 11:19:10 -05:00
})
if err != nil {
return nil , xerrors . Errorf ( "begin workspace dry-run: %w" , err )
}
2024-12-02 20:54:32 +00:00
matchedProvisioners , err := client . TemplateVersionDryRunMatchedProvisioners ( inv . Context (), templateVersion . ID , dryRun . ID )
if err != nil {
return nil , xerrors . Errorf ( "get matched provisioners: %w" , err )
}
cliutil . WarnMatchedProvisioners ( inv . Stdout , & matchedProvisioners , dryRun )
2023-03-23 17:42:20 -05:00
_ , _ = fmt . Fprintln ( inv . Stdout , "Planning workspace..." )
err = cliui . ProvisionerJob ( inv . Context (), inv . Stdout , cliui . ProvisionerJobOptions {
2022-06-27 11:19:10 -05:00
Fetch : func () ( codersdk . ProvisionerJob , error ) {
2023-03-23 17:42:20 -05:00
return client . TemplateVersionDryRun ( inv . Context (), templateVersion . ID , dryRun . ID )
2022-06-27 11:19:10 -05:00
},
Cancel : func () error {
2023-03-23 17:42:20 -05:00
return client . CancelTemplateVersionDryRun ( inv . Context (), templateVersion . ID , dryRun . ID )
2022-06-27 11:19:10 -05:00
},
2022-09-22 13:26:05 -05:00
Logs : func () ( <- chan codersdk . ProvisionerJobLog , io . Closer , error ) {
2023-03-23 17:42:20 -05:00
return client . TemplateVersionDryRunLogsAfter ( inv . Context (), templateVersion . ID , dryRun . ID , 0 )
2022-06-27 11:19:10 -05:00
},
// Don't show log output for the dry-run unless there's an error.
Silent : true ,
})
if err != nil {
// TODO (Dean): reprompt for parameter values if we deem it to
// be a validation error
return nil , xerrors . Errorf ( "dry-run workspace: %w" , err )
}
2023-03-23 17:42:20 -05:00
resources , err := client . TemplateVersionDryRunResources ( inv . Context (), templateVersion . ID , dryRun . ID )
2022-06-27 11:19:10 -05:00
if err != nil {
return nil , xerrors . Errorf ( "get workspace dry-run resources: %w" , err )
}
2023-03-23 17:42:20 -05:00
err = cliui . WorkspaceResources ( inv . Stdout , resources , cliui . WorkspaceResourcesOptions {
2022-06-27 11:19:10 -05:00
WorkspaceName : args . NewWorkspaceName ,
// Since agents haven't connected yet, hiding this makes more sense.
HideAgentState : true ,
Title : "Workspace Preview" ,
})
if err != nil {
2023-03-23 17:42:20 -05:00
return nil , xerrors . Errorf ( "get resources: %w" , err )
2022-06-27 11:19:10 -05:00
}
2023-08-09 13:00:25 +02:00
return buildParameters , nil
2023-04-04 14:22:46 +02:00
}