Sitelet https://github.com/kubernetes/kops/commit/8d428558f4551dbc2285710ff0f3048e03c2e75c
Skip to content

Commit 8d42855

Browse files
committed
kops create cluster: reject explicitly empty --project flag
1 parent e078f00 commit 8d42855

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

‎cmd/kops/create_cluster.go‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,10 @@ func NewCmdCreateCluster(f *util.Factory, out io.Writer) *cobra.Command {
212212
options.EncryptEtcdStorage = &encryptEtcdStorage
213213
}
214214

215+
if err := checkProjectFlag(cmd.Flag("project").Changed, options.Project); err != nil {
216+
return err
217+
}
218+
215219
if sshPublicKey != "" {
216220
options.SSHPublicKeys, err = loadSSHPublicKeys(sshPublicKey)
217221
if err != nil {
@@ -931,6 +935,16 @@ func RunCreateCluster(ctx context.Context, f *util.Factory, out io.Writer, c *Cr
931935
return nil
932936
}
933937

938+
// checkProjectFlag rejects an explicitly empty --project flag. An empty value usually comes from
939+
// an unset environment variable (e.g. --project=$PROJECT); silently accepting it would fall back
940+
// to the gcloud default project, which may not be the intended one.
941+
func checkProjectFlag(flagSet bool, project string) error {
942+
if flagSet && project == "" {
943+
return fmt.Errorf("--project cannot be empty; specify a project or omit the flag to use the gcloud default project")
944+
}
945+
return nil
946+
}
947+
934948
// parseCloudLabels takes a CSV list of key=value records and parses them into a map. Nested '='s are supported via
935949
// quoted strings (eg `foo="bar=baz"` parses to map[string]string{"foo":"bar=baz"}. Nested commas are not supported.
936950
func parseCloudLabels(s string) (map[string]string, error) {

‎cmd/kops/create_cluster_test.go‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,28 @@ import (
2020
"testing"
2121
)
2222

23+
func TestCheckProjectFlag(t *testing.T) {
24+
grid := []struct {
25+
flagSet bool
26+
project string
27+
shouldErr bool
28+
}{
29+
{flagSet: false, project: "", shouldErr: false},
30+
{flagSet: true, project: "my-project", shouldErr: false},
31+
{flagSet: true, project: "", shouldErr: true},
32+
}
33+
34+
for _, g := range grid {
35+
err := checkProjectFlag(g.flagSet, g.project)
36+
if g.shouldErr && err == nil {
37+
t.Errorf("checkProjectFlag(%v, %q): expected error, got nil", g.flagSet, g.project)
38+
}
39+
if !g.shouldErr && err != nil {
40+
t.Errorf("checkProjectFlag(%v, %q): unexpected error: %v", g.flagSet, g.project, err)
41+
}
42+
}
43+
}
44+
2345
func TestParseCloudLabels(t *testing.T) {
2446
expect := map[string]string{"foo": "bar", "fib": "baz"}
2547
checkParse(t, "", map[string]string{}, false)

0 commit comments

Comments
 (0)