2022-02-10 08:33:27 -06:00
package cli
import (
2023-03-08 16:32:00 +01:00
"errors"
2022-02-10 08:33:27 -06:00
"fmt"
2022-09-22 13:26:05 -05:00
"io"
2023-05-10 12:57:11 -07:00
"net/http"
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
2022-10-13 18:02:52 -05:00
"github.com/google/uuid"
2022-02-10 08:33:27 -06:00
"golang.org/x/xerrors"
2023-03-23 17:42:20 -05:00
"github.com/coder/coder/cli/clibase"
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-02-10 08:33:27 -06:00
)
2023-03-23 17:42:20 -05:00
func ( r * RootCmd ) templateCreate () * clibase . Cmd {
2022-02-12 13:34:04 -06:00
var (
2022-11-16 16:34:06 -06:00
provisioner string
provisionerTags [] string
2023-02-17 09:07:45 +01:00
variablesFile string
variables [] string
2023-06-14 11:08:58 -05:00
disableEveryone bool
2022-11-16 16:34:06 -06:00
defaultTTL time . Duration
2023-05-10 12:57:11 -07:00
failureTTL time . Duration
inactivityTTL time . Duration
2023-01-16 14:32:11 -06:00
uploadFlags templateUploadFlags
2022-02-12 13:34:04 -06:00
)
2023-03-23 17:42:20 -05:00
client := new ( codersdk . Client )
cmd := & clibase . Cmd {
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" ,
2023-03-23 17:42:20 -05:00
Middleware : clibase . Chain (
clibase . RequireRangeArgs ( 0 , 1 ),
r . InitClient ( client ),
),
Handler : func ( inv * clibase . Invocation ) error {
2023-05-10 12:57:11 -07:00
if failureTTL != 0 || inactivityTTL != 0 {
// This call can be removed when workspace_actions is no longer experimental
experiments , exErr := client . Experiments ( inv . Context ())
if exErr != nil {
return xerrors . Errorf ( "get experiments: %w" , exErr )
}
if ! experiments . Enabled ( codersdk . ExperimentWorkspaceActions ) {
return xerrors . Errorf ( "--failure-ttl and --inactivityTTL are experimental features. Use the workspace_actions CODER_EXPERIMENTS flag to set these configuration values." )
}
entitlements , err := client . Entitlements ( inv . Context ())
var sdkErr * codersdk . Error
if xerrors . As ( err , & sdkErr ) && sdkErr . StatusCode () == http . StatusNotFound {
return xerrors . Errorf ( "your deployment appears to be an AGPL deployment, so you cannot set --failure-ttl or --inactivityTTL" )
} else if err != nil {
return xerrors . Errorf ( "get entitlements: %w" , err )
}
if ! entitlements . Features [ codersdk . FeatureAdvancedTemplateScheduling ]. Enabled {
return xerrors . Errorf ( "your license is not entitled to use advanced template scheduling, so you cannot set --failure-ttl or --inactivityTTL" )
}
}
2023-03-23 17:42:20 -05:00
organization , err := CurrentOrganization ( inv , client )
2022-02-10 08:33:27 -06:00
if err != nil {
return err
}
2022-04-14 13:23:20 -04:00
2023-03-23 17:42:20 -05:00
templateName , err := uploadFlags . templateName ( inv . Args )
2023-01-16 14:32:11 -06:00
if err != nil {
return err
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" )
}
2023-03-23 17:42:20 -05:00
_ , err = client . TemplateByName ( inv . 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
}
2023-06-20 10:02:44 -05:00
err = uploadFlags . checkForLockfile ( inv )
if err != nil {
return xerrors . Errorf ( "check for lockfile: %w" , err )
}
2023-07-11 13:11:08 +03:00
message := uploadFlags . templateMessage ( inv )
2022-05-12 14:54:58 +03:00
// Confirm upload of the directory.
2023-03-23 17:42:20 -05:00
resp , err := uploadFlags . upload ( inv , client )
2022-04-11 18:54:30 -05:00
if err != nil {
return err
}
2022-11-16 16:34:06 -06:00
tags , err := ParseProvisionerTags ( provisionerTags )
if err != nil {
return err
}
2023-06-02 11:16:46 +02:00
job , err := createValidTemplateVersion ( inv , createValidTemplateVersionArgs {
2023-07-11 13:11:08 +03:00
Message : message ,
2022-11-16 16:34:06 -06:00
Client : client ,
Organization : organization ,
Provisioner : database . ProvisionerType ( provisioner ),
FileID : resp . ID ,
ProvisionerTags : tags ,
2023-02-17 09:07:45 +01:00
VariablesFile : variablesFile ,
Variables : variables ,
2022-06-17 12:22:28 -05:00
})
2022-03-22 13:17:50 -06:00
if err != nil {
return err
}
2023-01-16 14:32:11 -06:00
if ! uploadFlags . stdin () {
2023-03-23 17:42:20 -05:00
_ , err = cliui . Prompt ( inv , cliui . PromptOptions {
2023-01-16 14:32:11 -06:00
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 {
2023-06-14 11:08:58 -05:00
Name : templateName ,
VersionID : job . ID ,
DefaultTTLMillis : ptr . Ref ( defaultTTL . Milliseconds ()),
FailureTTLMillis : ptr . Ref ( failureTTL . Milliseconds ()),
InactivityTTLMillis : ptr . Ref ( inactivityTTL . Milliseconds ()),
DisableEveryoneGroupAccess : disableEveryone ,
2022-06-07 13:37:45 +01:00
}
2023-03-23 17:42:20 -05:00
_ , err = client . CreateTemplate ( inv . 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
}
2023-06-07 00:22:58 -05:00
_ , _ = fmt . Fprintln ( inv . Stdout , "\n" + cliui . DefaultStyles . Wrap . Render (
"The " + cliui . DefaultStyles . Keyword . Render ( templateName ) + " template has been created at " + cliui . DefaultStyles . 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" )
2023-06-07 00:22:58 -05:00
_ , _ = fmt . Fprintln ( inv . Stdout , " " + cliui . DefaultStyles . Code . Render ( fmt . Sprintf ( "coder create --template=%q [workspace name]" , templateName )))
2023-03-23 17:42:20 -05:00
_ , _ = fmt . Fprintln ( inv . Stdout )
2022-04-11 18:54:30 -05:00
2022-02-10 08:33:27 -06:00
return nil
},
}
2023-03-23 17:42:20 -05:00
cmd . Options = clibase . OptionSet {
2023-06-14 11:08:58 -05:00
{
Flag : "private" ,
Description : "Disable the default behavior of granting template access to the 'everyone' group. " +
"The template permissions must be updated to allow non-admin users to use this template." ,
Value : clibase . BoolOf ( & disableEveryone ),
},
2023-03-23 17:42:20 -05:00
{
Flag : "variables-file" ,
Description : "Specify a file path with values for Terraform-managed variables." ,
Value : clibase . StringOf ( & variablesFile ),
},
{
Flag : "variable" ,
Description : "Specify a set of values for Terraform-managed variables." ,
Value : clibase . StringArrayOf ( & variables ),
},
2023-07-25 09:36:02 -05:00
{
Flag : "var" ,
Description : "Alias of --variable." ,
Value : clibase . StringArrayOf ( & variables ),
},
2023-03-23 17:42:20 -05:00
{
Flag : "provisioner-tag" ,
Description : "Specify a set of tags to target provisioner daemons." ,
Value : clibase . StringArrayOf ( & provisionerTags ),
},
{
Flag : "default-ttl" ,
Description : "Specify a default TTL for workspaces created from this template." ,
Default : "24h" ,
Value : clibase . DurationOf ( & defaultTTL ),
},
2023-05-10 12:57:11 -07:00
{
Flag : "failure-ttl" ,
Description : "Specify a failure TTL for workspaces created from this template. This licensed feature's default is 0h (off)." ,
Default : "0h" ,
Value : clibase . DurationOf ( & failureTTL ),
},
{
Flag : "inactivity-ttl" ,
Description : "Specify an inactivity TTL for workspaces created from this template. This licensed feature's default is 0h (off)." ,
Default : "0h" ,
Value : clibase . DurationOf ( & inactivityTTL ),
},
2023-03-23 17:42:20 -05:00
{
Flag : "test.provisioner" ,
Description : "Customize the provisioner backend." ,
Default : "terraform" ,
Value : clibase . StringOf ( & provisioner ),
Hidden : true ,
},
cliui . SkipPromptOption (),
2022-02-12 13:34:04 -06:00
}
2023-06-20 10:02:44 -05:00
cmd . Options = append ( cmd . Options , uploadFlags . options () ... )
2022-02-12 13:34:04 -06:00
return cmd
}
2022-06-17 12:22:28 -05:00
type createValidTemplateVersionArgs struct {
2023-06-02 11:16:46 +02:00
Name string
2023-07-11 13:11:08 +03:00
Message string
2023-06-02 11:16:46 +02:00
Client * codersdk . Client
Organization codersdk . Organization
Provisioner database . ProvisionerType
FileID uuid . UUID
2023-02-17 09:07:45 +01:00
VariablesFile string
Variables [] string
2022-06-17 12:22:28 -05:00
// 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
}
2023-06-02 11:16:46 +02:00
func createValidTemplateVersion ( inv * clibase . Invocation , args createValidTemplateVersionArgs ) ( * codersdk . TemplateVersion , error ) {
2022-06-17 12:22:28 -05:00
client := args . Client
2023-02-17 09:07:45 +01:00
variableValues , err := loadVariableValuesFromFile ( args . VariablesFile )
2023-02-15 18:24:15 +01:00
if err != nil {
2023-06-02 11:16:46 +02:00
return nil , err
2023-02-15 18:24:15 +01:00
}
2023-02-17 09:07:45 +01:00
variableValuesFromKeyValues , err := loadVariableValuesFromOptions ( args . Variables )
if err != nil {
2023-06-02 11:16:46 +02:00
return nil , err
2023-02-17 09:07:45 +01:00
}
variableValues = append ( variableValues , variableValuesFromKeyValues ... )
2022-06-17 12:22:28 -05:00
req := codersdk . CreateTemplateVersionRequest {
2023-02-15 18:24:15 +01:00
Name : args . Name ,
2023-07-11 13:11:08 +03:00
Message : args . Message ,
2023-02-15 18:24:15 +01:00
StorageMethod : codersdk . ProvisionerStorageMethodFile ,
FileID : args . FileID ,
Provisioner : codersdk . ProvisionerType ( args . Provisioner ),
ProvisionerTags : args . ProvisionerTags ,
UserVariableValues : variableValues ,
2022-06-17 12:22:28 -05:00
}
if args . Template != nil {
req . TemplateID = args . Template . ID
}
2023-03-23 17:42:20 -05:00
version , err := client . CreateTemplateVersion ( inv . Context (), args . Organization . ID , req )
2022-02-12 13:34:04 -06:00
if err != nil {
2023-06-02 11:16:46 +02:00
return nil , err
2022-02-12 13:34:04 -06:00
}
2023-03-23 17:42:20 -05:00
err = cliui . ProvisionerJob ( inv . Context (), inv . Stdout , cliui . ProvisionerJobOptions {
2022-03-22 13:17:50 -06:00
Fetch : func () ( codersdk . ProvisionerJob , error ) {
2023-03-23 17:42:20 -05:00
version , err := client . TemplateVersion ( inv . Context (), version . ID )
2022-03-22 13:17:50 -06:00
return version . Job , err
},
Cancel : func () error {
2023-03-23 17:42:20 -05:00
return client . CancelTemplateVersion ( inv . 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 ) {
2023-03-23 17:42:20 -05:00
return client . TemplateVersionLogsAfter ( inv . Context (), version . ID , 0 )
2022-03-22 13:17:50 -06:00
},
})
if err != nil {
2023-03-08 16:32:00 +01:00
var jobErr * cliui . ProvisionerJobError
if errors . As ( err , & jobErr ) && ! provisionerd . IsMissingParameterErrorCode ( string ( jobErr . Code )) {
2023-06-02 11:16:46 +02:00
return nil , err
2022-03-28 12:43:22 -06:00
}
2022-03-22 13:17:50 -06:00
}
2023-03-23 17:42:20 -05:00
version , err = client . TemplateVersion ( inv . Context (), version . ID )
2022-02-12 13:34:04 -06:00
if err != nil {
2023-06-02 11:16:46 +02:00
return nil , err
2022-02-12 13:34:04 -06:00
}
2022-03-22 13:17:50 -06:00
if version . Job . Status != codersdk . ProvisionerJobSucceeded {
2023-06-02 11:16:46 +02:00
return nil , xerrors . New ( version . Job . Error )
2022-02-12 13:34:04 -06:00
}
2023-03-23 17:42:20 -05:00
resources , err := client . TemplateVersionResources ( inv . Context (), version . ID )
2022-02-12 13:34:04 -06:00
if err != nil {
2023-06-02 11:16:46 +02:00
return 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 )
}
}
2023-03-23 17:42:20 -05:00
err = cliui . WorkspaceResources ( inv . Stdout , 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 {
2023-06-02 11:16:46 +02:00
return nil , xerrors . Errorf ( "preview template resources: %w" , err )
2022-04-14 13:23:20 -04:00
}
2023-06-02 11:16:46 +02:00
return & version , 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
}