2022-02-10 08:33:27 -06:00
package cli
import (
"fmt"
2022-09-22 13:26:05 -05:00
"io"
2022-02-10 08:33:27 -06:00
"os"
"path/filepath"
2022-04-11 18:54:30 -05:00
"strings"
2022-02-10 08:33:27 -06:00
"time"
2022-09-07 13:01:18 -07:00
"unicode/utf8"
2022-02-10 08:33:27 -06:00
"github.com/briandowns/spinner"
2022-10-13 18:02:52 -05:00
"github.com/google/uuid"
2022-02-10 08:33:27 -06:00
"github.com/spf13/cobra"
"golang.org/x/xerrors"
2022-03-22 13:17:50 -06:00
"github.com/coder/coder/cli/cliui"
2022-03-25 16:07:45 -05:00
"github.com/coder/coder/coderd/database"
2022-06-07 13:37:45 +01:00
"github.com/coder/coder/coderd/util/ptr"
2022-02-10 08:33:27 -06:00
"github.com/coder/coder/codersdk"
2022-02-12 13:34:04 -06:00
"github.com/coder/coder/provisionerd"
2022-03-22 13:17:50 -06:00
"github.com/coder/coder/provisionersdk"
2022-02-10 08:33:27 -06:00
)
2022-04-06 12:42:40 -05:00
func templateCreate () * cobra . Command {
2022-02-12 13:34:04 -06:00
var (
2022-11-16 16:34:06 -06:00
directory string
provisioner string
provisionerTags [] string
parameterFile string
defaultTTL time . Duration
2022-02-12 13:34:04 -06:00
)
cmd := & cobra . Command {
2022-04-14 13:23:20 -04:00
Use : "create [name]" ,
2022-05-12 14:54:58 +03:00
Short : "Create a template from the current directory or as specified by flag" ,
Args : cobra . MaximumNArgs ( 1 ),
2022-02-10 08:33:27 -06:00
RunE : func ( cmd * cobra . Command , args [] string ) error {
2022-08-23 13:55:39 -07:00
client , err := CreateClient ( cmd )
2022-02-10 08:33:27 -06:00
if err != nil {
return err
}
2022-04-14 13:23:20 -04:00
2022-10-27 16:49:35 -05:00
organization , err := CurrentOrganization ( cmd , client )
2022-02-10 08:33:27 -06:00
if err != nil {
return err
}
2022-03-22 13:17:50 -06:00
2022-04-06 12:42:40 -05:00
var templateName string
2022-03-22 13:17:50 -06:00
if len ( args ) == 0 {
2022-04-06 12:42:40 -05:00
templateName = filepath . Base ( directory )
2022-03-22 13:17:50 -06:00
} else {
2022-04-06 12:42:40 -05:00
templateName = args [ 0 ]
2022-03-22 13:17:50 -06:00
}
2022-04-14 13:23:20 -04:00
2022-09-07 13:01:18 -07:00
if utf8 . RuneCountInString ( templateName ) > 31 {
return xerrors . Errorf ( "Template name must be less than 32 characters" )
}
2022-04-06 12:42:40 -05:00
_ , err = client . TemplateByName ( cmd . Context (), organization . ID , templateName )
2022-03-22 13:17:50 -06:00
if err == nil {
2022-04-06 12:42:40 -05:00
return xerrors . Errorf ( "A template already exists named %q!" , templateName )
2022-03-22 13:17:50 -06:00
}
2022-05-12 14:54:58 +03:00
// Confirm upload of the directory.
prettyDir := prettyDirectoryPath ( directory )
2022-04-11 18:54:30 -05:00
_ , err = cliui . Prompt ( cmd , cliui . PromptOptions {
2022-05-12 14:54:58 +03:00
Text : fmt . Sprintf ( "Create and upload %q?" , prettyDir ),
2022-04-11 18:54:30 -05:00
IsConfirm : true ,
2022-07-12 10:36:07 -07:00
Default : cliui . ConfirmYes ,
2022-04-11 18:54:30 -05:00
})
if err != nil {
return err
}
2022-03-22 13:17:50 -06:00
spin := spinner . New ( spinner . CharSets [ 5 ], 100 * time . Millisecond )
spin . Writer = cmd . OutOrStdout ()
2022-05-12 14:54:58 +03:00
spin . Suffix = cliui . Styles . Keyword . Render ( " Uploading directory..." )
2022-03-22 13:17:50 -06:00
spin . Start ()
defer spin . Stop ()
2022-04-11 18:54:30 -05:00
archive , err := provisionersdk . Tar ( directory , provisionersdk . TemplateArchiveLimit )
2022-02-10 08:33:27 -06:00
if err != nil {
return err
}
2022-03-22 13:17:50 -06:00
resp , err := client . Upload ( cmd . Context (), codersdk . ContentTypeTar , archive )
if err != nil {
return err
}
spin . Stop ()
2022-11-16 16:34:06 -06:00
tags , err := ParseProvisionerTags ( provisionerTags )
if err != nil {
return err
}
2022-06-17 12:22:28 -05:00
job , _ , err := createValidTemplateVersion ( cmd , createValidTemplateVersionArgs {
2022-11-16 16:34:06 -06:00
Client : client ,
Organization : organization ,
Provisioner : database . ProvisionerType ( provisioner ),
FileID : resp . ID ,
ParameterFile : parameterFile ,
ProvisionerTags : tags ,
2022-06-17 12:22:28 -05:00
})
2022-03-22 13:17:50 -06:00
if err != nil {
return err
}
2022-05-20 10:59:04 -05:00
_ , err = cliui . Prompt ( cmd , cliui . PromptOptions {
Text : "Confirm create?" ,
IsConfirm : true ,
})
if err != nil {
return err
2022-02-10 08:33:27 -06:00
}
2022-02-12 13:34:04 -06:00
2022-06-07 13:37:45 +01:00
createReq := codersdk . CreateTemplateRequest {
2022-11-09 14:36:25 -05:00
Name : templateName ,
VersionID : job . ID ,
DefaultTTLMillis : ptr . Ref ( defaultTTL . Milliseconds ()),
2022-06-07 13:37:45 +01:00
}
_ , err = client . CreateTemplate ( cmd . Context (), organization . ID , createReq )
2022-02-12 13:34:04 -06:00
if err != nil {
return err
2022-02-10 08:33:27 -06:00
}
2022-04-11 18:54:30 -05:00
_ , _ = fmt . Fprintln ( cmd . OutOrStdout (), "\n" + cliui . Styles . Wrap . Render (
2022-07-08 14:27:56 -05:00
"The " + cliui . Styles . Keyword . Render ( templateName ) + " template has been created at " + cliui . Styles . DateTimeStamp . Render ( time . Now (). Format ( time . Stamp )) + "! " +
2022-04-11 18:54:30 -05:00
"Developers can provision a workspace with this template using:" ) + "\n" )
2022-05-02 11:08:52 -05:00
_ , _ = fmt . Fprintln ( cmd . OutOrStdout (), " " + cliui . Styles . Code . Render ( fmt . Sprintf ( "coder create --template=%q [workspace name]" , templateName )))
2022-04-11 18:54:30 -05:00
_ , _ = fmt . Fprintln ( cmd . OutOrStdout ())
2022-02-10 08:33:27 -06:00
return nil
},
}
2022-02-12 13:34:04 -06:00
currentDirectory , _ := os . Getwd ()
cmd . Flags (). StringVarP ( & directory , "directory" , "d" , currentDirectory , "Specify the directory to create from" )
2022-05-12 14:54:58 +03:00
cmd . Flags (). StringVarP ( & provisioner , "test.provisioner" , "" , "terraform" , "Customize the provisioner backend" )
2022-05-20 11:29:10 -04:00
cmd . Flags (). StringVarP ( & parameterFile , "parameter-file" , "" , "" , "Specify a file path with parameter values." )
2022-11-16 16:34:06 -06:00
cmd . Flags (). StringArrayVarP ( & provisionerTags , "provisioner-tag" , "" , [] string {}, "Specify a set of tags to target provisioner daemons." )
2022-11-09 14:36:25 -05:00
cmd . Flags (). DurationVarP ( & defaultTTL , "default-ttl" , "" , 24 * time . Hour , "Specify a default TTL for workspaces created from this template." )
2022-02-12 13:34:04 -06:00
// This is for testing!
2022-05-12 14:54:58 +03:00
err := cmd . Flags (). MarkHidden ( "test.provisioner" )
2022-02-12 13:34:04 -06:00
if err != nil {
panic ( err )
}
2022-05-20 10:59:04 -05:00
cliui . AllowSkipPrompt ( cmd )
2022-02-12 13:34:04 -06:00
return cmd
}
2022-06-17 12:22:28 -05:00
type createValidTemplateVersionArgs struct {
2022-09-23 20:17:36 -05:00
Name string
2022-06-17 12:22:28 -05:00
Client * codersdk . Client
Organization codersdk . Organization
Provisioner database . ProvisionerType
2022-10-13 18:02:52 -05:00
FileID uuid . UUID
2022-06-17 12:22:28 -05:00
ParameterFile string
// Template is only required if updating a template's active version.
Template * codersdk . Template
// ReuseParameters will attempt to reuse params from the Template field
// before prompting the user. Set to false to always prompt for param
// values.
ReuseParameters bool
2022-11-16 16:34:06 -06:00
ProvisionerTags map [ string ] string
2022-06-17 12:22:28 -05:00
}
func createValidTemplateVersion ( cmd * cobra . Command , args createValidTemplateVersionArgs , parameters ... codersdk . CreateParameterRequest ) ( * codersdk . TemplateVersion , [] codersdk . CreateParameterRequest , error ) {
client := args . Client
req := codersdk . CreateTemplateVersionRequest {
2022-09-23 20:17:36 -05:00
Name : args . Name ,
2022-05-19 13:04:44 -05:00
StorageMethod : codersdk . ProvisionerStorageMethodFile ,
2022-10-13 18:02:52 -05:00
FileID : args . FileID ,
2022-06-17 12:22:28 -05:00
Provisioner : codersdk . ProvisionerType ( args . Provisioner ),
2022-02-12 13:34:04 -06:00
ParameterValues : parameters ,
2022-11-16 16:34:06 -06:00
ProvisionerTags : args . ProvisionerTags ,
2022-06-17 12:22:28 -05:00
}
if args . Template != nil {
req . TemplateID = args . Template . ID
}
version , err := client . CreateTemplateVersion ( cmd . Context (), args . Organization . ID , req )
2022-02-12 13:34:04 -06:00
if err != nil {
2022-03-22 13:17:50 -06:00
return nil , nil , err
2022-02-12 13:34:04 -06:00
}
2022-03-30 17:59:54 -05:00
err = cliui . ProvisionerJob ( cmd . Context (), cmd . OutOrStdout (), cliui . ProvisionerJobOptions {
2022-03-22 13:17:50 -06:00
Fetch : func () ( codersdk . ProvisionerJob , error ) {
2022-04-06 12:42:40 -05:00
version , err := client . TemplateVersion ( cmd . Context (), version . ID )
2022-03-22 13:17:50 -06:00
return version . Job , err
},
Cancel : func () error {
2022-04-06 12:42:40 -05:00
return client . CancelTemplateVersion ( cmd . Context (), version . ID )
2022-03-22 13:17:50 -06:00
},
2022-09-22 13:26:05 -05:00
Logs : func () ( <- chan codersdk . ProvisionerJobLog , io . Closer , error ) {
2022-11-06 18:50:34 -08:00
return client . TemplateVersionLogsAfter ( cmd . Context (), version . ID , 0 )
2022-03-22 13:17:50 -06:00
},
})
if err != nil {
2022-03-28 12:43:22 -06:00
if ! provisionerd . IsMissingParameterError ( err . Error ()) {
return nil , nil , err
}
2022-03-22 13:17:50 -06:00
}
2022-04-06 12:42:40 -05:00
version , err = client . TemplateVersion ( cmd . Context (), version . ID )
2022-02-12 13:34:04 -06:00
if err != nil {
2022-03-22 13:17:50 -06:00
return nil , nil , err
2022-02-12 13:34:04 -06:00
}
2022-04-06 12:42:40 -05:00
parameterSchemas , err := client . TemplateVersionSchema ( cmd . Context (), version . ID )
2022-02-12 13:34:04 -06:00
if err != nil {
2022-03-22 13:17:50 -06:00
return nil , nil , err
2022-02-12 13:34:04 -06:00
}
2022-04-06 12:42:40 -05:00
parameterValues , err := client . TemplateVersionParameters ( cmd . Context (), version . ID )
2022-02-12 13:34:04 -06:00
if err != nil {
2022-03-22 13:17:50 -06:00
return nil , nil , err
2022-02-12 13:34:04 -06:00
}
2022-06-17 12:22:28 -05:00
// lastParameterValues are pulled from the current active template version if
// templateID is provided. This allows pulling params from the last
// version instead of prompting if we are updating template versions.
lastParameterValues := make ( map [ string ] codersdk . Parameter )
if args . ReuseParameters && args . Template != nil {
activeVersion , err := client . TemplateVersion ( cmd . Context (), args . Template . ActiveVersionID )
if err != nil {
return nil , nil , xerrors . Errorf ( "Fetch current active template version: %w" , err )
}
// We don't want to compute the params, we only want to copy from this scope
values , err := client . Parameters ( cmd . Context (), codersdk . ParameterImportJob , activeVersion . Job . ID )
if err != nil {
return nil , nil , xerrors . Errorf ( "Fetch previous version parameters: %w" , err )
}
for _ , value := range values {
lastParameterValues [ value . Name ] = value
}
}
2022-03-07 11:40:54 -06:00
if provisionerd . IsMissingParameterError ( version . Job . Error ) {
2022-06-17 15:20:13 -05:00
valuesBySchemaID := map [ string ] codersdk . ComputedParameter {}
2022-02-12 13:34:04 -06:00
for _ , parameterValue := range parameterValues {
valuesBySchemaID [ parameterValue . SchemaID . String ()] = parameterValue
}
2022-06-17 12:22:28 -05:00
// parameterMapFromFile can be nil if parameter file is not specified
var parameterMapFromFile map [ string ] string
if args . ParameterFile != "" {
_ , _ = fmt . Fprintln ( cmd . OutOrStdout (), cliui . Styles . Paragraph . Render ( "Attempting to read the variables from the parameter file." ) + "\r\n" )
parameterMapFromFile , err = createParameterMapFromFile ( args . ParameterFile )
if err != nil {
return nil , nil , err
}
}
// pulled params come from the last template version
pulled := make ([] string , 0 )
2022-05-19 08:29:36 -05:00
missingSchemas := make ([] codersdk . ParameterSchema , 0 )
2022-02-12 13:34:04 -06:00
for _ , parameterSchema := range parameterSchemas {
_ , ok := valuesBySchemaID [ parameterSchema . ID . String ()]
if ok {
continue
}
2022-06-17 12:22:28 -05:00
// The file values are handled below. So don't handle them here,
// just check if a value is present in the file.
_ , fileOk := parameterMapFromFile [ parameterSchema . Name ]
if inherit , ok := lastParameterValues [ parameterSchema . Name ]; ok && ! fileOk {
// If the value is not in the param file, and can be pulled from the last template version,
// then don't mark it as missing.
parameters = append ( parameters , codersdk . CreateParameterRequest {
CloneID : inherit . ID ,
})
pulled = append ( pulled , fmt . Sprintf ( "%q" , parameterSchema . Name ))
continue
}
2022-03-22 13:17:50 -06:00
missingSchemas = append ( missingSchemas , parameterSchema )
}
2022-06-17 12:22:28 -05:00
_ , _ = fmt . Fprintln ( cmd . OutOrStdout (), cliui . Styles . Paragraph . Render ( "This template has required variables! They are scoped to the template, and not viewable after being set." ))
if len ( pulled ) > 0 {
_ , _ = fmt . Fprintln ( cmd . OutOrStdout (), cliui . Styles . Paragraph . Render ( fmt . Sprintf ( "The following parameter values are being pulled from the latest template version: %s." , strings . Join ( pulled , ", " ))))
_ , _ = fmt . Fprintln ( cmd . OutOrStdout (), cliui . Styles . Paragraph . Render ( "Use \"--always-prompt\" flag to change the values." ))
2022-05-20 11:29:10 -04:00
}
2022-06-17 12:22:28 -05:00
_ , _ = fmt . Fprint ( cmd . OutOrStdout (), "\r\n" )
2022-03-22 13:17:50 -06:00
for _ , parameterSchema := range missingSchemas {
2022-05-20 11:29:10 -04:00
parameterValue , err := getParameterValueFromMapOrInput ( cmd , parameterMapFromFile , parameterSchema )
2022-02-12 13:34:04 -06:00
if err != nil {
2022-03-22 13:17:50 -06:00
return nil , nil , err
2022-02-12 13:34:04 -06:00
}
2022-03-22 13:17:50 -06:00
parameters = append ( parameters , codersdk . CreateParameterRequest {
2022-02-12 13:34:04 -06:00
Name : parameterSchema . Name ,
2022-05-20 11:29:10 -04:00
SourceValue : parameterValue ,
2022-05-19 13:04:44 -05:00
SourceScheme : codersdk . ParameterSourceSchemeData ,
DestinationScheme : parameterSchema . DefaultDestinationScheme ,
2022-02-12 13:34:04 -06:00
})
2022-03-22 13:17:50 -06:00
_ , _ = fmt . Fprintln ( cmd . OutOrStdout ())
2022-02-12 13:34:04 -06:00
}
2022-05-20 11:29:10 -04:00
// This recursion is only 1 level deep in practice.
// The first pass populates the missing parameters, so it does not enter this `if` block again.
2022-06-17 12:22:28 -05:00
return createValidTemplateVersion ( cmd , args , parameters ... )
2022-02-12 13:34:04 -06:00
}
2022-03-22 13:17:50 -06:00
if version . Job . Status != codersdk . ProvisionerJobSucceeded {
return nil , nil , xerrors . New ( version . Job . Error )
2022-02-12 13:34:04 -06:00
}
2022-04-06 12:42:40 -05:00
resources , err := client . TemplateVersionResources ( cmd . Context (), version . ID )
2022-02-12 13:34:04 -06:00
if err != nil {
2022-03-22 13:17:50 -06:00
return nil , nil , err
2022-02-12 13:34:04 -06:00
}
2022-04-14 13:23:20 -04:00
2022-06-16 11:36:11 -07:00
// Only display the resources on the start transition, to avoid listing them more than once.
var startResources [] codersdk . WorkspaceResource
for _ , r := range resources {
if r . Transition == codersdk . WorkspaceTransitionStart {
startResources = append ( startResources , r )
}
}
err = cliui . WorkspaceResources ( cmd . OutOrStdout (), startResources , cliui . WorkspaceResourcesOptions {
2022-04-11 18:54:30 -05:00
HideAgentState : true ,
HideAccess : true ,
Title : "Template Preview" ,
})
2022-04-14 13:23:20 -04:00
if err != nil {
return nil , nil , xerrors . Errorf ( "preview template resources: %w" , err )
}
return & version , parameters , nil
2022-02-10 08:33:27 -06:00
}
2022-05-12 14:54:58 +03:00
// prettyDirectoryPath returns a prettified path when inside the users
// home directory. Falls back to dir if the users home directory cannot
// discerned. This function calls filepath.Clean on the result.
func prettyDirectoryPath ( dir string ) string {
dir = filepath . Clean ( dir )
homeDir , err := os . UserHomeDir ()
if err != nil {
return dir
}
pretty := dir
if strings . HasPrefix ( pretty , homeDir ) {
pretty = strings . TrimPrefix ( pretty , homeDir )
pretty = "~" + pretty
}
return pretty
}
2022-11-16 16:34:06 -06:00
func ParseProvisionerTags ( rawTags [] string ) ( map [ string ] string , error ) {
tags := map [ string ] string {}
for _ , rawTag := range rawTags {
parts := strings . SplitN ( rawTag , "=" , 2 )
if len ( parts ) < 2 {
return nil , xerrors . Errorf ( "invalid tag format for %q. must be key=value" , rawTag )
}
tags [ parts [ 0 ]] = parts [ 1 ]
}
return tags , nil
}