Destroy a node. Will check termination protection and warn if enabled.

    CLI Example:

    .. code-block:: bash

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

    node_metadata = _get_node(name)
    instance_id = node_metadata['instanceId']
    sir_id = node_metadata.get('spotInstanceRequestId')
    protected = show_term_protect(
        name=name,
        instance_id=instance_id,
        call='action',
        quiet=True
    )

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

    if protected == 'true':
        raise SaltCloudSystemExit(
            'This instance has been protected from being destroyed. '
            'Use the following command to disable protection:\n\n'
            'salt-cloud -a disable_term_protect {0}'.format(
                name
            )
        )

    ret = {}

    # Default behavior is to rename EC2 VMs when destroyed
    # via salt-cloud, unless explicitly set to False.
    rename_on_destroy = config.get_cloud_config_value('rename_on_destroy',
                                                      get_configured_provider(),
                                                      __opts__,
                                                      search_global=False)
    if rename_on_destroy is not False:
        newname = '{0}-DEL{1}'.format(name, uuid.uuid4().hex)
        rename(name, kwargs={'newname': newname}, call='action')
        log.info(
            'Machine will be identified as %s until it has been '
            'cleaned up.', newname
        )
        ret['newname'] = newname

    params = {'Action': 'TerminateInstances',
              'InstanceId.1': instance_id}

    location = get_location()
    provider = get_provider()
    result = aws.query(params,
                       location=location,
                       provider=provider,
                       opts=__opts__,
                       sigver='4')

    log.info(result)
    ret.update(result[0])

    # If this instance is part of a spot instance request, we
    # need to cancel it as well
    if sir_id is not None:
        params = {'Action': 'CancelSpotInstanceRequests',
                  'SpotInstanceRequestId.1': sir_id}
        result = aws.query(params,
                           location=location,
                           provider=provider,
                           opts=__opts__,
                           sigver='4')
        ret['spotInstance'] = result[0]

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

    __utils__['cloud.cachedir_index_del'](name)

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

    return ret
278973
def destroy(self):
        '''
        
        '''
        # We borrowed the local clients poller so give it back before
        # it's destroyed. Reset the local poller reference.
        super(Syndic, self).destroy()
        if hasattr(self, 'local'):
            del self.local

        if hasattr(self, 'forward_events'):
            self.forward_events.stop()
12356
def destroy(name, conn=None, 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']
    )

    if not conn:
        conn = get_conn()   # pylint: disable=E0602

    node = get_node(conn, name)
    profiles = get_configured_provider()['profiles']  # pylint: disable=E0602
    if node is None:
        log.error('Unable to find the VM %s', name)
    profile = None
    if 'metadata' in node.extra and 'profile' in node.extra['metadata']:
        profile = node.extra['metadata']['profile']

    flush_mine_on_destroy = False
    if profile and profile in profiles and 'flush_mine_on_destroy' in profiles[profile]:
        flush_mine_on_destroy = profiles[profile]['flush_mine_on_destroy']

    if flush_mine_on_destroy:
        log.info('Clearing Salt Mine: %s', name)

        mopts_ = salt.config.DEFAULT_MINION_OPTS
        conf_path = '/'.join(__opts__['conf_file'].split('/')[:-1])
        mopts_.update(
            salt.config.minion_config(os.path.join(conf_path, 'minion'))
        )
        client = salt.client.get_local_client(mopts_)
        minions = client.cmd(name, 'mine.flush')

    log.info('Clearing Salt Mine: %s, %s', name, flush_mine_on_destroy)
    log.info('Destroying VM: %s', name)
    ret = conn.destroy_node(node)
    if ret:
        log.info('Destroyed VM: %s', name)
        # Fire destroy action
        __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__['delete_sshkeys'] is True:
            public_ips = getattr(node, __opts__.get('ssh_interface', 'public_ips'))
            if public_ips:
                salt.utils.cloud.remove_sshkey(public_ips[0])

            private_ips = getattr(node, __opts__.get('ssh_interface', 'private_ips'))
            if private_ips:
                salt.utils.cloud.remove_sshkey(private_ips[0])

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

        return True

    log.error('Failed to Destroy VM: %s', name)
    return False
294379
def terminate(self, nodes=None):
        
        if not self.is_connected():
            return None

        nodes = nodes or self.nodes
        failed_kill = []

        result = self.gce.ex_destroy_multiple_nodes(nodes, poll_interval=1, ignore_errors=False)

        # Verify whether all instances have been terminated.
        for i, success in enumerate(result):
            if success:
                logging.info('Successfully destroyed: %s', nodes[i].name)
            else:
                logging.error('Failed to destroy: %s', nodes[i].name)
                failed_kill.append(nodes[i])

        return failed_kill
