Skip to content

Commit a4c464d

Browse files
Add automatic namespace provisioning before deployment
1 parent 2982cab commit a4c464d

2 files changed

Lines changed: 76 additions & 3 deletions

File tree

pkg/deploy/deploy.go

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,22 @@ func Run(envName string, dryRun bool) error {
99
return err
1010
}
1111

12-
////////////////////////////////////////////////////
13-
// PREFLIGHT FIRST
14-
////////////////////////////////////////////////////
12+
////////////////////////////////////
13+
// PREFLIGHT
14+
////////////////////////////////////
1515

1616
if err := Preflight(environment); err != nil {
1717
return err
1818
}
1919

20+
////////////////////////////////////
21+
// ENSURE NAMESPACE
22+
////////////////////////////////////
23+
24+
if err := EnsureNamespace(environment); err != nil {
25+
return err
26+
}
27+
2028
command, _, err := BuildCommand(environment)
2129
if err != nil {
2230
return err

pkg/deploy/namespace.go

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package deploy
2+
3+
import (
4+
"fmt"
5+
"os/exec"
6+
7+
"github.com/aryansharma9917/codewise-cli/pkg/env"
8+
)
9+
10+
func namespaceExists(namespace string, context string) bool {
11+
12+
args := []string{"get", "ns", namespace}
13+
14+
if context != "" {
15+
args = append(args, "--context", context)
16+
}
17+
18+
cmd := exec.Command("kubectl", args...)
19+
20+
if err := cmd.Run(); err != nil {
21+
return false
22+
}
23+
24+
return true
25+
}
26+
27+
func createNamespace(namespace string, context string) error {
28+
29+
args := []string{"create", "ns", namespace}
30+
31+
if context != "" {
32+
args = append(args, "--context", context)
33+
}
34+
35+
cmd := exec.Command("kubectl", args...)
36+
37+
output, err := cmd.CombinedOutput()
38+
if err != nil {
39+
return fmt.Errorf("failed to create namespace: %s", string(output))
40+
}
41+
42+
return nil
43+
}
44+
45+
func EnsureNamespace(environment *env.Env) error {
46+
47+
ns := environment.K8s.Namespace
48+
ctx := environment.K8s.Context
49+
50+
fmt.Printf("Checking namespace \"%s\"...\n", ns)
51+
52+
if namespaceExists(ns, ctx) {
53+
fmt.Println("Namespace exists")
54+
return nil
55+
}
56+
57+
fmt.Println("Namespace not found. Creating namespace...")
58+
59+
if err := createNamespace(ns, ctx); err != nil {
60+
return err
61+
}
62+
63+
fmt.Println("Namespace created")
64+
return nil
65+
}

0 commit comments

Comments
 (0)