Remove an existing node/member from an existing load-balancer configuration.

    CLI Example:

    .. code-block:: bash

        salt-cloud -f detach_lb gce name=lb member=myinstance
331451
def detach_lb(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The detach_lb function must be called with -f or --function.'
        )

    if not kwargs or 'name' not in kwargs:
        log.error(
            'A load-balancer name must be specified.'
        )
        return False
    if 'member' not in kwargs:
        log.error(
            'A node name name must be specified.'
        )
        return False

    conn = get_conn()
    lb_conn = get_lb_conn(conn)
    lb = lb_conn.get_balancer(kwargs['name'])

    member_list = lb_conn.balancer_list_members(lb)
    remove_member = None
    for member in member_list:
        if member.id == kwargs['member']:
            remove_member = member
            break

    if not remove_member:
        log.error(
            'The specified member %s was not a member of LB %s.',
            kwargs['member'], kwargs['name']
        )
        return False

    __utils__['cloud.fire_event'](
        'event',
        'detach load_balancer',
        'salt/cloud/loadbalancer/detaching',
        args=kwargs,
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    result = lb_conn.balancer_detach_member(lb, remove_member)

    __utils__['cloud.fire_event'](
        'event',
        'detached load_balancer',
        'salt/cloud/loadbalancer/detached',
        args=kwargs,
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return result
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
105072
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']
    )

    vmobj = _get_vm_by_name(name)
    if vmobj is not None:
        # stop the vm
        if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped':
            stop(name, vmobj['vmid'], 'action')

        # wait until stopped
        if not wait_for_state(vmobj['vmid'], 'stopped'):
            return {'Error': 'Unable to stop {0}, command timed out'.format(name)}

        # required to wait a bit here, otherwise the VM is sometimes
        # still locked and destroy fails.
        time.sleep(3)

        query('delete', 'nodes/{0}/{1}'.format(
            vmobj['node'], vmobj['id']
        ))
        __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 {'Destroyed': '{0} was destroyed.'.format(name)}
1164355
def remove(self, cls, originalMemberNameList, classNamingConvention):
        
        self._memberDelegate.remove(cls = cls,
                                    originalMemberNameList = originalMemberNameList,
                                    memberName = self._memberName,
                                    classNamingConvention = classNamingConvention)
1302899
def purge_existing_ovb(nova_api, neutron):
    
    LOG.info('Cleaning up OVB environment from the tenant.')
    for server in nova_api.servers.list():
        if server.name in ('bmc', 'undercloud'):
            server.delete()
        if server.name.startswith('baremetal_'):
            server.delete()
    for router in neutron.list_routers().get('routers'):
        if router['name'] not in ('router', 'bmc_router'):
            continue
        for subnet in neutron.list_subnets().get('subnets'):
            if not (subnet['name'].startswith('bmc_eth') or subnet['name'] == 'rdo-m-subnet'):
                continue
            try:
                neutron.remove_interface_router(router['id'], {'subnet_id': subnet['id']})
            except neutronclient.common.exceptions.NotFound:
                pass
    try:
        bmc_router = neutron.list_routers(name='bmc_router').get('routers')[0]
        for port in neutron.list_ports(device_id=bmc_router['id'])['ports']:
            if port.get('device_owner') == 'network:router_gateway':
                continue
            info = {'id': router['id'],
                    'port_id': port['id'],
                    'tenant_id': bmc_router.get('tenant_id'),
                    }
            neutron.remove_interface_router(bmc_router['id'], info)
        neutron.delete_router(bmc_router['id'])
    except IndexError:  # already doesnt exist
        pass

    for _ in range(0, 5):
        try:
            for port in neutron.list_ports()['ports']:
                if port['name'].endswith('_provision'):
                    neutron.delete_port(port['id'])
            for net in neutron.list_networks().get('networks'):
                if not net['name'].startswith('provision_'):
                    continue
                for port in neutron.list_ports(network_id=net['id'])['ports']:
                    if port.get('device_owner') == 'network:router_interface':
                        continue
                    try:
                        neutron.delete_port(port['id'])
                    except neutronclient.common.exceptions.PortNotFoundClient:
                            pass
                    for subnet in neutron.list_subnets(network_id=net['id'])['subnets']:
                        neutron.delete_subnet(subnet['id'])
                neutron.delete_network(net['id'])
        except neutronclient.common.exceptions.Conflict:
            LOG.debug('waiting for all the ports to be freed...')
            time.sleep(5)
        else:
            return
33150
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
    '''
    
    '''
    try:
        pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
    except MinionError as exc:
        raise CommandExecutionError(exc)

    old = list_pkgs()
    targets = [x for x in pkg_params if x in old]
    if not targets:
        return {}

    remove_arg = '-Rsc' if action == 'purge' else '-R'

    cmd = []
    if salt.utils.systemd.has_scope(__context__) \
            and __salt__['config.get']('systemd.scope', True):
        cmd.extend(['systemd-run', '--scope'])
    cmd.extend(['pacman', remove_arg, '--noprogressbar', '--noconfirm'])
    cmd.extend(targets)

    if 'root' in kwargs:
        cmd.extend(('-r', kwargs['root']))

    out = __salt__['cmd.run_all'](
        cmd,
        output_loglevel='trace',
        python_shell=False
    )

    if out['retcode'] != 0 and out['stderr']:
        errors = [out['stderr']]
    else:
        errors = []

    __context__.pop('pkg.list_pkgs', None)
    new = list_pkgs()
    ret = salt.utils.data.compare_dicts(old, new)

    if errors:
        raise CommandExecutionError(
            'Problem encountered removing package(s)',
            info={'errors': errors, 'changes': ret}
        )

    return ret
824101
def remove_node(self, node):
        
        try:
            self._nodes.remove(node)
            del self._weights[node]
        except (KeyError, ValueError):
            pass
        self._hashring = dict()
        self._sorted_keys = []

        self._build_circle()
90471
def detach_subnets(self, subnets):
        
        if isinstance(subnets, str) or isinstance(subnets, unicode):
            subnets = [subnets]
        new_subnets = self.connection.detach_lb_to_subnets(self.name, subnets)
        self.subnets = new_subnets
604622
def create_lb(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The create_lb function must be called with -f or --function.'
        )

    if not kwargs or 'name' not in kwargs:
        log.error(
            'A name must be specified when creating a health check.'
        )
        return False
    if 'ports' not in kwargs:
        log.error(
            'A port or port-range must be specified for the load-balancer.'
        )
        return False
    if 'region' not in kwargs:
        log.error(
            'A region must be specified for the load-balancer.'
        )
        return False
    if 'members' not in kwargs:
        log.error(
            'A comma-separated list of members must be specified.'
        )
        return False

    name = kwargs['name']
    ports = kwargs['ports']
    ex_region = kwargs['region']
    members = kwargs.get('members').split(',')

    protocol = kwargs.get('protocol', 'tcp')
    algorithm = kwargs.get('algorithm', None)
    ex_healthchecks = kwargs.get('healthchecks', None)

    # pylint: disable=W0511

    conn = get_conn()
    lb_conn = get_lb_conn(conn)

    ex_address = kwargs.get('address', None)
    if ex_address is not None:
        ex_address = __create_orget_address(conn, ex_address, ex_region)

    if ex_healthchecks:
        ex_healthchecks = ex_healthchecks.split(',')

    __utils__['cloud.fire_event'](
        'event',
        'create load_balancer',
        'salt/cloud/loadbalancer/creating',
        args=kwargs,
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    lb = lb_conn.create_balancer(
        name, ports, protocol, algorithm, members,
        ex_region=ex_region, ex_healthchecks=ex_healthchecks,
        ex_address=ex_address
    )

    __utils__['cloud.fire_event'](
        'event',
        'created load_balancer',
        'salt/cloud/loadbalancer/created',
        args=kwargs,
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return _expand_balancer(lb)
76357
def destroy(name=None, call=None):
    '''
    

    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )
    ret = {}
    __utils__['cloud.fire_event'](
        'event',
        'destroying instance',
        'salt/cloud/{0}/destroying'.format(name),
        args={'name': name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    session = _get_session()
    vm = _get_vm(name)
    if vm:
        # get vm
        record = session.xenapi.VM.get_record(vm)
        log.debug('power_state: %s', record['power_state'])
        # shut down
        if record['power_state'] != 'Halted':
            task = session.xenapi.Async.VM.hard_shutdown(vm)
            _run_async_task(task, session)

        # destroy disk (vdi) by reading vdb on vm
        ret['vbd'] = destroy_vm_vdis(name, session)
        # destroy vm
        task = session.xenapi.Async.VM.destroy(vm)
        _run_async_task(task, session)
        ret['destroyed'] = True
        __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__
            )
        __utils__['cloud.cachedir_index_del'](name)
        return ret
864607
def member_del(self, member_id, reconfig=True):
        
        server_id = self._servers.host_to_server_id(
            self.member_id_to_host(member_id))
        if reconfig and member_id in [member['_id'] for member in self.members()]:
            config = self.config
            config['members'].pop(member_id)
            self.repl_update(config)
        self._servers.remove(server_id)
        return True
442932
def _uninstall(
    action='remove',
    name=None,
    version=None,
    pkgs=None,
    normalize=True,
    ignore_epoch=False,
    **kwargs):
    '''
    
    '''
    if action not in ('remove', 'purge'):
        return {'name': name,
                'changes': {},
                'result': False,
                'comment': 'Invalid action \'{0}\'. '
                           'This is probably a bug.'.format(action)}

    try:
        pkg_params = __salt__['pkg_resource.parse_targets'](
            name,
            pkgs,
            normalize=normalize)[0]
    except MinionError as exc:
        return {'name': name,
                'changes': {},
                'result': False,
                'comment': 'An error was encountered while parsing targets: '
                           '{0}'.format(exc)}
    targets = _find_remove_targets(name, version, pkgs, normalize,
                                   ignore_epoch=ignore_epoch, **kwargs)
    if isinstance(targets, dict) and 'result' in targets:
        return targets
    elif not isinstance(targets, list):
        return {'name': name,
                'changes': {},
                'result': False,
                'comment': 'An error was encountered while checking targets: '
                           '{0}'.format(targets)}
    if action == 'purge':
        old_removed = __salt__['pkg.list_pkgs'](versions_as_list=True,
                                                removed=True,
                                                **kwargs)
        targets.extend([x for x in pkg_params if x in old_removed])
    targets.sort()

    if not targets:
        return {'name': name,
                'changes': {},
                'result': True,
                'comment': 'None of the targeted packages are installed'
                           '{0}'.format(' or partially installed'
                                        if action == 'purge' else '')}

    if __opts__['test']:
        return {'name': name,
                'changes': {},
                'result': None,
                'comment': 'The following packages will be {0}d: '
                           '{1}.'.format(action, ', '.join(targets))}

    changes = __salt__['pkg.{0}'.format(action)](name, pkgs=pkgs, version=version, **kwargs)
    new = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs)
    failed = []
    for x in pkg_params:
        if __grains__['os_family'] in ['Suse', 'RedHat']:
            # Check if the package version set to be removed is actually removed:
            if x in new and not pkg_params[x]:
                failed.append(x)
            elif x in new and pkg_params[x] in new[x]:
                failed.append(x + "-" + pkg_params[x])
        elif x in new:
            failed.append(x)

    if action == 'purge':
        new_removed = __salt__['pkg.list_pkgs'](versions_as_list=True,
                                                removed=True,
                                                **kwargs)
        failed.extend([x for x in pkg_params if x in new_removed])
    failed.sort()

    if failed:
        return {'name': name,
                'changes': changes,
                'result': False,
                'comment': 'The following packages failed to {0}: '
                           '{1}.'.format(action, ', '.join(failed))}

    comments = []
    not_installed = sorted([x for x in pkg_params if x not in targets])
    if not_installed:
        comments.append('The following packages were not installed: '
                        '{0}'.format(', '.join(not_installed)))
        comments.append('The following packages were {0}d: '
                        '{1}.'.format(action, ', '.join(targets)))
    else:
        comments.append('All targeted packages were {0}d.'.format(action))

    return {'name': name,
            'changes': changes,
            'result': True,
            'comment': ' '.join(comments)}
839484
def detached(name):
    '''
    

    '''
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    zones = __salt__['zoneadm.list'](installed=True, configured=True)
    if name in zones:
        if zones[name]['state'] != 'configured':
            if __opts__['test']:
                res_detach = {'status': True}
            else:
                res_detach = __salt__['zoneadm.detach'](name)
            ret['result'] = res_detach['status']
            if ret['result']:
                ret['changes'][name] = 'detached'
                ret['comment'] = 'The zone {0} was detached.'.format(name)
            else:
                ret['comment'] = []
                ret['comment'].append('Failed to detach zone {0}!'.format(name))
                if 'message' in res_detach:
                    ret['comment'].append(res_detach['message'])
                ret['comment'] = "\n".join(ret['comment'])
        else:
            ret['result'] = True
            ret['comment'] = 'zone {0} already detached.'.format(name)
    else:
        ## note: a non existing zone is not attached, we do not consider this a failure
        ret['result'] = True
        ret['comment'] = 'zone {0} is not configured!'.format(name)

    return ret
1236229
def destroy(instance_id, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    instance_data = show_instance(instance_id, call='action')
    name = instance_data['instance_name']

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

    params = {
        'action': 'TerminateInstances',
        'zone': _get_specified_zone(provider=get_configured_provider()),
        'instances.1': instance_id,
    }
    result = query(params)

    __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 result
391769
function (elbName, instanceId, cb) {
      // support removing array of instances at once
      var instance = mapInstances(instanceId),
        params   = { Instances: instance, LoadBalancerName: elbName };
      api.deregisterInstancesFromLoadBalancer(params, cb);
    }
584658
def detach(options = {})
      options = Aws::Util.deep_merge(options,
        auto_scaling_group_name: @group_name,
        load_balancer_names: [@name]
      )
      resp = @client.detach_load_balancers(options)
      resp.data
    end
108627
def on_cluster_remove(self, name):
        
        discovery_name = self.configurables[Cluster][name].discovery
        if discovery_name in self.configurables[Discovery]:
            self.configurables[Discovery][discovery_name].stop_watching(
                self.configurables[Cluster][name]
            )
            self.kill_thread(name)

        self.sync_balancer_files()