Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: Allow inheriting parameters from previous template_versions when updating a template#2397

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Emyrk merged 18 commits intomainfromstevenmasley/template_update_params
Jun 17, 2022
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
18 commits
Select commitHold shift + click to select a range
ed33a1c
WIP: feat: Update templates also updates parameters
EmyrkJun 14, 2022
1f2892c
Insert params for template version update
EmyrkJun 15, 2022
8d62c96
feat: Implement parameters list
EmyrkJun 15, 2022
aceca62
Working implementation of inherited params
EmyrkJun 15, 2022
effbde7
Merge remote-tracking branch 'origin/main' into stevenmasley/template…
EmyrkJun 15, 2022
e569f0f
Fix name of enum
EmyrkJun 15, 2022
2e5bf44
Lint cleanup
EmyrkJun 15, 2022
e5b90bc
Enable always prompting of params
EmyrkJun 16, 2022
9d17dac
Fix db query for scope enum
EmyrkJun 16, 2022
04098c3
Update comment
EmyrkJun 16, 2022
3422844
Fix list parameters
EmyrkJun 16, 2022
5f881aa
Rename field
EmyrkJun 16, 2022
bcca07a
Merge remote-tracking branch 'origin/main' into stevenmasley/template…
EmyrkJun 17, 2022
c43aedc
Unit test param prompting
EmyrkJun 17, 2022
fa9b230
Add "--always-prompt" flag and logging info
EmyrkJun 17, 2022
9438db8
Linting fixes
EmyrkJun 17, 2022
5c590ae
Linting
EmyrkJun 17, 2022
f46b4af
Remove excessive prompt
EmyrkJun 17, 2022
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
15 changes: 11 additions & 4 deletionscli/parameterslist.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -45,16 +45,23 @@ func parameterList() *cobra.Command {
return xerrors.Errorf("get workspace template: %w", err)
}
scopeID = template.ID

case codersdk.ParameterScopeImportJob, "template_version":
scope = string(codersdk.ParameterScopeImportJob)
case codersdk.ParameterImportJob, "template_version":
scope = string(codersdk.ParameterImportJob)
scopeID, err = uuid.Parse(name)
if err != nil {
return xerrors.Errorf("%q must be a uuid for this scope type", name)
}

// Could be a template_version id or a job id. Check for the
// version id.
tv, err := client.TemplateVersion(cmd.Context(), scopeID)
if err == nil {
scopeID = tv.Job.ID
}

default:
return xerrors.Errorf("%q is an unsupported scope, use %v", scope, []codersdk.ParameterScope{
codersdk.ParameterWorkspace, codersdk.ParameterTemplate, codersdk.ParameterScopeImportJob,
codersdk.ParameterWorkspace, codersdk.ParameterTemplate, codersdk.ParameterImportJob,
})
}

Expand Down
105 changes: 87 additions & 18 deletionscli/templatecreate.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -82,7 +82,13 @@ func templateCreate() *cobra.Command {
}
spin.Stop()

