Skip to content

Commit bf329bc

Browse files
committed
Merge azure CLI flags integration
Completes wiring for azure (subscription, resource group, type etc) so it matches other providers under the single onctl.yaml setup.
2 parents 492eeb7 + 0f95338 commit bf329bc

5 files changed

Lines changed: 118 additions & 2 deletions

File tree

‎cmd/create.go‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ var (
5151
// the placeholder in onctl.yaml's gcp.project (the one GCP setting with
5252
// no static default; it's account-specific).
5353
flagGCPProject string
54+
// Azure account-specific flags (moved to persistent in root so resolve
55+
// works for ls/destroy/ssh too, not just create). Bound to azure.* .
56+
flagAzureSubscriptionID string
57+
flagAzureResourceGroup string
5458
)
5559

5660
func parseConfigFile(configFile string) (*cmdCreateOptions, error) {
@@ -87,6 +91,11 @@ func init() {
8791
createCmd.Flags().StringVarP(&opt.ConfigFile, "file", "f", "", "Path to configuration YAML file")
8892
createCmd.Flags().StringVar(&opt.Vm.Image, "image", "", "OS image to use (e.g. ubuntu-22.04, fedora-42)")
8993

94+
// Register Azure special flags locally too (root registers them as persistent
95+
// for ls/destroy etc). This makes Lookup work and shows them under create --help.
96+
createCmd.Flags().StringVar(&flagAzureSubscriptionID, "subscription-id", "", "Azure: subscription ID (required for the azure provider; falls back to `az account show`)")
97+
createCmd.Flags().StringVar(&flagAzureResourceGroup, "resource-group", "", "Azure: resource group (required for the azure provider; falls back to the az CLI's configured default group, if any)")
98+
9099
// Generic VM flags, bound to the viper key the rest of the code already
91100
// reads. The hetzner.* defaults live in internal/files/init/onctl.yaml,
92101
// written by `onctl init`; these flag defaults only act as a last-resort
@@ -120,6 +129,16 @@ func init() {
120129
_ = viper.BindPFlag("gcp.type", createCmd.Flags().Lookup("type"))
121130
_ = viper.BindPFlag("gcp.vm.username", createCmd.Flags().Lookup("username"))
122131

132+
// Azure. Bind generics + the two account-specific ones.
133+
// subscriptionId and resourceGroup have no static defaults (placeholders
134+
// in onctl.yaml); --subscription-id / --resource-group + resolve fill them.
135+
// Use root persistent lookups because those flags are registered as persistent.
136+
_ = viper.BindPFlag("azure.subscriptionId", rootCmd.PersistentFlags().Lookup("subscription-id"))
137+
_ = viper.BindPFlag("azure.resourceGroup", rootCmd.PersistentFlags().Lookup("resource-group"))
138+
_ = viper.BindPFlag("azure.location", createCmd.Flags().Lookup("location"))
139+
_ = viper.BindPFlag("azure.vm.type", createCmd.Flags().Lookup("type"))
140+
_ = viper.BindPFlag("azure.vm.username", createCmd.Flags().Lookup("username"))
141+
123142
// Firecracker-specific flags, each bound to the fc.* key read by
124143
// providerfc.GetConfig. Defaults live in onctl.yaml's fc: section (and
125144
// providerfc.GetConfig has its own inline fallback besides). The generic

‎cmd/flags_defaults_test.go‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ import (
1313
// TestGenericCreateFlagsExist verifies the YAML-replacing flags are registered.
1414
func TestGenericCreateFlagsExist(t *testing.T) {
1515
for _, name := range []string{"type", "location", "username", "cloud-init-timeout", "image",
16-
"kernel-image", "rootfs-image", "fc-binary", "vcpu", "memory", "project"} {
16+
"kernel-image", "rootfs-image", "fc-binary", "vcpu", "memory", "project",
17+
"subscription-id", "resource-group"} {
1718
assert.NotNil(t, createCmd.Flags().Lookup(name), "create should have --%s flag", name)
1819
}
1920
assert.NotNil(t, rootCmd.PersistentFlags().Lookup("provider"), "root should have persistent --provider flag")
@@ -64,6 +65,10 @@ func TestCreateFlagsBindToViper(t *testing.T) {
6465
// resolved via gcloud or --project; tested separately).
6566
{"type", "gcp.type", "n1-standard-1", "n2-standard-2"},
6667
{"location", "gcp.zone", "europe-west4-a", "us-central1-a"},
68+
// Azure (from onctl.yaml azure: section).
69+
{"type", "azure.vm.type", "Standard_D4s_v3", "Standard_D8s_v3"},
70+
{"location", "azure.location", "westeurope", "northeurope"},
71+
{"username", "azure.vm.username", "azureuser", "adminuser"},
6772
}
6873
// Check every default before mutating any flag. Several keys share a
6974
// flag with a different per-provider default (e.g. --type backs both
@@ -77,17 +82,19 @@ func TestCreateFlagsBindToViper(t *testing.T) {
7782
}
7883
assert.Equal(t, "root", viper.GetString("fc.vm.username"))
7984
assert.Equal(t, "root", viper.GetString("gcp.vm.username"))
85+
assert.Equal(t, "azureuser", viper.GetString("azure.vm.username"))
8086

8187
for _, c := range cases {
8288
assert.NoError(t, createCmd.Flags().Set(c.flag, c.override))
8389
assert.Equal(t, c.override, viper.GetString(c.key), "override for %s", c.key)
8490
assert.NoError(t, createCmd.Flags().Set(c.flag, c.def))
8591
}
8692

87-
// The generic --username flag drives the Firecracker and GCP users too.
93+
// The generic --username flag drives the Firecracker , GCP and Azure users too.
8894
assert.NoError(t, createCmd.Flags().Set("username", "admin"))
8995
assert.Equal(t, "admin", viper.GetString("fc.vm.username"))
9096
assert.Equal(t, "admin", viper.GetString("gcp.vm.username"))
97+
assert.Equal(t, "admin", viper.GetString("azure.vm.username"))
9198

9299
// Restore the shared flags to their own intrinsic defaults (not
93100
// whichever per-provider case happened to run last) so sibling tests in

‎cmd/root.go‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,11 @@ func initState() error {
118118
return err
119119
}
120120
}
121+
if cloudProvider == "azure" {
122+
if err := resolveAzureIdentifiers(); err != nil {
123+
return err
124+
}
125+
}
121126
return nil
122127
}
123128

@@ -139,6 +144,32 @@ func resolveGCPProject() error {
139144
return fmt.Errorf(`gcp.project is required: set --project, edit .onctl/onctl.yaml, or run "gcloud config set project <id>"`)
140145
}
141146

147+
// resolveAzureIdentifiers fills azure.subscriptionId and azure.resourceGroup
148+
// from az CLI when the onctl.yaml still has the placeholders. Both are
149+
// required to talk to Azure; the resource group one may legitimately stay
150+
// empty for users who always pass it or set it in az defaults.
151+
func resolveAzureIdentifiers() error {
152+
sub := viper.GetString("azure.subscriptionId")
153+
if sub == "" || sub == "<subscription-id>" {
154+
if id := providerazure.AzureCLISubscriptionID(); id != "" {
155+
viper.Set("azure.subscriptionId", id)
156+
log.Printf("[DEBUG] resolved azure.subscriptionId from az: %s", id)
157+
} else {
158+
return fmt.Errorf(`azure.subscriptionId is required: set --subscription-id, edit .onctl/onctl.yaml, or run "az login"`)
159+
}
160+
}
161+
162+
rg := viper.GetString("azure.resourceGroup")
163+
if rg == "" || rg == "test" { // "test" is the placeholder/default in onctl.yaml
164+
if group := providerazure.AzureCLIDefaultResourceGroup(); group != "" {
165+
viper.Set("azure.resourceGroup", group)
166+
log.Printf("[DEBUG] resolved azure.resourceGroup from az: %s", group)
167+
}
168+
// If still empty it's ok for some users; the provider will error later if needed.
169+
}
170+
return nil
171+
}
172+
142173
// ensureProvider builds the provider client if it hasn't been already.
143174
// Cobra's shell-completion machinery (`__complete`) resolves
144175
// ValidArgsFunction without running PersistentPreRunE
@@ -204,6 +235,11 @@ func initProvider(cloudProvider string) {
204235

205236
func init() {
206237
rootCmd.PersistentFlags().StringVarP(&providerFlag, "provider", "p", "", "cloud provider: "+strings.Join(cloudProviderList, ", ")+" (overrides ONCTL_CLOUD)")
238+
// Azure account-specific settings are needed for many commands (ls, ssh,
239+
// destroy...), not just create. Register as persistent so resolve runs
240+
// and flags are available everywhere for the azure provider.
241+
rootCmd.PersistentFlags().StringVar(&flagAzureSubscriptionID, "subscription-id", "", "Azure: subscription ID (required for the azure provider; falls back to `az account show`)")
242+
rootCmd.PersistentFlags().StringVar(&flagAzureResourceGroup, "resource-group", "", "Azure: resource group (required for the azure provider; falls back to the az CLI's configured default group, if any)")
207243
rootCmd.AddCommand(versionCmd)
208244
rootCmd.AddCommand(initCmd)
209245
}

‎cmd/root_test.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,3 +87,21 @@ func TestResolveGCPProject(t *testing.T) {
8787
assert.Contains(t, err.Error(), "gcp.project is required")
8888
})
8989
}
90+
91+
func TestResolveAzureIdentifiers(t *testing.T) {
92+
origSub := viper.GetString("azure.subscriptionId")
93+
origRG := viper.GetString("azure.resourceGroup")
94+
defer func() {
95+
viper.Set("azure.subscriptionId", origSub)
96+
viper.Set("azure.resourceGroup", origRG)
97+
}()
98+
99+
t.Run("subscription placeholder without az errors clearly", func(t *testing.T) {
100+
viper.Set("azure.subscriptionId", "<subscription-id>")
101+
viper.Set("azure.resourceGroup", "test")
102+
t.Setenv("PATH", "") // no az
103+
err := resolveAzureIdentifiers()
104+
assert.Error(t, err)
105+
assert.Contains(t, err.Error(), "azure.subscriptionId is required")
106+
})
107+
}

‎internal/providerazure/common.go‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
package providerazure
22

33
import (
4+
"context"
45
"log"
6+
"os/exec"
7+
"strings"
8+
"time"
59

610
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
711
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
@@ -110,3 +114,35 @@ func connectionAzure() (azcore.TokenCredential, error) {
110114
}
111115
return cred, nil
112116
}
117+
118+
func runAzCLI(args ...string) string {
119+
if _, err := exec.LookPath("az"); err != nil {
120+
return ""
121+
}
122+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
123+
defer cancel()
124+
out, err := exec.CommandContext(ctx, "az", args...).Output()
125+
if err != nil {
126+
return ""
127+
}
128+
value := strings.TrimSpace(string(out))
129+
if value == "" || value == "null" {
130+
return ""
131+
}
132+
return value
133+
}
134+
135+
// AzureCLISubscriptionID best-effort resolves the az CLI's active
136+
// subscription (the same one `az` commands run against), so onctl can
137+
// default azure.subscriptionId to it when the value in onctl.yaml is still
138+
// the placeholder or unset. Returns "" if az isn't installed/logged in or errors.
139+
func AzureCLISubscriptionID() string {
140+
return runAzCLI("account", "show", "--query", "id", "-o", "tsv")
141+
}
142+
143+
// AzureCLIDefaultResourceGroup best-effort resolves the az CLI's configured
144+
// default resource group (`az configure --defaults group=<name>`).
145+
// Most users won't have this set (opt-in), so empty is normal.
146+
func AzureCLIDefaultResourceGroup() string {
147+
return runAzCLI("config", "get", "defaults.group", "--query", "value", "-o", "tsv")
148+
}

0 commit comments

Comments
 (0)
⌂ 换网址