diff --git a/pkg/cluster/createoption.go b/pkg/cluster/createoption.go index b93ab55307..352adf984e 100644 --- a/pkg/cluster/createoption.go +++ b/pkg/cluster/createoption.go @@ -94,6 +94,14 @@ func CreateWithAvoidCreation(avoidCreation bool) CreateOption { }) } +// CreateWithWaitForceDelete removes local cluster container +func CreateWithForceDelete(forceDelete bool) CreateOption { + return createOptionAdapter(func(o *internalcreate.ClusterOptions) error { + o.ForceDelete = forceDelete + return nil + }) +} + // CreateWithWaitForReady configures a maximum wait time for the control plane // node(s) to be ready. By default no waiting is performed func CreateWithWaitForReady(waitTime time.Duration) CreateOption { diff --git a/pkg/cluster/internal/create/create.go b/pkg/cluster/internal/create/create.go index 9311700d35..24986bb447 100644 --- a/pkg/cluster/internal/create/create.go +++ b/pkg/cluster/internal/create/create.go @@ -59,6 +59,8 @@ type ClusterOptions struct { DescriptorPath string MoveManagement bool AvoidCreation bool + // Force local container delete before creating the cluster if it already exists + ForceDelete bool // NodeImage overrides the nodes' images in Config if non-zero NodeImage string Retain bool @@ -85,7 +87,13 @@ func Cluster(logger log.Logger, p providers.Provider, opts *ClusterOptions) erro // Check if the cluster name already exists if err := alreadyExists(p, opts.Config.Name); err != nil { - return err + if opts.ForceDelete { + // Delete current cluster container + _ = delete.Cluster(nil, p, opts.Config.Name, "") + } else { + return errors.Errorf("A cluster with the name %q already exists \n"+ + "Please use a different cluster name or delete the current container with --delete-previous flag", opts.Config.Name) + } } // warn if cluster name might typically be too long diff --git a/pkg/cmd/kind/create/cluster/createcluster.go b/pkg/cmd/kind/create/cluster/createcluster.go index cc2cb789bc..9d486deed6 100644 --- a/pkg/cmd/kind/create/cluster/createcluster.go +++ b/pkg/cmd/kind/create/cluster/createcluster.go @@ -51,6 +51,7 @@ type flagpole struct { DescriptorPath string MoveManagement bool AvoidCreation bool + ForceDelete bool } const clusterDefaultPath = "./cluster.yaml" @@ -132,6 +133,12 @@ func NewCommand(logger log.Logger, streams cmd.IOStreams) *cobra.Command { false, "by setting this flag the worker cluster won't be created", ) + cmd.Flags().BoolVar( + &flags.ForceDelete, + "delete-previous", + false, + "by setting this flag the local cluster will be deleted", + ) return cmd } @@ -197,6 +204,7 @@ func runE(logger log.Logger, streams cmd.IOStreams, flags *flagpole) error { cluster.CreateWithRetain(flags.Retain), cluster.CreateWithMove(flags.MoveManagement), cluster.CreateWithAvoidCreation(flags.AvoidCreation), + cluster.CreateWithForceDelete(flags.ForceDelete), cluster.CreateWithWaitForReady(flags.Wait), cluster.CreateWithKubeconfigPath(flags.Kubeconfig), cluster.CreateWithDisplayUsage(true),