Skip to content

Commit f665f23

Browse files
cdalarclaude
andauthored
feat(create): expose Hetzner config as CLI flags; drop required .onctl YAML (#918)
* feat(create): expose Hetzner/global config as CLI flags; drop required .onctl YAML onctl previously required a .onctl config dir (from `onctl init`) and fatally refused to run without it. For Hetzner, every setting that lived in hetzner.yaml / onctl.yaml is now a CLI flag with a default, so onctl works with no config files on disk. - setDefaults() (cmd/common.go): viper.SetDefault for all Hetzner + global keys (location=fsn1, vm.type=cpx21, vm.image=ubuntu-22.04, vm.username=root, ssh.publicKey/privateKey, vm.cloud-init.timeout=3m, actions.githubOwner). - Generic create flags --type/--location/--username/--cloud-init-timeout (+ existing --image), each viper.BindPFlag'd to the key the code already reads, so values flow through unchanged. Defaults match the old YAML. - Persistent --provider flag (overrides ONCTL_CLOUD); --github-owner on action. - Provider construction + config load moved from Execute() into rootCmd.PersistentPreRunE so it runs after flag parsing (flags can override config). Missing .onctl is now best-effort (logged), not fatal. - Remove embedded init/hetzner.yaml and init/onctl.yaml (defaults are in code). Other providers keep their YAML for now (separate follow-up). Credentials are unaffected (still env: HCLOUD_TOKEN, etc.). Adds flags_defaults_test.go covering flag existence, viper binding, and defaults. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013fQKc2HmtfdtBeKfXBXab6 * fix: address review feedback on hetzner-flags-no-yaml PR - Keep config errors fatal outside Hetzner by extracting initState() from PersistentPreRunE, matching the pre-flags behavior for aws/gcp/ azure/firecracker while still defaulting Hetzner when .onctl is missing. - Add ensureProvider() and skip __complete/__completeNoDesc in PersistentPreRunE so shell completion doesn't dereference a nil provider or fatally error when config is missing. - Fix TestCreateFlagsBindToViper flaking under randomized test order by loading an isolated empty config before asserting on viper defaults. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0181WDmhDAKfTzXfFUZFKGvM --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 66b71c9 commit f665f23

9 files changed

Lines changed: 185 additions & 29 deletions

File tree

‎cmd/action.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,5 +150,7 @@ func downloadFile(url, filepath string) error {
150150

151151
func init() {
152152
actionCmd.Flags().StringVarP(&actionParamsFile, "params", "p", "", "JSON parameter file to pass as stdin")
153+
actionCmd.Flags().String("github-owner", "cdalar", "GitHub owner/org to download action binaries from")
154+
_ = viper.BindPFlag("actions.githubOwner", actionCmd.Flags().Lookup("github-owner"))
153155
rootCmd.AddCommand(actionCmd)
154156
}

‎cmd/common.go‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,25 @@ func GenerateIDToken() uuid.UUID {
4646
return u1
4747
}
4848

49+
// setDefaults registers built-in defaults for every setting that was
50+
// previously supplied by the YAML files written by `onctl init`. With these in
51+
// place onctl works for Hetzner with no .onctl config present; CLI flags and an
52+
// existing .onctl config still override them (viper precedence: flag > env >
53+
// config > default). See ROADMAP/PR: "Remove onctl's YAML config in favor of
54+
// CLI flags with defaults (Hetzner)".
55+
func setDefaults() {
56+
// Global (was onctl.yaml)
57+
viper.SetDefault("ssh.publicKey", "~/.ssh/id_rsa.pub")
58+
viper.SetDefault("ssh.privateKey", "~/.ssh/id_rsa")
59+
viper.SetDefault("vm.cloud-init.timeout", "3m")
60+
viper.SetDefault("actions.githubOwner", "cdalar")
61+
// Hetzner (was hetzner.yaml)
62+
viper.SetDefault("hetzner.location", "fsn1")
63+
viper.SetDefault("hetzner.vm.type", "cpx21")
64+
viper.SetDefault("hetzner.vm.image", "ubuntu-22.04")
65+
viper.SetDefault("hetzner.vm.username", "root")
66+
}
67+
4968
func ReadConfig(cloudProvider string) error {
5069
// Check current working directory
5170
dir, err := os.Getwd()

‎cmd/create.go‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ type cmdCreateOptions struct {
3434

3535
var (
3636
opt cmdCreateOptions
37+
// Generic VM flags bound to viper keys (see init below). Kept as package
38+
// vars only to satisfy cobra's StringVar; the values are read via viper.
39+
flagType string
40+
flagLocation string
41+
flagUsername string
42+
flagCloudInitTimeout string
3743
)
3844

3945
func parseConfigFile(configFile string) (*cmdCreateOptions, error) {
@@ -69,6 +75,24 @@ func init() {
6975
createCmd.Flags().StringSliceVarP(&opt.Variables, "vars", "e", []string{}, "Environment variables passed to the script")
7076
createCmd.Flags().StringVarP(&opt.ConfigFile, "file", "f", "", "Path to configuration YAML file")
7177
createCmd.Flags().StringVar(&opt.Vm.Image, "image", "", "OS image to use (e.g. ubuntu-22.04, fedora-42)")
78+
79+
// Generic VM flags. These replace the per-provider YAML written by
80+
// `onctl init` (Hetzner pass): each is bound to the viper key the rest of
81+
// the code already reads, so values flow through unchanged. Defaults match
82+
// the previous hetzner.yaml/onctl.yaml so behavior is identical with no
83+
// config present. See setDefaults() in common.go.
84+
createCmd.Flags().StringVar(&flagType, "type", "cpx21", "instance type (provider-specific; Hetzner default cpx21)")
85+
createCmd.Flags().StringVar(&flagLocation, "location", "fsn1", "location/region for the VM")
86+
createCmd.Flags().StringVar(&flagUsername, "username", "root", "ssh username on the VM")
87+
createCmd.Flags().StringVar(&flagCloudInitTimeout, "cloud-init-timeout", "3m", "max wait for cloud-init (e.g. 3m, 180s)")
88+
_ = viper.BindPFlag("hetzner.vm.type", createCmd.Flags().Lookup("type"))
89+
_ = viper.BindPFlag("hetzner.location", createCmd.Flags().Lookup("location"))
90+
_ = viper.BindPFlag("hetzner.vm.username", createCmd.Flags().Lookup("username"))
91+
_ = viper.BindPFlag("vm.cloud-init.timeout", createCmd.Flags().Lookup("cloud-init-timeout"))
92+
// --image keeps an empty flag default (so the non-hetzner guard below and
93+
// opt.Vm.Image stay empty when unset); viper supplies the real default.
94+
_ = viper.BindPFlag("hetzner.vm.image", createCmd.Flags().Lookup("image"))
95+
7296
// Register create command at root level for convenience
7397
rootCmd.AddCommand(createCmd)
7498
createCmd.SetUsageTemplate(createCmd.UsageTemplate() + `

‎cmd/destroy.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@ var destroyCmd = &cobra.Command{
2727
Aliases: []string{"down", "delete", "remove", "rm"},
2828
Short: "Destroy VM(s)",
2929
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
30+
ensureProvider()
31+
if provider == nil {
32+
return nil, cobra.ShellCompDirectiveError
33+
}
3034
VMList, err := provider.List()
3135
list := []string{}
3236
for _, vm := range VMList.List {

‎cmd/flags_defaults_test.go‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package cmd
2+
3+
import (
4+
"os"
5+
"path/filepath"
6+
"testing"
7+
8+
"github.com/spf13/viper"
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
// TestGenericCreateFlagsExist verifies the YAML-replacing flags are registered.
13+
func TestGenericCreateFlagsExist(t *testing.T) {
14+
for _, name := range []string{"type", "location", "username", "cloud-init-timeout", "image"} {
15+
assert.NotNil(t, createCmd.Flags().Lookup(name), "create should have --%s flag", name)
16+
}
17+
assert.NotNil(t, rootCmd.PersistentFlags().Lookup("provider"), "root should have persistent --provider flag")
18+
assert.NotNil(t, actionCmd.Flags().Lookup("github-owner"), "action should have --github-owner flag")
19+
}
20+
21+
// TestCreateFlagsBindToViper verifies that setting a create flag is reflected
22+
// through its viper binding (the path the rest of the code reads), and that the
23+
// default value matches the old hetzner.yaml. Deterministic: it sets values
24+
// explicitly and restores them.
25+
func TestCreateFlagsBindToViper(t *testing.T) {
26+
// viper.ReadInConfig() replaces (not merges) the general-config layer,
27+
// which outranks our SetDefault values. Loading an empty config here
28+
// clears any values a sibling test (e.g. TestReadConfig_WithValidConfig)
29+
// left behind in the shared, global viper instance, so this test's
30+
// outcome doesn't depend on `go test`'s randomized run order.
31+
tempDir, err := os.MkdirTemp("", "onctl-flags-test")
32+
assert.NoError(t, err)
33+
defer func() { _ = os.RemoveAll(tempDir) }()
34+
onctlDir := filepath.Join(tempDir, ".onctl")
35+
assert.NoError(t, os.Mkdir(onctlDir, 0755))
36+
assert.NoError(t, os.WriteFile(filepath.Join(onctlDir, "onctl.yaml"), []byte("{}\n"), 0644))
37+
assert.NoError(t, os.WriteFile(filepath.Join(onctlDir, "hetzner.yaml"), []byte("{}\n"), 0644))
38+
39+
originalWd, err := os.Getwd()
40+
assert.NoError(t, err)
41+
defer func() { _ = os.Chdir(originalWd) }()
42+
assert.NoError(t, os.Chdir(tempDir))
43+
assert.NoError(t, ReadConfig("hetzner"))
44+
setDefaults()
45+
46+
cases := []struct{ flag, key, def, override string }{
47+
{"type", "hetzner.vm.type", "cpx21", "cpx31"},
48+
{"location", "hetzner.location", "fsn1", "nbg1"},
49+
{"username", "hetzner.vm.username", "root", "admin"},
50+
{"cloud-init-timeout", "vm.cloud-init.timeout", "3m", "180s"},
51+
}
52+
for _, c := range cases {
53+
// Default (flag unchanged) resolves via the binding.
54+
assert.Equal(t, c.def, viper.GetString(c.key), "default for %s", c.key)
55+
// Override flows through.
56+
assert.NoError(t, createCmd.Flags().Set(c.flag, c.override))
57+
assert.Equal(t, c.override, viper.GetString(c.key), "override for %s", c.key)
58+
// Restore so other tests see the default again.
59+
assert.NoError(t, createCmd.Flags().Set(c.flag, c.def))
60+
}
61+
}

‎cmd/root.go‎

Lines changed: 71 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,41 @@ var (
3434
3535
# Destroy a VM
3636
onctl destroy test`,
37+
// PersistentPreRunE runs after cobra parses flags, so flag→viper
38+
// bindings (set in each command's init) are in effect before we build
39+
// the provider config. init/version/help and the bare root need no
40+
// provider, so they are skipped.
41+
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
42+
// Bare root (no subcommand) and commands that need no provider.
43+
if cmd.Parent() == nil {
44+
return nil
45+
}
46+
switch cmd.Name() {
47+
case "init", "version", "help", "__complete", "__completeNoDesc":
48+
return nil
49+
}
50+
if providerFlag != "" {
51+
if !tools.Contains(cloudProviderList, providerFlag) {
52+
return fmt.Errorf("unsupported provider %q; use one of: %s", providerFlag, strings.Join(cloudProviderList, ", "))
53+
}
54+
if err := os.Setenv("ONCTL_CLOUD", providerFlag); err != nil {
55+
return err
56+
}
57+
}
58+
if err := initState(); err != nil {
59+
return err
60+
}
61+
// The images command initializes its own provider lazily.
62+
if cmd.Name() != "images" {
63+
initProvider(cloudProvider)
64+
}
65+
return nil
66+
},
3767
}
3868
cloudProvider string
3969
cloudProviderList = []string{"aws", "hetzner", "azure", "gcp", "firecracker"}
4070
provider cloud.CloudProviderInterface
71+
providerFlag string
4172
)
4273

4374
func checkCloudProvider() string {
@@ -64,22 +95,50 @@ func checkCloudProvider() string {
6495
return cloudProvider
6596
}
6697

67-
// Execute executes the root command.
98+
// Execute executes the root command. Provider selection and config loading now
99+
// happen in rootCmd.PersistentPreRunE (after flag parsing) so CLI flags can
100+
// override config values.
68101
func Execute() error {
69102
log.Println("[DEBUG] Args: " + strings.Join(os.Args, ","))
70-
if len(os.Args) > 1 && os.Args[1] != "init" && os.Args[1] != "version" {
71-
cloudProvider = checkCloudProvider()
72-
log.Println("[DEBUG] Cloud: " + cloudProvider)
73-
err := ReadConfig(cloudProvider)
74-
if err != nil {
75-
log.Fatalln(err)
103+
return rootCmd.Execute()
104+
}
105+
106+
// initState resolves the cloud provider and loads its config. Hetzner has
107+
// built-in defaults (see setDefaults), so a missing .onctl is best-effort
108+
// there; every other provider still requires its YAML config, so a missing
109+
// or unreadable config stays a fatal error, matching the pre-flags behavior.
110+
func initState() error {
111+
setDefaults()
112+
cloudProvider = checkCloudProvider()
113+
log.Println("[DEBUG] Cloud: " + cloudProvider)
114+
if err := ReadConfig(cloudProvider); err != nil {
115+
if cloudProvider != "hetzner" {
116+
return err
76117
}
118+
log.Println("[DEBUG] no config file loaded, using defaults:", err)
119+
}
120+
return nil
121+
}
122+
123+
// ensureProvider builds the provider client if it hasn't been already.
124+
// Cobra's shell-completion machinery (`__complete`) resolves
125+
// ValidArgsFunction without running PersistentPreRunE
126+
// (https://github.com/spf13/cobra/issues/1291), so completion functions that
127+
// call provider.List() (destroy, ssh) must invoke this themselves, or they'd
128+
// dereference a nil provider.
129+
func ensureProvider() {
130+
if provider != nil {
131+
return
77132
}
78-
// images command handles its own provider init to avoid fatal-on-missing-credentials
79-
// for providers that don't support image listing.
80-
if len(os.Args) > 1 && os.Args[1] == "images" {
81-
return rootCmd.Execute()
133+
if err := initState(); err != nil {
134+
log.Println("[DEBUG] completion: " + err.Error())
135+
return
82136
}
137+
initProvider(cloudProvider)
138+
}
139+
140+
// initProvider builds the global provider client for the selected cloud.
141+
func initProvider(cloudProvider string) {
83142
switch cloudProvider {
84143
case "hetzner":
85144
provider = &cloud.ProviderHetzner{
@@ -122,10 +181,10 @@ func Execute() error {
122181
Rootfs: providerfirecracker.NewRootfsPreparer(),
123182
}
124183
}
125-
return rootCmd.Execute()
126184
}
127185

128186
func init() {
187+
rootCmd.PersistentFlags().StringVar(&providerFlag, "provider", "", "cloud provider: "+strings.Join(cloudProviderList, ", ")+" (overrides ONCTL_CLOUD)")
129188
rootCmd.AddCommand(versionCmd)
130189
rootCmd.AddCommand(initCmd)
131190
}

‎cmd/ssh.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ var sshCmd = &cobra.Command{
7474
TraverseChildren: true,
7575
DisableFlagsInUseLine: true,
7676
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
77+
ensureProvider()
78+
if provider == nil {
79+
return nil, cobra.ShellCompDirectiveError
80+
}
7781
VMList, err := provider.List()
7882
list := []string{}
7983
for _, vm := range VMList.List {

‎internal/files/init/hetzner.yaml‎

Lines changed: 0 additions & 6 deletions
This file was deleted.

‎internal/files/init/onctl.yaml‎

Lines changed: 0 additions & 11 deletions
This file was deleted.

0 commit comments

Comments
 (0)
⌂ 换网址