github.com/coreos/mantle@v0.13.0/cmd/ore/gcloud/destroy.go (about)

     1  // Copyright 2015 CoreOS, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package gcloud
    16  
    17  import (
    18  	"fmt"
    19  	"os"
    20  
    21  	"github.com/spf13/cobra"
    22  )
    23  
    24  var (
    25  	cmdDestroy = &cobra.Command{
    26  		Use:   "destroy-instances --prefix=<prefix> ",
    27  		Short: "destroy cluster on GCE",
    28  		Long:  "Destroy GCE instances based on name prefix.",
    29  		Run:   runDestroy,
    30  	}
    31  )
    32  
    33  func init() {
    34  	GCloud.AddCommand(cmdDestroy)
    35  }
    36  
    37  func runDestroy(cmd *cobra.Command, args []string) {
    38  	if len(args) != 0 {
    39  		fmt.Fprintf(os.Stderr, "Unrecognized args in ore list cmd: %v\n", args)
    40  		os.Exit(2)
    41  	}
    42  
    43  	// avoid wiping out all instances in project or mishaps with short destroyPrefixes
    44  	if opts.BaseName == "" || len(opts.BaseName) < 2 {
    45  		fmt.Fprintf(os.Stderr, "Please specify a prefix of length 2 or greater with -prefix\n")
    46  		os.Exit(1)
    47  	}
    48  
    49  	vms, err := api.ListInstances(opts.BaseName)
    50  	if err != nil {
    51  		fmt.Fprintf(os.Stderr, "Failed listing vms: %v\n", err)
    52  		os.Exit(1)
    53  	}
    54  
    55  	var count int
    56  	for _, vm := range vms {
    57  		if err := api.TerminateInstance(vm.Name); err != nil {
    58  			fmt.Fprintf(os.Stderr, "Failed destroying vm: %v\n", err)
    59  			os.Exit(1)
    60  		}
    61  		count++
    62  	}
    63  
    64  	fmt.Printf("%v instance(s) scheduled for deletion\n", count)
    65  }