mirror of
https://github.com/helmfile/helmfile.git
synced 2026-09-30 19:51:56 +02:00
* feat: add 'create' subcommand to scaffold helmfile deployment projects Add 'helmfile create [NAME]' command that generates a best-practice helmfile project structure with: - helmfile.yaml with commented examples (helmDefaults, repositories, environments, releases) - environments/default.yaml for environment-specific values - values/.gitkeep placeholder for release values Supports --output-dir/-o for custom output path and --force to overwrite existing files. Validates project name to prevent path traversal. Signed-off-by: yxxhero <aiopsclub@163.com> * fix: add overwrite protection for all scaffold files and unit tests for create command - pkg/app/create.go: extract writeFileIfNotExists helper that respects the --force flag; all three scaffold files (helmfile.yaml, environments/default.yaml, values/.gitkeep) now refuse to overwrite without --force - pkg/config/create.go: ValidateConfig now checks all three scaffold paths and reports every already-existing file in a single error before proceeding, instead of only checking helmfile.yaml - pkg/app/create_test.go: add unit tests covering new directory, current directory, per-file overwrite rejection without --force, and full overwrite with --force Agent-Logs-Url: https://github.com/helmfile/helmfile/sessions/eb6d9e4b-0f72-4e26-b841-e1e39a2b2e83 Co-authored-by: yxxhero <11087727+yxxhero@users.noreply.github.com> * fix: remove redundant absDir from ValidateConfig error message Agent-Logs-Url: https://github.com/helmfile/helmfile/sessions/eb6d9e4b-0f72-4e26-b841-e1e39a2b2e83 Co-authored-by: yxxhero <11087727+yxxhero@users.noreply.github.com> * fix: address create command review feedback - cmd/create.go: add config.NewCLIConfigImpl() call for consistency with other subcommands; update --force flag help text to list all overwritten files - pkg/config/create.go: delegate to c.GlobalImpl.ValidateConfig() at end of ValidateConfig() for global option validation (--color/--no-color) - pkg/config/create_test.go: add unit tests for CreateImpl.ValidateConfig() covering path separator rejection, '..' rejection, existing-file detection per-file and with --force, and global color conflict delegation Agent-Logs-Url: https://github.com/helmfile/helmfile/sessions/6327d657-5888-4b94-85fb-def80c0a193f Co-authored-by: yxxhero <11087727+yxxhero@users.noreply.github.com> * fix: clarify test helper name and comment in create_test.go Agent-Logs-Url: https://github.com/helmfile/helmfile/sessions/6327d657-5888-4b94-85fb-def80c0a193f Co-authored-by: yxxhero <11087727+yxxhero@users.noreply.github.com> * fix: atomic preflight check in App.Create before any writes Refactor Create to collect all conflicting scaffold paths up front before writing anything. When --force is not set and any scaffold file already exists, the command returns a single error listing all conflicts without touching the filesystem. Also removes the now-unnecessary writeFileIfNotExists helper and adds a test (TestCreate_PreflightAtomicOnLaterConflict) verifying that a conflict on a later file (e.g. environments/default.yaml) prevents even the first file (helmfile.yaml) from being created. Agent-Logs-Url: https://github.com/helmfile/helmfile/sessions/aae6f2e6-7f9e-42b8-afa3-78edd3215127 Co-authored-by: yxxhero <11087727+yxxhero@users.noreply.github.com> * fix: handle non-IsNotExist Stat errors in preflight check; add whitespace name test; fix gci formatting - pkg/app/create.go: treat os.Stat errors that are NOT os.IsNotExist as hard errors in the preflight scan, surfacing permission/IO issues before any writes happen; remove trailing blank line that caused gci failure - pkg/config/create.go: same non-IsNotExist error handling in ValidateConfig - pkg/config/create_test.go: add TestCreateImpl_ValidateConfig_WhitespaceOnlyName covering the " " (whitespace-only) name rejection branch Agent-Logs-Url: https://github.com/helmfile/helmfile/sessions/d6574f56-f46d-46f7-99d9-e0b0b897b3b5 Co-authored-by: yxxhero <11087727+yxxhero@users.noreply.github.com> * refactor: eliminate duplicated scaffold existence check; use O_EXCL for TOCTOU protection - pkg/config/create.go: remove file-existence check from ValidateConfig (duplicate of App.Create's preflight); ValidateConfig now only validates the project name and delegates to GlobalImpl.ValidateConfig. Remove unused os/path/filepath imports. - pkg/app/create.go: add writeScaffoldFile helper that uses O_CREATE|O_EXCL when force=false, so a file appearing between the preflight check and the actual write is caught rather than silently overwritten (TOCTOU protection). - pkg/config/create_test.go: remove four file-existence tests that tested the now-deleted ValidateConfig logic; file-conflict coverage remains in pkg/app/create_test.go. Simplify ValidName and GlobalColorConflict tests. Agent-Logs-Url: https://github.com/helmfile/helmfile/sessions/82f82e72-934f-416c-8662-5060e92284fa Co-authored-by: yxxhero <11087727+yxxhero@users.noreply.github.com> * fix: wrap O_EXCL error with --force hint; add writeScaffoldFile unit tests - pkg/app/create.go: wrap os.IsExist error from writeScaffoldFile with a message that names the conflicting file and suggests --force, so the user gets actionable output even in the TOCTOU case - pkg/app/create_test.go: add TestWriteScaffoldFile_CreatesNewFile, TestWriteScaffoldFile_ExistingFileNoForce, and TestWriteScaffoldFile_ExistingFileWithForce to cover the helper directly Agent-Logs-Url: https://github.com/helmfile/helmfile/sessions/82f82e72-934f-416c-8662-5060e92284fa Co-authored-by: yxxhero <11087727+yxxhero@users.noreply.github.com> * fix: wrap App.Create errors in *app.Error; reject '.' as project name; add '.' name test - pkg/app/create.go: wrap all App.Create fmt.Errorf returns with appError("", ...) so toCLIError produces a clean user-friendly message instead of "unexpected error: *fmt.wrapError: ..." - pkg/config/create.go: reject "." as a NAME alongside ".." to prevent accidentally scaffolding into the current directory via a named argument - pkg/config/create_test.go: add TestCreateImpl_ValidateConfig_NameDot Agent-Logs-Url: https://github.com/helmfile/helmfile/sessions/6d64508e-2d66-47e9-a02a-7669a2f481b7 Co-authored-by: yxxhero <11087727+yxxhero@users.noreply.github.com> * fix: drop unused outputDir param from test helper to fix unparam lint error Agent-Logs-Url: https://github.com/helmfile/helmfile/sessions/11cd65e9-c5ef-4195-9375-bc929169616b Co-authored-by: yxxhero <11087727+yxxhero@users.noreply.github.com> * fix: drop unused force param from test helper to fix unparam lint error Agent-Logs-Url: https://github.com/helmfile/helmfile/sessions/0e1bdac5-708f-4615-ae6d-e22fc1e921f2 Co-authored-by: yxxhero <11087727+yxxhero@users.noreply.github.com> --------- Signed-off-by: yxxhero <aiopsclub@163.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
161 lines
8.3 KiB
Go
161 lines
8.3 KiB
Go
package cmd
|
|
|
|
import (
|
|
stderrors "errors"
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/spf13/pflag"
|
|
"go.szostok.io/version/extension"
|
|
"go.uber.org/zap"
|
|
|
|
"github.com/helmfile/helmfile/pkg/app"
|
|
"github.com/helmfile/helmfile/pkg/app/version"
|
|
"github.com/helmfile/helmfile/pkg/config"
|
|
"github.com/helmfile/helmfile/pkg/envvar"
|
|
"github.com/helmfile/helmfile/pkg/errors"
|
|
"github.com/helmfile/helmfile/pkg/helmexec"
|
|
"github.com/helmfile/helmfile/pkg/runtime"
|
|
)
|
|
|
|
var logger *zap.SugaredLogger
|
|
var globalUsage = "Declaratively deploy your Kubernetes manifests, Kustomize configs, and Charts as Helm releases in one shot\n" + runtime.Info()
|
|
|
|
func toCLIError(g *config.GlobalImpl, err error) error {
|
|
if err != nil {
|
|
var exitErr helmexec.ExitError
|
|
if stderrors.As(err, &exitErr) {
|
|
return errors.NewExitError(exitErr.Error(), exitErr.ExitStatus())
|
|
}
|
|
switch e := err.(type) {
|
|
case *app.NoMatchingHelmfileError:
|
|
noMatchingExitCode := 3
|
|
if g.AllowNoMatchingRelease {
|
|
noMatchingExitCode = 0
|
|
}
|
|
return errors.NewExitError(e.Error(), noMatchingExitCode)
|
|
case *app.MultiError:
|
|
return errors.NewExitError(e.Error(), 1)
|
|
case *app.Error:
|
|
return errors.NewExitError(e.Error(), e.Code())
|
|
default:
|
|
return errors.NewExitError(fmt.Sprintf("unexpected error: %T: %v", e, e), 1)
|
|
}
|
|
}
|
|
return err
|
|
}
|
|
|
|
// NewRootCmd creates the root command for the CLI.
|
|
func NewRootCmd(globalConfig *config.GlobalOptions) (*cobra.Command, error) {
|
|
cmd := &cobra.Command{
|
|
Use: "helmfile",
|
|
Short: globalUsage,
|
|
Long: globalUsage,
|
|
Version: version.Version(),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
PersistentPreRunE: func(c *cobra.Command, args []string) error {
|
|
// Valid levels:
|
|
// https://github.com/uber-go/zap/blob/7e7e266a8dbce911a49554b945538c5b950196b8/zapcore/level.go#L126
|
|
logLevel := globalConfig.LogLevel
|
|
switch {
|
|
case globalConfig.Debug:
|
|
logLevel = "debug"
|
|
case globalConfig.Quiet:
|
|
logLevel = "warn"
|
|
}
|
|
|
|
// If the log output is not set, default to stderr.
|
|
logOut := globalConfig.LogOutput
|
|
if logOut == nil {
|
|
logOut = os.Stderr
|
|
}
|
|
logger = helmexec.NewLogger(logOut, logLevel)
|
|
globalConfig.SetLogger(logger)
|
|
return nil
|
|
},
|
|
}
|
|
flags := cmd.PersistentFlags()
|
|
|
|
// Set the global options for the root command.
|
|
setGlobalOptionsForRootCmd(flags, globalConfig)
|
|
|
|
flags.ParseErrorsAllowlist.UnknownFlags = true
|
|
|
|
globalImpl := config.NewGlobalImpl(globalConfig)
|
|
|
|
// when set environment HELMFILE_UPGRADE_NOTICE_DISABLED any value, skip upgrade notice.
|
|
var versionOpts []extension.CobraOption
|
|
if os.Getenv(envvar.UpgradeNoticeDisabled) == "" {
|
|
versionOpts = append(versionOpts, extension.WithUpgradeNotice("helmfile", "helmfile"))
|
|
}
|
|
|
|
cmd.AddCommand(
|
|
NewCreateCmd(globalImpl),
|
|
NewInitCmd(globalImpl),
|
|
NewApplyCmd(globalImpl),
|
|
NewBuildCmd(globalImpl),
|
|
NewCacheCmd(globalImpl),
|
|
NewDepsCmd(globalImpl),
|
|
NewDestroyCmd(globalImpl),
|
|
NewFetchCmd(globalImpl),
|
|
NewListCmd(globalImpl),
|
|
NewReposCmd(globalImpl),
|
|
NewLintCmd(globalImpl),
|
|
NewWriteValuesCmd(globalImpl),
|
|
NewTestCmd(globalImpl),
|
|
NewUnittestCmd(globalImpl),
|
|
NewTemplateCmd(globalImpl),
|
|
NewSyncCmd(globalImpl),
|
|
NewDiffCmd(globalImpl),
|
|
NewStatusCmd(globalImpl),
|
|
NewShowDAGCmd(globalImpl),
|
|
NewPrintEnvCmd(globalImpl),
|
|
extension.NewVersionCobraCmd(
|
|
versionOpts...,
|
|
),
|
|
)
|
|
|
|
return cmd, nil
|
|
}
|
|
|
|
func setGlobalOptionsForRootCmd(fs *pflag.FlagSet, globalOptions *config.GlobalOptions) {
|
|
fs.StringVarP(&globalOptions.HelmBinary, "helm-binary", "b", app.DefaultHelmBinary, "Path to the helm binary")
|
|
fs.StringVarP(&globalOptions.KustomizeBinary, "kustomize-binary", "k", app.DefaultKustomizeBinary, "Path to the kustomize binary")
|
|
fs.StringVarP(&globalOptions.File, "file", "f", "", "load config from file or directory. defaults to \"`helmfile.yaml`\" or \"helmfile.yaml.gotmpl\" or \"helmfile.d\" (means \"helmfile.d/*.yaml\" or \"helmfile.d/*.yaml.gotmpl\") in this preference. Specify - to load the config from the standard input.")
|
|
fs.StringVarP(&globalOptions.Environment, "environment", "e", "", `specify the environment name. Overrides "HELMFILE_ENVIRONMENT" OS environment variable when specified. defaults to "default"`)
|
|
fs.StringArrayVar(&globalOptions.StateValuesSet, "state-values-set", nil, "set state values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2). Used to override .Values within the helmfile template (not values template).")
|
|
fs.StringArrayVar(&globalOptions.StateValuesSetString, "state-values-set-string", nil, "set state STRING values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2). Used to override .Values within the helmfile template (not values template).")
|
|
fs.StringArrayVar(&globalOptions.StateValuesFile, "state-values-file", nil, "specify state values in a YAML file. Used to override .Values within the helmfile template (not values template).")
|
|
fs.BoolVar(&globalOptions.SkipDeps, "skip-deps", false, `skip running "helm repo update" and "helm dependency build"`)
|
|
fs.BoolVar(&globalOptions.SkipRefresh, "skip-refresh", false, `skip running "helm repo update"`)
|
|
fs.BoolVar(&globalOptions.StripArgsValuesOnExitError, "strip-args-values-on-exit-error", true, `Strip the potential secret values of the helm command args contained in a helmfile error message`)
|
|
fs.BoolVar(&globalOptions.DisableForceUpdate, "disable-force-update", false, `do not force helm repos to update when executing "helm repo add" (Helm 3 only)`)
|
|
fs.BoolVar(&globalOptions.EnforcePluginVerification, "enforce-plugin-verification", false, `fail plugin installation if verification is not supported (for security purposes)`)
|
|
fs.BoolVar(&globalOptions.HelmOCIPlainHTTP, "oci-plain-http", false, `use plain HTTP for OCI registries (required for local/insecure registries in Helm 4)`)
|
|
fs.BoolVarP(&globalOptions.Quiet, "quiet", "q", false, "Silence output. Equivalent to log-level warn")
|
|
fs.StringVar(&globalOptions.Kubeconfig, "kubeconfig", "", "Use a particular kubeconfig file")
|
|
fs.StringVar(&globalOptions.KubeContext, "kube-context", "", "Set kubectl context. Uses current context by default")
|
|
fs.BoolVar(&globalOptions.Debug, "debug", false, "Enable verbose output for Helm and set log-level to debug, this disables --quiet/-q effect")
|
|
fs.BoolVar(&globalOptions.Color, "color", false, "Output with color")
|
|
fs.BoolVar(&globalOptions.NoColor, "no-color", false, "Output without color")
|
|
fs.StringVar(&globalOptions.LogLevel, "log-level", "info", "Set log level, default info")
|
|
fs.StringVarP(&globalOptions.Namespace, "namespace", "n", "", "Set namespace. Uses the namespace set in the context by default, and is available in templates as {{ .Namespace }}")
|
|
fs.StringVarP(&globalOptions.Chart, "chart", "c", "", "Set chart. Uses the chart set in release by default, and is available in template as {{ .Chart }}")
|
|
fs.StringArrayVarP(&globalOptions.Selector, "selector", "l", nil, `Only run using the releases that match labels. Labels can take the form of foo=bar or foo!=bar.
|
|
A release must match all labels in a group in order to be used. Multiple groups can be specified at once.
|
|
"--selector tier=frontend,tier!=proxy --selector tier=backend" will match all frontend, non-proxy releases AND all backend releases.
|
|
The name of a release can be used as a label: "--selector name=myrelease"`)
|
|
fs.BoolVar(&globalOptions.AllowNoMatchingRelease, "allow-no-matching-release", false, `Do not exit with an error code if the provided selector has no matching releases.`)
|
|
fs.BoolVar(&globalOptions.EnableLiveOutput, "enable-live-output", globalOptions.EnableLiveOutput, `Show live output from the Helm binary Stdout/Stderr into Helmfile own Stdout/Stderr.
|
|
It only applies for the Helm CLI commands, Stdout/Stderr for Hooks are still displayed only when it's execution finishes.`)
|
|
fs.BoolVarP(&globalOptions.Interactive, "interactive", "i", false, "Request confirmation before attempting to modify clusters")
|
|
fs.BoolVar(&globalOptions.SequentialHelmfiles, "sequential-helmfiles", false, `Process helmfile.d files sequentially in alphabetical order instead of in parallel.
|
|
Useful when file order matters for dependencies (e.g., databases before applications).
|
|
When processing multiple files, paths are resolved without changing the process working directory,
|
|
so relative environment variables like KUBECONFIG work correctly.`)
|
|
// avoid 'pflag: help requested' error (#251)
|
|
fs.BoolP("help", "h", false, "help for helmfile")
|
|
}
|