1035705
def terminate_with_threads(self, nodes=None):
        
        if not self.is_connected():
            return None

        nodes = nodes or self.nodes
        failed_kill = []

        def worker(gce, node):
            self.logger.info("Terminating node: %s", node.name)
            terminated = gce.destroy_node(node)
            if not terminated:
                failed_kill.append(node)

        threads = []
        for node in nodes:
            thread = threading.Thread(target=worker, args=(self.gce, node))
            threads.append(thread)
            thread.start()

        self.logger.info("Waiting for nodes to shut down ...")
        for thread in threads:
            thread.join()

        return failed_kill
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')
1222727
def destroy(self):
        
        logger.info("destroying snap7 client")
        if self.library:
            return self.library.Cli_Destroy(byref(self.pointer))
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
167922
@Override
    public void destroy()
    {
        // if(logger.isDebugEnabled())
        logger.info("on close destroying connection pool");

        if (getConnectionPoolOrConnection() != null && getConnectionPoolOrConnection() instanceof JedisPool)
        {
            ((JedisPool) getConnectionPoolOrConnection()).destroy();
        }
        else if (getConnectionPoolOrConnection() != null && getConnectionPoolOrConnection() instanceof Jedis)
        {
            ((Jedis) getConnectionPoolOrConnection()).disconnect();
        }

    }
905667
def destroy(name, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudException(
            '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_ = get_configured_provider()
    manager = packet.Manager(auth_token=vm_['token'])

    nodes = list_nodes_min()

    node = nodes[name]

    for project in manager.list_projects():

        for volume in manager.list_volumes(project.id):
            if volume.attached_to == node['id']:
                volume.detach()
                volume.delete()
                break

    manager.call_api("devices/{id}".format(id=node['id']), type='DELETE')

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

    return {}
846267
def close(self):
        
        yield from self._telnet.close()
        self._telnet_server.close()
        
        for nio in self._nios.values():
            if nio:
                yield from nio.close()
        self.manager.port_manager.release_tcp_port(self._console, self._project)
        if self._hypervisor:
            try:
                yield from self._hypervisor.send('ethsw delete "{}"'.format(self._name))
                log.info('Ethernet switch "{name}" [{id}] has been deleted'.format(name=self._name, id=self._id))
            except DynamipsError:
                log.debug("Could not properly delete Ethernet switch {}".format(self._name))
        if self._hypervisor and self in self._hypervisor.devices:
            self._hypervisor.devices.remove(self)
        if self._hypervisor and not self._hypervisor.devices:
            yield from self.hypervisor.stop()
            self._hypervisor = None
        return True
11914
def stop(name, call=None):
    '''
    
    '''
    conn = get_conn()
    node = get_node(conn, name)  # pylint: disable=not-callable
    log.debug('Node of Cloud VM: %s', node)

    status = conn.ex_shutdown_graceful(node)
    log.debug('Status of Cloud VM: %s', status)

    return status
1058050
def destroy(self):
        

        subnets = (
            str(net.gw()) for net in self.virt_env.get_nets().itervalues()
        )

        self._subnet_store.release(subnets)
        self.cleanup()
        shutil.rmtree(self.paths.prefix_path())
765681
def delete(node)
      unless @nodes.key?(node.key)
        raise NoSuchNodeError.new(node.key)
      end

      (node.edges(:out) + node.edges(:in)).each do |edge|
        edge.from.disconnect_via(edge)
        edge.to.disconnect_via(edge)
      end

      @nodes.delete(node.key)
    end
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
1277549
def destroy(name):
    '''
    
    '''
    node = show_instance(name, call='action')
    params = {'SUBID': node['SUBID']}
    result = _query('server/destroy', method='POST', decode=False, data=_urlencode(params))

    # The return of a destroy call is empty in the case of a success.
    # Errors are only indicated via HTTP status code. Status code 200
    # effetively therefore means "success".
    if result.get('body') == '' and result.get('text') == '':
        return True
    return result
384147
def destroyCluster(self):
        
        assert self._ctx
        def expectedShutdownErrors(e):
            return e.status == 400 and 'dependent object' in e.body

        instances = self._getNodesInCluster(nodeType=None, both=True)
        spotIDs = self._getSpotRequestIDs()
        if spotIDs:
            self._ctx.ec2.cancel_spot_instance_requests(request_ids=spotIDs)
        instancesToTerminate = awsFilterImpairedNodes(instances, self._ctx.ec2)
        vpcId = None
        if instancesToTerminate:
            vpcId = instancesToTerminate[0].vpc_id
            self._deleteIAMProfiles(instances=instancesToTerminate)
            self._terminateInstances(instances=instancesToTerminate)
        if len(instances) == len(instancesToTerminate):
            logger.debug('Deleting security group...')
            removed = False
            for attempt in retry(timeout=300, predicate=expectedShutdownErrors):
                with attempt:
                    for sg in self._ctx.ec2.get_all_security_groups():
                        if sg.name == self.clusterName and vpcId and sg.vpc_id == vpcId:
                            try:
                                self._ctx.ec2.delete_security_group(group_id=sg.id)
                                removed = True
                            except BotoServerError as e:
                                if e.error_code == 'InvalidGroup.NotFound':
                                    pass
                                else:
                                    raise
            if removed:
                logger.debug('... Succesfully deleted security group')
        else:
            assert len(instances) > len(instancesToTerminate)
            # the security group can't be deleted until all nodes are terminated
            logger.warning('The TOIL_AWS_NODE_DEBUG environment variable is set and some nodes '
                           'have failed health checks. As a result, the security group & IAM '
                           'roles will not be deleted.')