To destroy a VM from the VMware environment

    CLI Example:

    .. code-block:: bash

        salt-cloud -d vmname
        salt-cloud --destroy vmname
        salt-cloud -a destroy vmname
5600
def destroy(name, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    __utils__['cloud.fire_event'](
        'event',
        'destroying instance',
        'salt/cloud/{0}/destroying'.format(name),
        args={'name': name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    vm_properties = [
        "name",
        "summary.runtime.powerState"
    ]

    vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)

    for vm in vm_list:
        if vm["name"] == name:
            if vm["summary.runtime.powerState"] != "poweredOff":
                # Power off the vm first
                try:
                    log.info('Powering Off VM %s', name)
                    task = vm["object"].PowerOff()
                    salt.utils.vmware.wait_for_task(task, name, 'power off')
                except Exception as exc:
                    log.error(
                        'Error while powering off VM %s: %s',
                        name, exc,
                        # Show the traceback if the debug logging level is enabled
                        exc_info_on_loglevel=logging.DEBUG
                    )
                    return 'failed to destroy'
            try:
                log.info('Destroying VM %s', name)
                task = vm["object"].Destroy_Task()
                salt.utils.vmware.wait_for_task(task, name, 'destroy')
            except Exception as exc:
                log.error(
                    'Error while destroying VM %s: %s',
                    name, exc,
                    # Show the traceback if the debug logging level is enabled
                    exc_info_on_loglevel=logging.DEBUG
                )
                return 'failed to destroy'

    __utils__['cloud.fire_event'](
        'event',
        'destroyed instance',
        'salt/cloud/{0}/destroyed'.format(name),
        args={'name': name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    if __opts__.get('update_cachedir', False) is True:
        __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)

    return True
1270552
def _erase_vm_info(name):
    '''
    
    '''
    try:
        # delete the machine record
        vm_ = get_vm_info(name)
        if vm_['machine']:
            key = _build_machine_uri(vm_['machine'], vm_.get('cwd', '.'))
            try:
                __utils__['sdb.sdb_delete'](key, __opts__)
            except KeyError:
                # no delete method found -- load a blank value
                __utils__['sdb.sdb_set'](key, None, __opts__)
    except Exception:
        pass

    uri = _build_sdb_uri(name)
    try:
        # delete the name record
        __utils__['sdb.sdb_delete'](uri, __opts__)
    except KeyError:
        # no delete method found -- load an empty dictionary
        __utils__['sdb.sdb_set'](uri, {}, __opts__)
    except Exception:
        pass
1208610
def destroy(name, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    __utils__['cloud.fire_event'](
        'event',
        'destroying instance',
        'salt/cloud/{0}/destroying'.format(name),
        args={'name': name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    response = _query('grid', 'server/delete', args={'name': name})

    __utils__['cloud.fire_event'](
        'event',
        'destroyed instance',
        'salt/cloud/{0}/destroyed'.format(name),
        args={'name': name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    if __opts__.get('update_cachedir', False) is True:
        __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)

    return response
1320401
def uninstall
      vm.Event[:unload].call(self.name)
      vm.Delayer.new do
        @events.map(&:detach)
        @filters.map(&:detach)
        self.class.destroy name
      end
      self end
957663
def remove(name, conf_file=default_conf):
    '''
    
    '''
    command = "logadm -f {0} -r {1}".format(conf_file, name)
    result = __salt__['cmd.run_all'](command, python_shell=False)
    if result['retcode'] != 0:
        return dict(
            Error='Failure in removing log. Possibly already removed?',
            Output=result['stderr']
        )
    return dict(Result='Success')
611266
def stop(name):
    '''
    
    '''
    vm_ = get_vm_info(name)
    machine = vm_['machine']

    cmd = 'vagrant halt {}'.format(machine)
    ret = __salt__['cmd.retcode'](cmd,
                                  runas=vm_.get('runas'),
                                  cwd=vm_.get('cwd'))
    return ret == 0
1218204
def destroy(name):
    '''
    
    '''
    vm_ = get_vm_info(name)
    machine = vm_['machine']

    cmd = 'vagrant destroy -f {}'.format(machine)

    ret = __salt__['cmd.run_all'](cmd,
                                  runas=vm_.get('runas'),
                                  cwd=vm_.get('cwd'),
                                  output_loglevel='info')
    if ret['retcode'] == 0:
        _erase_vm_info(name)
        return 'Destroyed VM {0}'.format(name)
    return False
931937
private String destroyAs(String[] args) throws Exception {
        if (args.length < 4) {
            return M3UAOAMMessages.INVALID_COMMAND;
        }

        String asName = args[3];
        if (asName == null) {
            return M3UAOAMMessages.INVALID_COMMAND;
        }

        String m3uaStackName = null;

        if (args.length > 4) {
            if (!args[4].equals("stackname")) {
                return M3UAOAMMessages.INVALID_COMMAND;
            }

            m3uaStackName = args[5];
            M3UAManagementImpl m3uaManagementtmp = this.m3uaManagements.get(m3uaStackName);

            if (m3uaManagementtmp == null) {
                return String.format(M3UAOAMMessages.NO_M3UA_MANAGEMENT_BEAN_FOR_NAME, m3uaStackName);
            }

            this.m3uaManagement = m3uaManagementtmp;
        } else {
            this.setDefaultValue();
        }

        AsImpl asImpl = this.m3uaManagement.destroyAs(asName);

        return String.format(M3UAOAMMessages.DESTROY_AS_SUCESSFULL, asName, this.m3uaManagement.getName());
    }
1016445
def destroy_template(name=None, call=None, kwargs=None):
    '''
    

    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The destroy_template function must be called with  -f.'
        )
    if kwargs is None:
        kwargs = {}
    name = kwargs.get('name', None)
    session = _get_session()
    vms = session.xenapi.VM.get_all_records()
    ret = {}
    found = False
    for vm in vms:
        record = session.xenapi.VM.get_record(vm)
        if record['is_a_template']:
            if record['name_label'] == name:
                found = True
                # log.debug(record['name_label'])
                session.xenapi.VM.destroy(vm)
                ret[name] = {'status': 'destroyed'}
    if not found:
        ret[name] = {'status': 'not found'}
    return ret
51923
def delete_lb(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The delete_hc function must be called with -f or --function.'
        )

    if not kwargs or 'name' not in kwargs:
        log.error(
            'A name must be specified when deleting a health check.'
        )
        return False

    name = kwargs['name']
    lb_conn = get_lb_conn(get_conn())

    __utils__['cloud.fire_event'](
        'event',
        'delete load_balancer',
        'salt/cloud/loadbalancer/deleting',
        args={
            'name': name,
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    try:
        result = lb_conn.destroy_balancer(
            lb_conn.get_balancer(name)
        )
    except ResourceNotFoundError as exc:
        log.error(
            'Load balancer %s was not found. Exception was: %s',
            name, exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False

    __utils__['cloud.fire_event'](
        'event',
        'deleted load_balancer',
        'salt/cloud/loadbalancer/deleted',
        args={
            'name': name,
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return result
1218329
def script(vm_):
    '''
    
    '''
    script_name = config.get_cloud_config_value('script', vm_, __opts__)
    if not script_name:
        script_name = 'bootstrap-salt'

    return salt.utils.cloud.os_script(
        script_name,
        vm_,
        __opts__,
        salt.utils.cloud.salt_config_to_yaml(
            salt.utils.cloud.minion_config(__opts__, vm_)
        )
    )
1133656
def delete_service(kwargs=None, conn=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The delete_service function must be called with -f or --function.'
        )

    if kwargs is None:
        kwargs = {}

    if 'name' not in kwargs:
        raise SaltCloudSystemExit('A name must be specified as "name"')

    if not conn:
        conn = get_conn()

    try:
        conn.delete_hosted_service(kwargs['name'])
        return {'Success': 'The service was successfully deleted'}
    except AzureMissingResourceHttpError as exc:
        raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
643269
def delete(event, saltenv='base', test=None):
    '''
    
    '''
    sevent = salt.utils.event.get_event(
            'master',
            __opts__['sock_dir'],
            __opts__['transport'],
            opts=__opts__,
            listen=True)

    master_key = salt.utils.master.get_master_key('root', __opts__)

    __jid_event__.fire_event({'event': event, 'key': master_key}, 'salt/reactors/manage/delete')

    res = sevent.get_event(wait=30, tag='salt/reactors/manage/delete-complete')
    return res['result']
1043415
def destroy(zpool, force=False):
    '''
    

    '''
    # destroy zpool
    res = __salt__['cmd.run_all'](
        __utils__['zfs.zpool_command'](
            command='destroy',
            flags=['-f'] if force else None,
            target=zpool,
        ),
        python_shell=False,
    )

    return __utils__['zfs.parse_command_result'](res, 'destroyed')
91564
def destroy(self, names, cached=False):
        '''
        
        '''
        processed = {}
        names = set(names)
        matching = self.get_running_by_names(names, cached=cached)
        vms_to_destroy = set()
        parallel_data = []
        for alias, drivers in six.iteritems(matching):
            for driver, vms in six.iteritems(drivers):
                for name in vms:
                    if name in names:
                        vms_to_destroy.add((alias, driver, name))
                        if self.opts['parallel']:
                            parallel_data.append({
                                'opts': self.opts,
                                'name': name,
                                'alias': alias,
                                'driver': driver,
                            })

        # destroying in parallel
        if self.opts['parallel'] and parallel_data:
            # set the pool size based on configuration or default to
            # the number of machines we're destroying
            if 'pool_size' in self.opts:
                pool_size = self.opts['pool_size']
            else:
                pool_size = len(parallel_data)
            log.info('Destroying in parallel mode; '
                     'Cloud pool size: %s', pool_size)

            # kick off the parallel destroy
            output_multip = enter_mainloop(
                _destroy_multiprocessing, parallel_data, pool_size=pool_size)

            # massage the multiprocessing output a bit
            ret_multip = {}
            for obj in output_multip:
                ret_multip.update(obj)

            # build up a data structure similar to what the non-parallel
            # destroy uses
            for obj in parallel_data:
                alias = obj['alias']
                driver = obj['driver']
                name = obj['name']
                if alias not in processed:
                    processed[alias] = {}
                if driver not in processed[alias]:
                    processed[alias][driver] = {}
                processed[alias][driver][name] = ret_multip[name]
                if name in names:
                    names.remove(name)

        # not destroying in parallel
        else:
            log.info('Destroying in non-parallel mode.')
            for alias, driver, name in vms_to_destroy:
                fun = '{0}.destroy'.format(driver)
                with salt.utils.context.func_globals_inject(
                    self.clouds[fun],
                    __active_provider_name__=':'.join([alias, driver])
                ):
                    ret = self.clouds[fun](name)
                if alias not in processed:
                    processed[alias] = {}
                if driver not in processed[alias]:
                    processed[alias][driver] = {}
                processed[alias][driver][name] = ret
                if name in names:
                    names.remove(name)

        # now the processed data structure contains the output from either
        # the parallel or non-parallel destroy and we should finish up
        # with removing minion keys if necessary
        for alias, driver, name in vms_to_destroy:
            ret = processed[alias][driver][name]
            if not ret:
                continue

            vm_ = {
                'name': name,
                'profile': None,
                'provider': ':'.join([alias, driver]),
                'driver': driver
            }
            minion_dict = salt.config.get_cloud_config_value(
                'minion', vm_, self.opts, default={}
            )
            key_file = os.path.join(
                self.opts['pki_dir'], 'minions', minion_dict.get('id', name)
            )
            globbed_key_file = glob.glob('{0}.*'.format(key_file))

            if not os.path.isfile(key_file) and not globbed_key_file:
                # There's no such key file!? It might have been renamed
                if isinstance(ret, dict) and 'newname' in ret:
                    salt.utils.cloud.remove_key(
                        self.opts['pki_dir'], ret['newname']
                    )
                continue

            if os.path.isfile(key_file) and not globbed_key_file:
                # Single key entry. Remove it!
                salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file))
                continue

            # Since we have globbed matches, there are probably some keys for which their minion
            # configuration has append_domain set.
            if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1:
                # Single entry, let's remove it!
                salt.utils.cloud.remove_key(
                    self.opts['pki_dir'],
                    os.path.basename(globbed_key_file[0])
                )
                continue

            # Since we can't get the profile or map entry used to create
            # the VM, we can't also get the append_domain setting.
            # And if we reached this point, we have several minion keys
            # who's name starts with the machine name we're deleting.
            # We need to ask one by one!?
            print(
                'There are several minion keys who\'s name starts '
                'with \'{0}\'. We need to ask you which one should be '
                'deleted:'.format(
                    name
                )
            )
            while True:
                for idx, filename in enumerate(globbed_key_file):
                    print(' {0}: {1}'.format(
                        idx, os.path.basename(filename)
                    ))
                selection = input(
                    'Which minion key should be deleted(number)? '
                )
                try:
                    selection = int(selection)
                except ValueError:
                    print(
                        '\'{0}\' is not a valid selection.'.format(selection)
                    )

                try:
                    filename = os.path.basename(
                        globbed_key_file.pop(selection)
                    )
                except Exception:
                    continue

                delete = input(
                    'Delete \'{0}\'? [Y/n]? '.format(filename)
                )
                if delete == '' or delete.lower().startswith('y'):
                    salt.utils.cloud.remove_key(
                        self.opts['pki_dir'], filename
                    )
                    print('Deleted \'{0}\''.format(filename))
                    break

                print('Did not delete \'{0}\''.format(filename))
                break

        if names and not processed:
            # These machines were asked to be destroyed but could not be found
            raise SaltCloudSystemExit(
                'The following VM\'s were not found: {0}'.format(
                    ', '.join(names)
                )
            )

        elif names and processed:
            processed['Not Found'] = names

        elif not processed:
            raise SaltCloudSystemExit('No machines were destroyed!')

        return processed
1238435
def _sysv_delete(name):
    '''
    
    '''
    if not _service_is_chkconfig(name):
        return False
    cmd = '/sbin/chkconfig --del {0}'.format(name)
    return not __salt__['cmd.retcode'](cmd)
218162
def main():
    

    parser = argparse.ArgumentParser(description='%(prog)s add/remove vmnet interfaces')
    parser.add_argument('-r', "--range", nargs='+', action=parse_vmnet_range(1, 255),
                        type=int, help="vmnet range to add (default is {} {})".format(DEFAULT_RANGE[0], DEFAULT_RANGE[1]))
    parser.add_argument("-C", "--clean", action="store_true", help="remove all vmnets excepting vmnet1 and vmnet8")
    parser.add_argument("-l", "--list", action="store_true", help="list all existing vmnets (UNIX only)")

    try:
        args = parser.parse_args()
    except argparse.ArgumentTypeError as e:
        raise SystemExit(e)

    vmnet_range = args.range if args.range is not None else DEFAULT_RANGE
    if sys.platform.startswith("win"):
        try:
            vmnet_windows(args, vmnet_range[0], vmnet_range[1])
        except SystemExit:
            os.system("pause")
            raise
    else:
        vmnet_unix(args, vmnet_range[0], vmnet_range[1])