job, parameters, err := createValidTemplateVersion(cmd, client, organization, database.ProvisionerType(provisioner), resp.Hash, parameterFile)
job, _, err := createValidTemplateVersion(cmd, createValidTemplateVersionArgs{
Client: client,
Organization: organization,
Provisioner: database.ProvisionerType(provisioner),
FileHash: resp.Hash,
ParameterFile: parameterFile,
})
if err != nil {
return err
}
Expand All@@ -98,7 +104,6 @@ func templateCreate() *cobra.Command {
createReq := codersdk.CreateTemplateRequest{
Name: templateName,
VersionID: job.ID,
ParameterValues: parameters,
MaxTTLMillis: ptr.Ref(maxTTL.Milliseconds()),
MinAutostartIntervalMillis: ptr.Ref(minAutostartInterval.Milliseconds()),
}
Expand DownExpand Up@@ -133,14 +138,34 @@ func templateCreate() *cobra.Command {
return cmd
}

func createValidTemplateVersion(cmd *cobra.Command, client *codersdk.Client, organization codersdk.Organization, provisioner database.ProvisionerType, hash string, parameterFile string, parameters ...codersdk.CreateParameterRequest) (*codersdk.TemplateVersion, []codersdk.CreateParameterRequest, error) {
type createValidTemplateVersionArgs struct {
Client *codersdk.Client
Organization codersdk.Organization
Provisioner database.ProvisionerType
FileHash string
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
}

func createValidTemplateVersion(cmd *cobra.Command, args createValidTemplateVersionArgs, parameters ...codersdk.CreateParameterRequest) (*codersdk.TemplateVersion, []codersdk.CreateParameterRequest, error) {
Copy link
Member

@johnstcnjohnstcnJun 16, 2022
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

yeah we're there now :D (args struct)

Copy link
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I really want to try refactoring this function. It's growing limbs and becoming quite large lol.

"Get it working" was my first step...

before := time.Now()
version, err := client.CreateTemplateVersion(cmd.Context(), organization.ID, codersdk.CreateTemplateVersionRequest{
client := args.Client

req := codersdk.CreateTemplateVersionRequest{
StorageMethod: codersdk.ProvisionerStorageMethodFile,
StorageSource:hash,
Provisioner: codersdk.ProvisionerType(provisioner),
StorageSource:args.FileHash,
Provisioner: codersdk.ProvisionerType(args.Provisioner),
ParameterValues: parameters,
})
}
if args.Template != nil {
req.TemplateID = args.Template.ID
}
version, err := client.CreateTemplateVersion(cmd.Context(), args.Organization.ID, req)
if err != nil {
return nil, nil, err
}
Expand DownExpand Up@@ -175,33 +200,77 @@ func createValidTemplateVersion(cmd *cobra.Command, client *codersdk.Client, org
return nil, nil, err
}

// 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
}
}

if provisionerd.IsMissingParameterError(version.Job.Error) {
valuesBySchemaID := map[string]codersdk.TemplateVersionParameter{}
for _, parameterValue := range parameterValues {
valuesBySchemaID[parameterValue.SchemaID.String()] = parameterValue
}

sort.Slice(parameterSchemas, func(i, j int) bool {
return parameterSchemas[i].Name < parameterSchemas[j].Name
})

// parameterMapFromFile can be nil if parameter file is not specified
var parameterMapFromFile map[string]string
if args.ParameterFile != "" {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I think we should remove theParameterFile in favor of a--var=asd=asd approach. Separate issue, but I think it conflates some of this logic.

Copy link
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

The file logic needs to be looked at for sure. I kept it as is for now.

_, _ = 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)
missingSchemas := make([]codersdk.ParameterSchema, 0)
for _, parameterSchema := range parameterSchemas {
_, ok := valuesBySchemaID[parameterSchema.ID.String()]
if ok {
continue
}
missingSchemas = append(missingSchemas, parameterSchema)
}
_, _ = 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.")+"\r\n")

// parameterMapFromFile can be nil if parameter file is not specified
var parameterMapFromFile map[string]string
if parameterFile != "" {
_, _ = fmt.Fprintln(cmd.OutOrStdout(), cliui.Styles.Paragraph.Render("Attempting to read the variables from the parameter file.")+"\r\n")
parameterMapFromFile, err = createParameterMapFromFile(parameterFile)
if err != nil {
return nil, nil, err
// 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
}

missingSchemas = append(missingSchemas, parameterSchema)
}
_, _ = 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."))
}
_, _ = fmt.Fprint(cmd.OutOrStdout(), "\r\n")

for _, parameterSchema := range missingSchemas {
parameterValue, err := getParameterValueFromMapOrInput(cmd, parameterMapFromFile, parameterSchema)
if err != nil {
Expand All@@ -218,7 +287,7 @@ func createValidTemplateVersion(cmd *cobra.Command, client *codersdk.Client, org

// 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.
return createValidTemplateVersion(cmd,client, organization, provisioner, hash, parameterFile, parameters...)
return createValidTemplateVersion(cmd,args, parameters...)
}

if version.Job.Status != codersdk.ProvisionerJobSucceeded {
Expand Down
45 changes: 19 additions & 26 deletionscli/templateupdate.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,14 +10,17 @@ import (
"golang.org/x/xerrors"

"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/provisionersdk"
)

func templateUpdate() *cobra.Command {
var (
directory string
provisioner string
directory string
provisioner string
parameterFile string
alwaysPrompt bool
)

cmd := &cobra.Command{
Expand DownExpand Up@@ -64,42 +67,30 @@ func templateUpdate() *cobra.Command {
}
spin.Stop()

before := time.Now()
templateVersion, err := client.CreateTemplateVersion(cmd.Context(), organization.ID, codersdk.CreateTemplateVersionRequest{
TemplateID: template.ID,
StorageMethod: codersdk.ProvisionerStorageMethodFile,
StorageSource: resp.Hash,
Provisioner: codersdk.ProvisionerType(provisioner),
job, _, err := createValidTemplateVersion(cmd, createValidTemplateVersionArgs{
Client: client,
Organization: organization,
Provisioner: database.ProvisionerType(provisioner),
FileHash: resp.Hash,
ParameterFile: parameterFile,
Template: &template,
ReuseParameters: !alwaysPrompt,
})
if err != nil {
return err
}
logs, err := client.TemplateVersionLogsAfter(cmd.Context(), templateVersion.ID, before)
if err != nil {
return err
}
for {
log, ok := <-logs
if !ok {
break
}
_, _ = fmt.Printf("%s (%s): %s\n", provisioner, log.Level, log.Output)
}
templateVersion, err = client.TemplateVersion(cmd.Context(), templateVersion.ID)
if err != nil {
return err
}

iftemplateVersion.Job.Status != codersdk.ProvisionerJobSucceeded {
return xerrors.Errorf("job failed: %s",templateVersion.Job.Error)
ifjob.Job.Status != codersdk.ProvisionerJobSucceeded {
return xerrors.Errorf("job failed: %s",job.Job.Status)
}

err = client.UpdateActiveTemplateVersion(cmd.Context(), template.ID, codersdk.UpdateActiveTemplateVersion{
ID:templateVersion.ID,
ID:job.ID,
})
if err != nil {
return err
}

_, _ = fmt.Printf("Updated version!\n")
return nil
},
Expand All@@ -108,6 +99,8 @@ func templateUpdate() *cobra.Command {
currentDirectory, _ := os.Getwd()
cmd.Flags().StringVarP(&directory, "directory", "d", currentDirectory, "Specify the directory to create from")
cmd.Flags().StringVarP(&provisioner, "test.provisioner", "", "terraform", "Customize the provisioner backend")
cmd.Flags().StringVarP(&parameterFile, "parameter-file", "", "", "Specify a file path with parameter values.")
cmd.Flags().BoolVar(&alwaysPrompt, "always-prompt", false, "Always prompt all parameters. Does not pull parameter values from active template version")
cliui.AllowSkipPrompt(cmd)
// This is for testing!
err := cmd.Flags().MarkHidden("test.provisioner")
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp