github.com/vmware/govmomi@v0.43.0/govc/vm/destroy.go (about) 1 /* 2 Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package vm 18 19 import ( 20 "context" 21 "flag" 22 23 "github.com/vmware/govmomi/govc/cli" 24 "github.com/vmware/govmomi/govc/flags" 25 "github.com/vmware/govmomi/object" 26 "github.com/vmware/govmomi/vim25/types" 27 ) 28 29 type destroy struct { 30 *flags.ClientFlag 31 *flags.SearchFlag 32 } 33 34 func init() { 35 cli.Register("vm.destroy", &destroy{}) 36 } 37 38 func (cmd *destroy) Register(ctx context.Context, f *flag.FlagSet) { 39 cmd.ClientFlag, ctx = flags.NewClientFlag(ctx) 40 cmd.ClientFlag.Register(ctx, f) 41 42 cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines) 43 cmd.SearchFlag.Register(ctx, f) 44 } 45 46 func (cmd *destroy) Process(ctx context.Context) error { 47 if err := cmd.ClientFlag.Process(ctx); err != nil { 48 return err 49 } 50 if err := cmd.SearchFlag.Process(ctx); err != nil { 51 return err 52 } 53 return nil 54 } 55 56 func (cmd *destroy) Usage() string { 57 return "VM..." 58 } 59 60 func (cmd *destroy) Description() string { 61 return `Power off and delete VM. 62 63 When a VM is destroyed, any attached virtual disks are also deleted. 64 Use the 'device.remove -vm VM -keep disk-*' command to detach and 65 keep disks if needed, prior to calling vm.destroy. 66 67 Examples: 68 govc vm.destroy my-vm` 69 } 70 71 func (cmd *destroy) Run(ctx context.Context, f *flag.FlagSet) error { 72 vms, err := cmd.VirtualMachines(f.Args()) 73 if err != nil { 74 return err 75 } 76 77 for _, vm := range vms { 78 var ( 79 task *object.Task 80 state types.VirtualMachinePowerState 81 ) 82 83 state, err = vm.PowerState(ctx) 84 if err != nil { 85 return err 86 } 87 88 if state == types.VirtualMachinePowerStatePoweredOn { 89 task, err = vm.PowerOff(ctx) 90 if err != nil { 91 return err 92 } 93 94 // Ignore error since the VM may already been in powered off state. 95 // vm.Destroy will fail if the VM is still powered on. 96 _ = task.Wait(ctx) 97 } 98 99 task, err = vm.Destroy(ctx) 100 if err != nil { 101 return err 102 } 103 104 if err = task.Wait(ctx); err != nil { 105 return err 106 } 107 } 108 109 return nil 110 }