Skip to content

Commit

Permalink
add clean command
Browse files Browse the repository at this point in the history
  • Loading branch information
ryota-sakamoto committed Jun 16, 2024
1 parent a9236c8 commit 4c093fa
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
19 changes: 19 additions & 0 deletions pkg/cmd/clean.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package cmd

import (
"github.com/ryota-sakamoto/kubernetes-on-multipass/pkg/provisioner"
"github.com/spf13/cobra"
)

var cleanCmd = &cobra.Command{
Use: "clean",
Short: "Clean up a cluster",
RunE: func(cmd *cobra.Command, args []string) error {
return provisioner.Clean(cmd.Flag("cluster-name").Value.String())
},
}

func init() {
rootCmd.AddCommand(cleanCmd)
cleanCmd.Flags().StringP("cluster-name", "", "kubernetes", "Cluster name")
}
18 changes: 18 additions & 0 deletions pkg/multipass/multipass.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,24 @@ func LaunchInstance(config InstanceConfig, cloudinit string) error {
return err
}

func DeleteInstance(name string) error {
_, err := exec.Command("multipass", "delete", name).Output()
if err != nil {
return err
}

return nil
}

func Purge() error {
_, err := exec.Command("multipass", "purge").Output()
if err != nil {
return err
}

return nil
}

func Exec(name string, command string) (string, error) {
args := []string{"exec", name, "--"}
args = append(args, strings.Fields(command)...)
Expand Down
25 changes: 25 additions & 0 deletions pkg/provisioner/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"log/slog"
"os"
"strings"

"github.com/goccy/go-yaml"
"k8s.io/apimachinery/pkg/runtime"
Expand Down Expand Up @@ -148,3 +149,27 @@ func GenerateKubeconfig(name string) error {

return nil
}

func Clean(clusterName string) error {
slog.Debug("clean", slog.String("clusterName", clusterName))

instances, err := multipass.ListInstances()
if err != nil {
return fmt.Errorf("failed to list instances: %w", err)
}

for _, instance := range instances.List {
if !strings.HasPrefix(instance.Name, clusterName) {
continue
}

slog.Debug("delete instance", slog.String("name", instance.Name))
err := multipass.DeleteInstance(instance.Name)
if err != nil {
return fmt.Errorf("failed to delete instance: %w", err)
}
}

slog.Debug("purge instances")
return multipass.Purge()
}

0 comments on commit 4c093fa

Please sign in to comment.