text
stringlengths
52
3.87M
def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response)
def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response)
def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response)
def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
def list_(return_yaml=True, include_pillar=True, include_opts=True, **kwargs): ''' List the beacons currently configured on the minion. Args: return_yaml (bool): Whether to return YAML formatted output, default ``True``. include_pillar (bool): Whether to include beacons that are configured in pillar, default is ``True``. include_opts (bool): Whether to include beacons that are configured in opts, default is ``True``. Returns: list: List of currently configured Beacons. CLI Example: .. code-block:: bash salt '*' beacons.list ''' beacons = None try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'include_pillar': include_pillar, 'include_opts': include_opts}, 'manage_beacons') if res: event_ret = eventer.get_event( tag='/salt/minion/minion_beacons_list_complete', wait=kwargs.get('timeout', 30)) log.debug('event_ret %s', event_ret) if event_ret and event_ret['complete']: beacons = event_ret['beacons'] except KeyError: # Effectively a no-op, since we can't really return without an event # system ret = {'comment': 'Event module not available. Beacon list failed.', 'result': False} return ret if beacons: if return_yaml: tmp = {'beacons': beacons} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return beacons else: return {'beacons': {}}
def add(name, beacon_data, **kwargs): ''' Add a beacon on the minion Args: name (str): Name of the beacon to configure beacon_data (dict): Dictionary or list containing configuration for beacon. Returns: dict: Boolean and status message on success or failure of add. CLI Example: .. code-block:: bash salt '*' beacons.add ps "[{'processes': {'salt-master': 'stopped', 'apache2': 'stopped'}}]" ''' ret = {'comment': 'Failed to add beacon {0}.'.format(name), 'result': False} if name in list_(return_yaml=False, **kwargs): ret['comment'] = 'Beacon {0} is already configured.'.format(name) return ret # Check to see if a beacon_module is specified, if so, verify it is # valid and available beacon type. if any('beacon_module' in key for key in beacon_data): res = next(value for value in beacon_data if 'beacon_module' in value) beacon_name = res['beacon_module'] else: beacon_name = name if beacon_name not in list_available(return_yaml=False, **kwargs): ret['comment'] = 'Beacon "{0}" is not available.'.format(beacon_name) return ret if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'] = 'Beacon: {0} would be added.'.format(name) else: try: # Attempt to load the beacon module so we have access to the # validate function eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'beacon_data': beacon_data, 'func': 'validate_beacon'}, 'manage_beacons') if res: event_ret = eventer.get_event( tag='/salt/minion/minion_beacon_validation_complete', wait=kwargs.get('timeout', 30)) valid = event_ret['valid'] vcomment = event_ret['vcomment'] if not valid: ret['result'] = False ret['comment'] = ('Beacon {0} configuration invalid, ' 'not adding.\n{1}'.format(name, vcomment)) return ret except KeyError: # Effectively a no-op, since we can't really return without an event # system ret['result'] = False ret['comment'] = 'Event module not available. Beacon add failed.' return ret try: res = __salt__['event.fire']({'name': name, 'beacon_data': beacon_data, 'func': 'add'}, 'manage_beacons') if res: event_ret = eventer.get_event( tag='/salt/minion/minion_beacon_add_complete', wait=kwargs.get('timeout', 30)) if event_ret and event_ret['complete']: beacons = event_ret['beacons'] if name in beacons and beacons[name] == beacon_data: ret['result'] = True ret['comment'] = 'Added beacon: {0}.'.format(name) elif event_ret: ret['result'] = False ret['comment'] = event_ret['comment'] else: ret['result'] = False ret['comment'] = 'Did not receive the manage event ' \ 'before the timeout of {0}s' \ ''.format(kwargs.get('timeout', 30)) return ret except KeyError: # Effectively a no-op, since we can't really return without an event # system ret['result'] = False ret['comment'] = 'Event module not available. Beacon add failed.' return ret
def modify(name, beacon_data, **kwargs): ''' Modify an existing beacon. Args: name (str): Name of the beacon to configure. beacon_data (dict): Dictionary or list containing updated configuration for beacon. Returns: dict: Boolean and status message on success or failure of modify. CLI Example: .. code-block:: bash salt '*' beacons.modify ps "[{'salt-master': 'stopped'}, {'apache2': 'stopped'}]" ''' ret = {'comment': '', 'result': True} current_beacons = list_(return_yaml=False, **kwargs) if name not in current_beacons: ret['comment'] = 'Beacon {0} is not configured.'.format(name) return ret if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'] = 'Beacon: {0} would be modified.'.format(name) else: try: # Attempt to load the beacon module so we have access to the # validate function eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'beacon_data': beacon_data, 'func': 'validate_beacon'}, 'manage_beacons') if res: event_ret = eventer.get_event( tag='/salt/minion/minion_beacon_validation_complete', wait=kwargs.get('timeout', 30)) valid = event_ret['valid'] vcomment = event_ret['vcomment'] if not valid: ret['result'] = False ret['comment'] = ('Beacon {0} configuration invalid, ' 'not modifying.\n{1}'.format(name, vcomment)) return ret except KeyError: # Effectively a no-op, since we can't really return without an event # system ret['result'] = False ret['comment'] = 'Event module not available. Beacon modify failed.' return ret if not valid: ret['result'] = False ret['comment'] = ('Beacon {0} configuration invalid, ' 'not modifying.\n{1}'.format(name, vcomment)) return ret _current = current_beacons[name] _new = beacon_data if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = [] for _item in _current: _current_lines.extend(['{0}:{1}\n'.format(key, value) for (key, value) in six.iteritems(_item)]) _new_lines = [] for _item in _new: _new_lines.extend(['{0}:{1}\n'.format(key, value) for (key, value) in six.iteritems(_item)]) _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes'] = {} ret['changes']['diff'] = ''.join(_diff) try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'beacon_data': beacon_data, 'func': 'modify'}, 'manage_beacons') if res: event_ret = eventer.get_event( tag='/salt/minion/minion_beacon_modify_complete', wait=kwargs.get('timeout', 30)) if event_ret and event_ret['complete']: beacons = event_ret['beacons'] if name in beacons and beacons[name] == beacon_data: ret['result'] = True ret['comment'] = 'Modified beacon: {0}.'.format(name) elif event_ret: ret['result'] = False ret['comment'] = event_ret['comment'] else: ret['result'] = False ret['comment'] = 'Did not receive the manage event ' \ 'before the timeout of {0}s' \ ''.format(kwargs.get('timeout', 30)) return ret except KeyError: # Effectively a no-op, since we can't really return without an event # system ret['result'] = False ret['comment'] = 'Event module not available. Beacon modify failed.' return ret
def save(**kwargs): ''' Save all configured beacons to the minion config. Returns: dict: Boolean and status message on success or failure of save. CLI Example: .. code-block:: bash salt '*' beacons.save ''' ret = {'comment': [], 'result': True} beacons = list_(return_yaml=False, include_pillar=False, **kwargs) # move this file into an configurable opt sfn = os.path.join(os.path.dirname(__opts__['conf_file']), os.path.dirname(__opts__['default_include']), 'beacons.conf') if beacons: tmp = {'beacons': beacons} yaml_out = salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: yaml_out = '' try: with salt.utils.files.fopen(sfn, 'w+') as fp_: fp_.write(yaml_out) ret['comment'] = 'Beacons saved to {0}.'.format(sfn) except (IOError, OSError): ret['comment'] = 'Unable to write to beacons file at {0}. Check ' \ 'permissions.'.format(sfn) ret['result'] = False return ret
def enable_beacon(name, **kwargs): ''' Enable a beacon on the minion. Args: name (str): Name of the beacon to enable. Returns: dict: Boolean and status message on success or failure of enable. CLI Example: .. code-block:: bash salt '*' beacons.enable_beacon ps ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Beacon name is required.' ret['result'] = False return ret if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Beacon {0} would be enabled.'.format(name) else: _beacons = list_(return_yaml=False, **kwargs) if name not in _beacons: ret['comment'] = 'Beacon {0} is not currently configured.' \ ''.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable_beacon', 'name': name}, 'manage_beacons') if res: event_ret = eventer.get_event( tag='/salt/minion/minion_beacon_enabled_complete', wait=kwargs.get('timeout', 30)) if event_ret and event_ret['complete']: beacons = event_ret['beacons'] beacon_config_dict = _get_beacon_config_dict(beacons[name]) if 'enabled' in beacon_config_dict and beacon_config_dict['enabled']: ret['result'] = True ret['comment'] = 'Enabled beacon {0} on minion.' \ ''.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable beacon {0} on ' \ 'minion.'.format(name) elif event_ret: ret['result'] = False ret['comment'] = event_ret['comment'] else: ret['result'] = False ret['comment'] = 'Did not receive the manage event ' \ 'before the timeout of {0}s' \ ''.format(kwargs.get('timeout', 30)) return ret except KeyError: # Effectively a no-op, since we can't really return without an event # system ret['result'] = False ret['comment'] = 'Event module not available. Beacon enable job ' \ 'failed.' return ret
def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the REST interface ''' return query(key, value, service, profile)
def query(key, value=None, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the REST interface ''' comps = key.split('?') key = comps[0] key_vars = {} for pair in comps[1].split('&'): pair_key, pair_val = pair.split('=') key_vars[pair_key] = pair_val renderer = __opts__.get('renderer', 'jinja|yaml') rend = salt.loader.render(__opts__, {}) blacklist = __opts__.get('renderer_blacklist') whitelist = __opts__.get('renderer_whitelist') url = compile_template( ':string:', rend, renderer, blacklist, whitelist, input_data=profile[key]['url'], **key_vars ) extras = {} for item in profile[key]: if item not in ('backend', 'url'): extras[item] = profile[key][item] result = http.query( url, decode=True, **extras ) return result['dict']
def send(name, data=None, preload=None, with_env=False, with_grains=False, with_pillar=False, show_changed=True, **kwargs): ''' Send an event to the Salt Master .. versionadded:: 2014.7.0 Accepts the same arguments as the :py:func:`event.send <salt.modules.event.send>` execution module of the same name, with the additional argument: :param show_changed: If ``True``, state will show as changed with the data argument as the change value. If ``False``, shows as unchanged. Example: .. code-block:: yaml # ...snip bunch of states above mycompany/mystaterun/status/update: event.send: - data: status: "Half-way through the state run!" # ...snip bunch of states below ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if show_changed: ret['changes'] = {'tag': name, 'data': data} else: ret['changes'] = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'Event would have been fired' return ret ret['result'] = __salt__['event.send'](name, data=data, preload=preload, with_env=with_env, with_grains=with_grains, with_pillar=with_pillar, **kwargs) ret['comment'] = 'Event fired' return ret
def _rule_compare(rule1, rule2): ''' Compare the common keys between security group rules against eachother ''' commonkeys = set(rule1.keys()).intersection(rule2.keys()) for key in commonkeys: if rule1[key] != rule2[key]: return False return True
def present(name, auth=None, **kwargs): ''' Ensure a security group rule exists defaults: port_range_min=None, port_range_max=None, protocol=None, remote_ip_prefix=None, remote_group_id=None, direction='ingress', ethertype='IPv4', project_id=None name Name of the security group to associate with this rule project_name Name of the project associated with the security group protocol The protocol that is matched by the security group rule. Valid values are None, tcp, udp, and icmp. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} kwargs = __utils__['args.clean_kwargs'](**kwargs) __salt__['neutronng.setup_clouds'](auth) if 'project_name' in kwargs: kwargs['project_id'] = kwargs['project_name'] del kwargs['project_name'] project = __salt__['keystoneng.project_get']( name=kwargs['project_id']) if project is None: ret['result'] = False ret['comment'] = "Project does not exist" return ret secgroup = __salt__['neutronng.security_group_get']( name=name, filters={'tenant_id': project.id} ) if secgroup is None: ret['result'] = False ret['changes'] = {}, ret['comment'] = 'Security Group does not exist {}'.format(name) return ret # we have to search through all secgroup rules for a possible match rule_exists = None for rule in secgroup['security_group_rules']: if _rule_compare(rule, kwargs) is True: rule_exists = True if rule_exists is None: if __opts__['test'] is True: ret['result'] = None ret['changes'] = kwargs ret['comment'] = 'Security Group rule will be created.' return ret # The variable differences are a little clumsy right now kwargs['secgroup_name_or_id'] = secgroup new_rule = __salt__['neutronng.security_group_rule_create'](**kwargs) ret['changes'] = new_rule ret['comment'] = 'Created security group rule' return ret return ret
def absent(name, auth=None, **kwargs): ''' Ensure a security group rule does not exist name name or id of the security group rule to delete rule_id uuid of the rule to delete project_id id of project to delete rule from ''' rule_id = kwargs['rule_id'] ret = {'name': rule_id, 'changes': {}, 'result': True, 'comment': ''} __salt__['neutronng.setup_clouds'](auth) secgroup = __salt__['neutronng.security_group_get']( name=name, filters={'tenant_id': kwargs['project_id']} ) # no need to delete a rule if the security group doesn't exist if secgroup is None: ret['comment'] = "security group does not exist" return ret # This should probably be done with compare on fields instead of # rule_id in the future rule_exists = None for rule in secgroup['security_group_rules']: if _rule_compare(rule, {"id": rule_id}) is True: rule_exists = True if rule_exists: if __opts__['test']: ret['result'] = None ret['changes'] = {'id': kwargs['rule_id']} ret['comment'] = 'Security group rule will be deleted.' return ret __salt__['neutronng.security_group_rule_delete'](rule_id=rule_id) ret['changes']['id'] = rule_id ret['comment'] = 'Deleted security group rule' return ret
def query(name, match=None, match_type='string', status=None, status_type='string', wait_for=None, **kwargs): ''' Perform an HTTP query and statefully return the result Passes through all the parameters described in the :py:func:`utils.http.query function <salt.utils.http.query>`: name The name of the query. match Specifies a pattern to look for in the return text. By default, this will perform a string comparison of looking for the value of match in the return text. match_type Specifies the type of pattern matching to use on match. Default is ``string``, but can also be set to ``pcre`` to use regular expression matching if a more complex pattern matching is required. .. note:: Despite the name of ``match_type`` for this argument, this setting actually uses Python's ``re.search()`` function rather than Python's ``re.match()`` function. status The status code for a URL for which to be checked. Can be used instead of or in addition to the ``match`` setting. status_type Specifies the type of pattern matching to use for status. Default is ``string``, but can also be set to ``pcre`` to use regular expression matching if a more complex pattern matching is required. .. versionadded:: Neon .. note:: Despite the name of ``match_type`` for this argument, this setting actually uses Python's ``re.search()`` function rather than Python's ``re.match()`` function. If both ``match`` and ``status`` options are set, both settings will be checked. However, note that if only one option is ``True`` and the other is ``False``, then ``False`` will be returned. If this case is reached, the comments in the return data will contain troubleshooting information. For more information about the ``http.query`` state, refer to the :ref:`HTTP Tutorial <tutorial-http>`. .. code-block:: yaml query_example: http.query: - name: 'http://example.com/' - status: 200 ''' # Monitoring state, but changes may be made over HTTP ret = {'name': name, 'result': None, 'comment': '', 'changes': {}, 'data': {}} # Data field for monitoring state if match is None and status is None: ret['result'] = False ret['comment'] += ( ' Either match text (match) or a status code (status) is required.' ) return ret if 'decode' not in kwargs: kwargs['decode'] = False kwargs['text'] = True kwargs['status'] = True if __opts__['test']: kwargs['test'] = True if wait_for: data = __salt__['http.wait_for_successful_query'](name, wait_for=wait_for, **kwargs) else: data = __salt__['http.query'](name, **kwargs) if match is not None: if match_type == 'string': if str(match) in data.get('text', ''): ret['result'] = True ret['comment'] += ' Match text "{0}" was found.'.format(match) else: ret['result'] = False ret['comment'] += ' Match text "{0}" was not found.'.format(match) elif match_type == 'pcre': if re.search(str(match), str(data.get('text', ''))): ret['result'] = True ret['comment'] += ' Match pattern "{0}" was found.'.format(match) else: ret['result'] = False ret['comment'] += ' Match pattern "{0}" was not found.'.format(match) if status is not None: if status_type == 'string': if str(data.get('status', '')) == str(status): ret['comment'] += ' Status {0} was found.'.format(status) if ret['result'] is None: ret['result'] = True else: ret['comment'] += ' Status {0} was not found.'.format(status) ret['result'] = False elif status_type == 'pcre': if re.search(str(status), str(data.get('status', ''))): ret['comment'] += ' Status pattern "{0}" was found.'.format(status) if ret['result'] is None: ret['result'] = True else: ret['comment'] += ' Status pattern "{0}" was not found.'.format(status) ret['result'] = False # cleanup spaces in comment ret['comment'] = ret['comment'].strip() if __opts__['test'] is True: ret['result'] = None ret['comment'] += ' (TEST MODE' if 'test_url' in kwargs: ret['comment'] += ', TEST URL WAS: {0}'.format(kwargs['test_url']) ret['comment'] += ')' ret['data'] = data return ret
def wait_for_successful_query(name, wait_for=300, **kwargs): ''' Like query but, repeat and wait until match/match_type or status is fulfilled. State returns result from last query state in case of success or if no successful query was made within wait_for timeout. name The name of the query. wait_for Total time to wait for requests that succeed. request_interval Optional interval to delay requests by N seconds to reduce the number of requests sent. .. note:: All other arguments are passed to the http.query state. ''' starttime = time.time() while True: caught_exception = None ret = None try: ret = query(name, **kwargs) if ret['result']: return ret except Exception as exc: caught_exception = exc if time.time() > starttime + wait_for: if not ret and caught_exception: # workaround pylint bug https://www.logilab.org/ticket/3207 raise caught_exception # pylint: disable=E0702 return ret else: # Space requests out by delaying for an interval if 'request_interval' in kwargs: log.debug('delaying query for %s seconds.', kwargs['request_interval']) time.sleep(kwargs['request_interval'])
def __parse_drac(output): ''' Parse Dell DRAC output ''' drac = {} section = '' for i in output.splitlines(): if i.strip().endswith(':') and '=' not in i: section = i[0:-1] drac[section] = {} if i.rstrip() and '=' in i: if section in drac: drac[section].update(dict( [[prop.strip() for prop in i.split('=')]] )) else: section = i.strip() if section not in drac and section: drac[section] = {} return drac
def __execute_cmd(command, host=None, admin_username=None, admin_password=None, module=None): ''' Execute rac commands ''' if module: # -a takes 'server' or 'switch' to represent all servers # or all switches in a chassis. Allow # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH' if module.startswith('ALL_'): modswitch = '-a '\ + module[module.index('_') + 1:len(module)].lower() else: modswitch = '-m {0}'.format(module) else: modswitch = '' if not host: # This is a local call cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command, modswitch)) else: cmd = __salt__['cmd.run_all']( 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host, admin_username, admin_password, command, modswitch), output_loglevel='quiet') if cmd['retcode'] != 0: log.warning('racadm returned an exit code of %s', cmd['retcode']) return False return True
def __execute_ret(command, host=None, admin_username=None, admin_password=None, module=None): ''' Execute rac commands ''' if module: if module == 'ALL': modswitch = '-a ' else: modswitch = '-m {0}'.format(module) else: modswitch = '' if not host: # This is a local call cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command, modswitch)) else: cmd = __salt__['cmd.run_all']( 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host, admin_username, admin_password, command, modswitch), output_loglevel='quiet') if cmd['retcode'] != 0: log.warning('racadm returned an exit code of %s', cmd['retcode']) else: fmtlines = [] for l in cmd['stdout'].splitlines(): if l.startswith('Security Alert'): continue if l.startswith('RAC1168:'): break if l.startswith('RAC1169:'): break if l.startswith('Continuing execution'): continue if not l.strip(): continue fmtlines.append(l) if '=' in l: continue cmd['stdout'] = '\n'.join(fmtlines) return cmd
def get_property(host=None, admin_username=None, admin_password=None, property=None): ''' .. versionadded:: Fluorine Return specific property host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. property: The property which should be get. CLI Example: .. code-block:: bash salt dell dracr.get_property property=System.ServerOS.HostName ''' if property is None: raise SaltException('No property specified!') ret = __execute_ret('get \'{0}\''.format(property), host=host, admin_username=admin_username, admin_password=admin_password) return ret
def set_property(host=None, admin_username=None, admin_password=None, property=None, value=None): ''' .. versionadded:: Fluorine Set specific property host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. property: The property which should be set. value: The value which should be set to property. CLI Example: .. code-block:: bash salt dell dracr.set_property property=System.ServerOS.HostName value=Pretty-server ''' if property is None: raise SaltException('No property specified!') elif value is None: raise SaltException('No value specified!') ret = __execute_ret('set \'{0}\' \'{1}\''.format(property, value), host=host, admin_username=admin_username, admin_password=admin_password) return ret
def ensure_property_set(host=None, admin_username=None, admin_password=None, property=None, value=None): ''' .. versionadded:: Fluorine Ensure that property is set to specific value host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. property: The property which should be set. value: The value which should be set to property. CLI Example: .. code-block:: bash salt dell dracr.ensure_property_set property=System.ServerOS.HostName value=Pretty-server ''' ret = get_property(host, admin_username, admin_password, property) if ret['stdout'] == value: return True ret = set_property(host, admin_username, admin_password, property, value) return ret
def system_info(host=None, admin_username=None, admin_password=None, module=None): ''' Return System information CLI Example: .. code-block:: bash salt dell dracr.system_info ''' cmd = __execute_ret('getsysinfo', host=host, admin_username=admin_username, admin_password=admin_password, module=module) if cmd['retcode'] != 0: log.warning('racadm returned an exit code of %s', cmd['retcode']) return cmd return __parse_drac(cmd['stdout'])
def network_info(host=None, admin_username=None, admin_password=None, module=None): ''' Return Network Configuration CLI Example: .. code-block:: bash salt dell dracr.network_info ''' inv = inventory(host=host, admin_username=admin_username, admin_password=admin_password) if inv is None: cmd = {} cmd['retcode'] = -1 cmd['stdout'] = 'Problem getting switch inventory' return cmd if module not in inv.get('switch') and module not in inv.get('server'): cmd = {} cmd['retcode'] = -1 cmd['stdout'] = 'No module {0} found.'.format(module) return cmd cmd = __execute_ret('getniccfg', host=host, admin_username=admin_username, admin_password=admin_password, module=module) if cmd['retcode'] != 0: log.warning('racadm returned an exit code of %s', cmd['retcode']) cmd['stdout'] = 'Network:\n' + 'Device = ' + module + '\n' + \ cmd['stdout'] return __parse_drac(cmd['stdout'])
def nameservers(ns, host=None, admin_username=None, admin_password=None, module=None): ''' Configure the nameservers on the DRAC CLI Example: .. code-block:: bash salt dell dracr.nameservers [NAMESERVERS] salt dell dracr.nameservers ns1.example.com ns2.example.com admin_username=root admin_password=calvin module=server-1 host=192.168.1.1 ''' if len(ns) > 2: log.warning('racadm only supports two nameservers') return False for i in range(1, len(ns) + 1): if not __execute_cmd('config -g cfgLanNetworking -o ' 'cfgDNSServer{0} {1}'.format(i, ns[i - 1]), host=host, admin_username=admin_username, admin_password=admin_password, module=module): return False return True
def syslog(server, enable=True, host=None, admin_username=None, admin_password=None, module=None): ''' Configure syslog remote logging, by default syslog will automatically be enabled if a server is specified. However, if you want to disable syslog you will need to specify a server followed by False CLI Example: .. code-block:: bash salt dell dracr.syslog [SYSLOG IP] [ENABLE/DISABLE] salt dell dracr.syslog 0.0.0.0 False ''' if enable and __execute_cmd('config -g cfgRemoteHosts -o ' 'cfgRhostsSyslogEnable 1', host=host, admin_username=admin_username, admin_password=admin_password, module=None): return __execute_cmd('config -g cfgRemoteHosts -o ' 'cfgRhostsSyslogServer1 {0}'.format(server), host=host, admin_username=admin_username, admin_password=admin_password, module=module) return __execute_cmd('config -g cfgRemoteHosts -o cfgRhostsSyslogEnable 0', host=host, admin_username=admin_username, admin_password=admin_password, module=module)
def email_alerts(action, host=None, admin_username=None, admin_password=None): ''' Enable/Disable email alerts CLI Example: .. code-block:: bash salt dell dracr.email_alerts True salt dell dracr.email_alerts False ''' if action: return __execute_cmd('config -g cfgEmailAlert -o ' 'cfgEmailAlertEnable -i 1 1', host=host, admin_username=admin_username, admin_password=admin_password) else: return __execute_cmd('config -g cfgEmailAlert -o ' 'cfgEmailAlertEnable -i 1 0')
def list_users(host=None, admin_username=None, admin_password=None, module=None): ''' List all DRAC users CLI Example: .. code-block:: bash salt dell dracr.list_users ''' users = {} _username = '' for idx in range(1, 17): cmd = __execute_ret('getconfig -g ' 'cfgUserAdmin -i {0}'.format(idx), host=host, admin_username=admin_username, admin_password=admin_password) if cmd['retcode'] != 0: log.warning('racadm returned an exit code of %s', cmd['retcode']) for user in cmd['stdout'].splitlines(): if not user.startswith('cfg'): continue (key, val) = user.split('=') if key.startswith('cfgUserAdminUserName'): _username = val.strip() if val: users[_username] = {'index': idx} else: break else: if _username: users[_username].update({key: val}) return users
def delete_user(username, uid=None, host=None, admin_username=None, admin_password=None): ''' Delete a user CLI Example: .. code-block:: bash salt dell dracr.delete_user [USERNAME] [UID - optional] salt dell dracr.delete_user diana 4 ''' if uid is None: user = list_users() uid = user[username]['index'] if uid: return __execute_cmd('config -g cfgUserAdmin -o ' 'cfgUserAdminUserName -i {0} ""'.format(uid), host=host, admin_username=admin_username, admin_password=admin_password) else: log.warning('User \'%s\' does not exist', username) return False
def change_password(username, password, uid=None, host=None, admin_username=None, admin_password=None, module=None): ''' Change user's password CLI Example: .. code-block:: bash salt dell dracr.change_password [USERNAME] [PASSWORD] uid=[OPTIONAL] host=<remote DRAC> admin_username=<DRAC user> admin_password=<DRAC PW> salt dell dracr.change_password diana secret Note that if only a username is specified then this module will look up details for all 16 possible DRAC users. This is time consuming, but might be necessary if one is not sure which user slot contains the one you want. Many late-model Dell chassis have 'root' as UID 1, so if you can depend on that then setting the password is much quicker. Raises an error if the supplied password is greater than 20 chars. ''' if len(password) > 20: raise CommandExecutionError('Supplied password should be 20 characters or less') if uid is None: user = list_users(host=host, admin_username=admin_username, admin_password=admin_password, module=module) uid = user[username]['index'] if uid: return __execute_cmd('config -g cfgUserAdmin -o ' 'cfgUserAdminPassword -i {0} {1}' .format(uid, password), host=host, admin_username=admin_username, admin_password=admin_password, module=module) else: log.warning('racadm: user \'%s\' does not exist', username) return False
def deploy_password(username, password, host=None, admin_username=None, admin_password=None, module=None): ''' Change the QuickDeploy password, used for switches as well CLI Example: .. code-block:: bash salt dell dracr.deploy_password [USERNAME] [PASSWORD] host=<remote DRAC> admin_username=<DRAC user> admin_password=<DRAC PW> salt dell dracr.change_password diana secret Note that if only a username is specified then this module will look up details for all 16 possible DRAC users. This is time consuming, but might be necessary if one is not sure which user slot contains the one you want. Many late-model Dell chassis have 'root' as UID 1, so if you can depend on that then setting the password is much quicker. ''' return __execute_cmd('deploy -u {0} -p {1}'.format( username, password), host=host, admin_username=admin_username, admin_password=admin_password, module=module )
def deploy_snmp(snmp, host=None, admin_username=None, admin_password=None, module=None): ''' Change the QuickDeploy SNMP community string, used for switches as well CLI Example: .. code-block:: bash salt dell dracr.deploy_snmp SNMP_STRING host=<remote DRAC or CMC> admin_username=<DRAC user> admin_password=<DRAC PW> salt dell dracr.deploy_password diana secret ''' return __execute_cmd('deploy -v SNMPv2 {0} ro'.format(snmp), host=host, admin_username=admin_username, admin_password=admin_password, module=module)
def set_snmp(community, host=None, admin_username=None, admin_password=None): ''' Configure CMC or individual iDRAC SNMP community string. Use ``deploy_snmp`` for configuring chassis switch SNMP. CLI Example: .. code-block:: bash salt dell dracr.set_snmp [COMMUNITY] salt dell dracr.set_snmp public ''' return __execute_cmd('config -g cfgOobSnmp -o ' 'cfgOobSnmpAgentCommunity {0}'.format(community), host=host, admin_username=admin_username, admin_password=admin_password)
def set_network(ip, netmask, gateway, host=None, admin_username=None, admin_password=None): ''' Configure Network on the CMC or individual iDRAC. Use ``set_niccfg`` for blade and switch addresses. CLI Example: .. code-block:: bash salt dell dracr.set_network [DRAC IP] [NETMASK] [GATEWAY] salt dell dracr.set_network 192.168.0.2 255.255.255.0 192.168.0.1 admin_username=root admin_password=calvin host=192.168.1.1 ''' return __execute_cmd('setniccfg -s {0} {1} {2}'.format( ip, netmask, gateway, host=host, admin_username=admin_username, admin_password=admin_password ))
def server_power(status, host=None, admin_username=None, admin_password=None, module=None): ''' status One of 'powerup', 'powerdown', 'powercycle', 'hardreset', 'graceshutdown' host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. module The element to reboot on the chassis such as a blade. If not provided, the chassis will be rebooted. CLI Example: .. code-block:: bash salt dell dracr.server_reboot salt dell dracr.server_reboot module=server-1 ''' return __execute_cmd('serveraction {0}'.format(status), host=host, admin_username=admin_username, admin_password=admin_password, module=module)
def server_reboot(host=None, admin_username=None, admin_password=None, module=None): ''' Issues a power-cycle operation on the managed server. This action is similar to pressing the power button on the system's front panel to power down and then power up the system. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. module The element to reboot on the chassis such as a blade. If not provided, the chassis will be rebooted. CLI Example: .. code-block:: bash salt dell dracr.server_reboot salt dell dracr.server_reboot module=server-1 ''' return __execute_cmd('serveraction powercycle', host=host, admin_username=admin_username, admin_password=admin_password, module=module)
def server_poweroff(host=None, admin_username=None, admin_password=None, module=None): ''' Powers down the managed server. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. module The element to power off on the chassis such as a blade. If not provided, the chassis will be powered off. CLI Example: .. code-block:: bash salt dell dracr.server_poweroff salt dell dracr.server_poweroff module=server-1 ''' return __execute_cmd('serveraction powerdown', host=host, admin_username=admin_username, admin_password=admin_password, module=module)
def server_poweron(host=None, admin_username=None, admin_password=None, module=None): ''' Powers up the managed server. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. module The element to power on located on the chassis such as a blade. If not provided, the chassis will be powered on. CLI Example: .. code-block:: bash salt dell dracr.server_poweron salt dell dracr.server_poweron module=server-1 ''' return __execute_cmd('serveraction powerup', host=host, admin_username=admin_username, admin_password=admin_password, module=module)
def server_hardreset(host=None, admin_username=None, admin_password=None, module=None): ''' Performs a reset (reboot) operation on the managed server. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. module The element to hard reset on the chassis such as a blade. If not provided, the chassis will be reset. CLI Example: .. code-block:: bash salt dell dracr.server_hardreset salt dell dracr.server_hardreset module=server-1 ''' return __execute_cmd('serveraction hardreset', host=host, admin_username=admin_username, admin_password=admin_password, module=module)
def server_powerstatus(host=None, admin_username=None, admin_password=None, module=None): ''' return the power status for the passed module CLI Example: .. code-block:: bash salt dell drac.server_powerstatus ''' ret = __execute_ret('serveraction powerstatus', host=host, admin_username=admin_username, admin_password=admin_password, module=module) result = {'retcode': 0} if ret['stdout'] == 'ON': result['status'] = True result['comment'] = 'Power is on' if ret['stdout'] == 'OFF': result['status'] = False result['comment'] = 'Power is on' if ret['stdout'].startswith('ERROR'): result['status'] = False result['comment'] = ret['stdout'] return result
def server_pxe(host=None, admin_username=None, admin_password=None): ''' Configure server to PXE perform a one off PXE boot CLI Example: .. code-block:: bash salt dell dracr.server_pxe ''' if __execute_cmd('config -g cfgServerInfo -o cfgServerFirstBootDevice PXE', host=host, admin_username=admin_username, admin_password=admin_password): if __execute_cmd('config -g cfgServerInfo -o cfgServerBootOnce 1', host=host, admin_username=admin_username, admin_password=admin_password): return server_reboot else: log.warning('failed to set boot order') return False log.warning('failed to configure PXE boot') return False
def list_slotnames(host=None, admin_username=None, admin_password=None): ''' List the names of all slots in the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt-call --local dracr.list_slotnames host=111.222.333.444 admin_username=root admin_password=secret ''' slotraw = __execute_ret('getslotname', host=host, admin_username=admin_username, admin_password=admin_password) if slotraw['retcode'] != 0: return slotraw slots = {} stripheader = True for l in slotraw['stdout'].splitlines(): if l.startswith('<'): stripheader = False continue if stripheader: continue fields = l.split() slots[fields[0]] = {} slots[fields[0]]['slot'] = fields[0] if len(fields) > 1: slots[fields[0]]['slotname'] = fields[1] else: slots[fields[0]]['slotname'] = '' if len(fields) > 2: slots[fields[0]]['hostname'] = fields[2] else: slots[fields[0]]['hostname'] = '' return slots
def get_slotname(slot, host=None, admin_username=None, admin_password=None): ''' Get the name of a slot number in the chassis. slot The number of the slot for which to obtain the name. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt-call --local dracr.get_slotname 0 host=111.222.333.444 admin_username=root admin_password=secret ''' slots = list_slotnames(host=host, admin_username=admin_username, admin_password=admin_password) # The keys for this dictionary are strings, not integers, so convert the # argument to a string slot = six.text_type(slot) return slots[slot]['slotname']
def set_slotname(slot, name, host=None, admin_username=None, admin_password=None): ''' Set the name of a slot in a chassis. slot The slot number to change. name The name to set. Can only be 15 characters long. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_slotname 2 my-slotname host=111.222.333.444 admin_username=root admin_password=secret ''' return __execute_cmd('config -g cfgServerInfo -o cfgServerName -i {0} {1}'.format(slot, name), host=host, admin_username=admin_username, admin_password=admin_password)
def set_chassis_name(name, host=None, admin_username=None, admin_password=None): ''' Set the name of the chassis. name The name to be set on the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_chassis_name my-chassis host=111.222.333.444 admin_username=root admin_password=secret ''' return __execute_cmd('setsysinfo -c chassisname {0}'.format(name), host=host, admin_username=admin_username, admin_password=admin_password)
def get_chassis_name(host=None, admin_username=None, admin_password=None): ''' Get the name of a chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.get_chassis_name host=111.222.333.444 admin_username=root admin_password=secret ''' return bare_rac_cmd('getchassisname', host=host, admin_username=admin_username, admin_password=admin_password)
def set_chassis_location(location, host=None, admin_username=None, admin_password=None): ''' Set the location of the chassis. location The name of the location to be set on the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_chassis_location location-name host=111.222.333.444 admin_username=root admin_password=secret ''' return __execute_cmd('setsysinfo -c chassislocation {0}'.format(location), host=host, admin_username=admin_username, admin_password=admin_password)
def get_chassis_location(host=None, admin_username=None, admin_password=None): ''' Get the location of the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_chassis_location host=111.222.333.444 admin_username=root admin_password=secret ''' return system_info(host=host, admin_username=admin_username, admin_password=admin_password)['Chassis Information']['Chassis Location']
def set_chassis_datacenter(location, host=None, admin_username=None, admin_password=None): ''' Set the location of the chassis. location The name of the datacenter to be set on the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_chassis_datacenter datacenter-name host=111.222.333.444 admin_username=root admin_password=secret ''' return set_general('cfgLocation', 'cfgLocationDatacenter', location, host=host, admin_username=admin_username, admin_password=admin_password)
def get_chassis_datacenter(host=None, admin_username=None, admin_password=None): ''' Get the datacenter of the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_chassis_location host=111.222.333.444 admin_username=root admin_password=secret ''' return get_general('cfgLocation', 'cfgLocationDatacenter', host=host, admin_username=admin_username, admin_password=admin_password)
def idrac_general(blade_name, command, idrac_password=None, host=None, admin_username=None, admin_password=None): ''' Run a generic racadm command against a particular blade in a chassis. Blades are usually named things like 'server-1', 'server-2', etc. If the iDRAC has a different password than the CMC, then you can pass it with the idrac_password kwarg. :param blade_name: Name of the blade to run the command on :param command: Command like to pass to racadm :param idrac_password: Password for the iDRAC if different from the CMC :param host: Chassis hostname :param admin_username: CMC username :param admin_password: CMC password :return: stdout if the retcode is 0, otherwise a standard cmd.run_all dictionary CLI Example: .. code-block:: bash salt fx2 chassis.cmd idrac_general server-1 'get BIOS.SysProfileSettings' ''' module_network = network_info(host, admin_username, admin_password, blade_name) if idrac_password is not None: password = idrac_password else: password = admin_password idrac_ip = module_network['Network']['IP Address'] ret = __execute_ret(command, host=idrac_ip, admin_username='root', admin_password=password) if ret['retcode'] == 0: return ret['stdout'] else: return ret
def update_firmware(filename, host=None, admin_username=None, admin_password=None): ''' Updates firmware using local firmware file .. code-block:: bash salt dell dracr.update_firmware firmware.exe This executes the following command on your FX2 (using username and password stored in the pillar data) .. code-block:: bash racadm update –f firmware.exe -u user –p pass ''' if os.path.exists(filename): return _update_firmware('update -f {0}'.format(filename), host=None, admin_username=None, admin_password=None) else: raise CommandExecutionError('Unable to find firmware file {0}' .format(filename))
def update_firmware_nfs_or_cifs(filename, share, host=None, admin_username=None, admin_password=None): ''' Executes the following for CIFS (using username and password stored in the pillar data) .. code-block:: bash racadm update -f <updatefile> -u user –p pass -l //IP-Address/share Or for NFS (using username and password stored in the pillar data) .. code-block:: bash racadm update -f <updatefile> -u user –p pass -l IP-address:/share Salt command for CIFS: .. code-block:: bash salt dell dracr.update_firmware_nfs_or_cifs \ firmware.exe //IP-Address/share Salt command for NFS: .. code-block:: bash salt dell dracr.update_firmware_nfs_or_cifs \ firmware.exe IP-address:/share ''' if os.path.exists(filename): return _update_firmware('update -f {0} -l {1}'.format(filename, share), host=None, admin_username=None, admin_password=None) else: raise CommandExecutionError('Unable to find firmware file {0}' .format(filename))
def post_card(name, message, hook_url=None, title=None, theme_color=None): ''' Send a message to a Microsft Teams channel .. code-block:: yaml send-msteams-message: msteams.post_card: - message: 'This state was executed successfully.' - hook_url: https://outlook.office.com/webhook/837 The following parameters are required: message The message that is to be sent to the MS Teams channel. The following parameters are optional: hook_url The webhook URL given configured in Teams interface, if not specified in the configuration options of master or minion. title The title for the card posted to the channel theme_color A hex code for the desired highlight color ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: ret['comment'] = 'The following message is to be sent to Teams: {0}'.format(message) ret['result'] = None return ret if not message: ret['comment'] = 'Teams message is missing: {0}'.format(message) return ret try: result = __salt__['msteams.post_card']( message=message, hook_url=hook_url, title=title, theme_color=theme_color, ) except SaltInvocationError as sie: ret['comment'] = 'Failed to send message ({0}): {1}'.format(sie, name) else: if isinstance(result, bool) and result: ret['result'] = True ret['comment'] = 'Sent message: {0}'.format(name) else: ret['comment'] = 'Failed to send message ({0}): {1}'.format(result['message'], name) return ret
def accept_dict(match, include_rejected=False, include_denied=False): ''' Accept keys based on a dict of keys. Returns a dictionary. match The dictionary of keys to accept. include_rejected To include rejected keys in the match along with pending keys, set this to ``True``. Defaults to ``False``. .. versionadded:: 2016.3.4 include_denied To include denied keys in the match along with pending keys, set this to ``True``. Defaults to ``False``. .. versionadded:: 2016.3.4 Example to move a list of keys from the ``minions_pre`` (pending) directory to the ``minions`` (accepted) directory: .. code-block:: python >>> wheel.cmd('key.accept_dict', { 'minions_pre': [ 'jerry', 'stuart', 'bob', ], }) {'minions': ['jerry', 'stuart', 'bob']} ''' skey = get_key(__opts__) return skey.accept(match_dict=match, include_rejected=include_rejected, include_denied=include_denied)
def reject(match, include_accepted=False, include_denied=False): ''' Reject keys based on a glob match. Returns a dictionary. match The glob match of keys to reject. include_accepted To include accepted keys in the match along with pending keys, set this to ``True``. Defaults to ``False``. include_denied To include denied keys in the match along with pending keys, set this to ``True``. Defaults to ``False``. .. code-block:: python >>> wheel.cmd_async({'fun': 'key.reject', 'match': 'minion1'}) {'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'} ''' skey = get_key(__opts__) return skey.reject(match, include_accepted=include_accepted, include_denied=include_denied)
def finger(match, hash_type=None): ''' Return the matching key fingerprints. Returns a dictionary. match The key for with to retrieve the fingerprint. hash_type The hash algorithm used to calculate the fingerprint .. code-block:: python >>> wheel.cmd('key.finger', ['minion1']) {'minions': {'minion1': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}} ''' if hash_type is None: hash_type = __opts__['hash_type'] skey = get_key(__opts__) return skey.finger(match, hash_type)
def finger_master(hash_type=None): ''' Return the fingerprint of the master's public key hash_type The hash algorithm used to calculate the fingerprint .. code-block:: python >>> wheel.cmd('key.finger_master') {'local': {'master.pub': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}} ''' keyname = 'master.pub' if hash_type is None: hash_type = __opts__['hash_type'] fingerprint = salt.utils.crypt.pem_finger( os.path.join(__opts__['pki_dir'], keyname), sum_type=hash_type) return {'local': {keyname: fingerprint}}
def gen(id_=None, keysize=2048): r''' Generate a key pair. No keys are stored on the master. A key pair is returned as a dict containing pub and priv keys. Returns a dictionary containing the the ``pub`` and ``priv`` keys with their generated values. id\_ Set a name to generate a key pair for use with salt. If not specified, a random name will be specified. keysize The size of the key pair to generate. The size must be ``2048``, which is the default, or greater. If set to a value less than ``2048``, the key size will be rounded up to ``2048``. .. code-block:: python >>> wheel.cmd('key.gen') {'pub': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBC ... BBPfamX9gGPQTpN9e8HwcZjXQnmg8OrcUl10WHw09SDWLOlnW+ueTWugEQpPt\niQIDAQAB\n -----END PUBLIC KEY-----', 'priv': '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA42Kf+w9XeZWgguzv ... QH3/W74X1+WTBlx4R2KGLYBiH+bCCFEQ/Zvcu4Xp4bIOPtRKozEQ==\n -----END RSA PRIVATE KEY-----'} ''' if id_ is None: id_ = hashlib.sha512(os.urandom(32)).hexdigest() else: id_ = clean.filename(id_) ret = {'priv': '', 'pub': ''} priv = salt.crypt.gen_keys(__opts__['pki_dir'], id_, keysize) pub = '{0}.pub'.format(priv[:priv.rindex('.')]) with salt.utils.files.fopen(priv) as fp_: ret['priv'] = salt.utils.stringutils.to_unicode(fp_.read()) with salt.utils.files.fopen(pub) as fp_: ret['pub'] = salt.utils.stringutils.to_unicode(fp_.read()) # The priv key is given the Read-Only attribute. The causes `os.remove` to # fail in Windows. if salt.utils.platform.is_windows(): os.chmod(priv, 128) os.remove(priv) os.remove(pub) return ret
def gen_accept(id_, keysize=2048, force=False): r''' Generate a key pair then accept the public key. This function returns the key pair in a dict, only the public key is preserved on the master. Returns a dictionary. id\_ The name of the minion for which to generate a key pair. keysize The size of the key pair to generate. The size must be ``2048``, which is the default, or greater. If set to a value less than ``2048``, the key size will be rounded up to ``2048``. force If a public key has already been accepted for the given minion on the master, then the gen_accept function will return an empty dictionary and not create a new key. This is the default behavior. If ``force`` is set to ``True``, then the minion's previously accepted key will be overwritten. .. code-block:: python >>> wheel.cmd('key.gen_accept', ['foo']) {'pub': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBC ... BBPfamX9gGPQTpN9e8HwcZjXQnmg8OrcUl10WHw09SDWLOlnW+ueTWugEQpPt\niQIDAQAB\n -----END PUBLIC KEY-----', 'priv': '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA42Kf+w9XeZWgguzv ... QH3/W74X1+WTBlx4R2KGLYBiH+bCCFEQ/Zvcu4Xp4bIOPtRKozEQ==\n -----END RSA PRIVATE KEY-----'} We can now see that the ``foo`` minion's key has been accepted by the master: .. code-block:: python >>> wheel.cmd('key.list', ['accepted']) {'minions': ['foo', 'minion1', 'minion2', 'minion3']} ''' id_ = clean.id(id_) ret = gen(id_, keysize) acc_path = os.path.join(__opts__['pki_dir'], 'minions', id_) if os.path.isfile(acc_path) and not force: return {} with salt.utils.files.fopen(acc_path, 'w+') as fp_: fp_.write(salt.utils.stringutils.to_str(ret['pub'])) return ret
def gen_keys(keydir=None, keyname=None, keysize=None, user=None): ''' Generate minion RSA public keypair ''' skey = get_key(__opts__) return skey.gen_keys(keydir, keyname, keysize, user)
def gen_signature(priv, pub, signature_path, auto_create=False, keysize=None): ''' Generate master public-key-signature ''' skey = get_key(__opts__) return skey.gen_keys_signature(priv, pub, signature_path, auto_create, keysize)
def dirinfo(path, opts=None): ''' Return information on a directory located on the Moose CLI Example: .. code-block:: bash salt '*' moosefs.dirinfo /path/to/dir/ [-[n][h|H]] ''' cmd = 'mfsdirinfo' ret = {} if opts: cmd += ' -' + opts cmd += ' ' + path out = __salt__['cmd.run_all'](cmd, python_shell=False) output = out['stdout'].splitlines() for line in output: if not line: continue comps = line.split(':') ret[comps[0].strip()] = comps[1].strip() return ret
def fileinfo(path): ''' Return information on a file located on the Moose CLI Example: .. code-block:: bash salt '*' moosefs.fileinfo /path/to/dir/ ''' cmd = 'mfsfileinfo ' + path ret = {} chunknum = '' out = __salt__['cmd.run_all'](cmd, python_shell=False) output = out['stdout'].splitlines() for line in output: if not line: continue if '/' in line: comps = line.split('/') chunknum = comps[0].strip().split(':') meta = comps[1].strip().split(' ') chunk = chunknum[0].replace('chunk ', '') loc = chunknum[1].strip() id_ = meta[0].replace('(id:', '') ver = meta[1].replace(')', '').replace('ver:', '') ret[chunknum[0]] = { 'chunk': chunk, 'loc': loc, 'id': id_, 'ver': ver, } if 'copy' in line: copyinfo = line.strip().split(':') ret[chunknum[0]][copyinfo[0]] = { 'copy': copyinfo[0].replace('copy ', ''), 'ip': copyinfo[1].strip(), 'port': copyinfo[2], } return ret
def mounts(): ''' Return a list of current MooseFS mounts CLI Example: .. code-block:: bash salt '*' moosefs.mounts ''' cmd = 'mount' ret = {} out = __salt__['cmd.run_all'](cmd) output = out['stdout'].splitlines() for line in output: if not line: continue if 'fuse.mfs' in line: comps = line.split(' ') info1 = comps[0].split(':') info2 = info1[1].split('/') ret[comps[2]] = { 'remote': { 'master': info1[0], 'port': info2[0], 'subfolder': '/' + info2[1], }, 'local': comps[2], 'options': (comps[5].replace('(', '').replace(')', '') .split(',')), } return ret
def getgoal(path, opts=None): ''' Return goal(s) for a file or directory CLI Example: .. code-block:: bash salt '*' moosefs.getgoal /path/to/file [-[n][h|H]] salt '*' moosefs.getgoal /path/to/dir/ [-[n][h|H][r]] ''' cmd = 'mfsgetgoal' ret = {} if opts: cmd += ' -' + opts else: opts = '' cmd += ' ' + path out = __salt__['cmd.run_all'](cmd, python_shell=False) output = out['stdout'].splitlines() if 'r' not in opts: goal = output[0].split(': ') ret = { 'goal': goal[1], } else: for line in output: if not line: continue if path in line: continue comps = line.split() keytext = comps[0] + ' with goal' if keytext not in ret: ret[keytext] = {} ret[keytext][comps[3]] = comps[5] return ret
def _auditpol_cmd(cmd): ''' Helper function for running the auditpol command Args: cmd (str): the auditpol command to run Returns: list: A list containing each line of the return (splitlines) Raises: CommandExecutionError: If the command encounters an error ''' ret = salt.modules.cmdmod.run_all(cmd='auditpol {0}'.format(cmd), python_shell=True) if ret['retcode'] == 0: return ret['stdout'].splitlines() msg = 'Error executing auditpol command: {0}\n'.format(cmd) msg += '\n'.join(ret['stdout']) raise CommandExecutionError(msg)
def get_settings(category='All'): ''' Get the current configuration for all audit settings specified in the category Args: category (str): One of the nine categories to return. Can also be ``All`` to return the settings for all categories. Valid options are: - Account Logon - Account Management - Detailed Tracking - DS Access - Logon/Logoff - Object Access - Policy Change - Privilege Use - System - All Default value is ``All`` Returns: dict: A dictionary containing all subcategories for the specified category along with their current configuration Raises: KeyError: On invalid category CommandExecutionError: If an error is encountered retrieving the settings Usage: .. code-block:: python import salt.utils.win_lgpo_auditpol # Get current state of all audit settings salt.utils.win_lgpo_auditpol.get_settings() # Get the current state of all audit settings in the "Account Logon" # category salt.utils.win_lgpo_auditpol.get_settings(category="Account Logon") ''' # Parameter validation if category.lower() in ['all', '*']: category = '*' elif category.lower() not in [x.lower() for x in categories]: raise KeyError('Invalid category: "{0}"'.format(category)) cmd = '/get /category:"{0}"'.format(category) results = _auditpol_cmd(cmd) ret = {} # Skip the first 2 lines for line in results[3:]: if ' ' in line.strip(): ret.update(dict(list(zip(*[iter(re.split(r"\s{2,}", line.strip()))]*2)))) return ret
def get_setting(name): ''' Get the current configuration for the named audit setting Args: name (str): The name of the setting to retrieve Returns: str: The current configuration for the named setting Raises: KeyError: On invalid setting name CommandExecutionError: If an error is encountered retrieving the settings Usage: .. code-block:: python import salt.utils.win_lgpo_auditpol # Get current state of the "Credential Validation" setting salt.utils.win_lgpo_auditpol.get_setting(name='Credential Validation') ''' current_settings = get_settings(category='All') for setting in current_settings: if name.lower() == setting.lower(): return current_settings[setting] raise KeyError('Invalid name: {0}'.format(name))
def set_setting(name, value): ''' Set the configuration for the named audit setting Args: name (str): The name of the setting to configure value (str): The configuration for the named value. Valid options are: - No Auditing - Success - Failure - Success and Failure Returns: bool: True if successful Raises: KeyError: On invalid ``name`` or ``value`` CommandExecutionError: If an error is encountered modifying the setting Usage: .. code-block:: python import salt.utils.win_lgpo_auditpol # Set the state of the "Credential Validation" setting to Success and # Failure salt.utils.win_lgpo_auditpol.set_setting(name='Credential Validation', value='Success and Failure') # Set the state of the "Credential Validation" setting to No Auditing salt.utils.win_lgpo_auditpol.set_setting(name='Credential Validation', value='No Auditing') ''' # Input validation if name.lower() not in _get_valid_names(): raise KeyError('Invalid name: {0}'.format(name)) for setting in settings: if value.lower() == setting.lower(): cmd = '/set /subcategory:"{0}" {1}'.format(name, settings[setting]) break else: raise KeyError('Invalid setting value: {0}'.format(value)) _auditpol_cmd(cmd) return True
def get_auditpol_dump(): ''' Gets the contents of an auditpol /backup. Used by the LGPO module to get fieldnames and GUIDs for Advanced Audit policies. Returns: list: A list of lines form the backup file Usage: .. code-block:: python import salt.utils.win_lgpo_auditpol dump = salt.utils.win_lgpo_auditpol.get_auditpol_dump() ''' # Just get a temporary file name # NamedTemporaryFile will delete the file it creates by default on Windows with tempfile.NamedTemporaryFile(suffix='.csv') as tmp_file: csv_file = tmp_file.name cmd = '/backup /file:{0}'.format(csv_file) _auditpol_cmd(cmd) with salt.utils.files.fopen(csv_file) as fp: return fp.readlines()
def _ruby_installed(ret, ruby, user=None): ''' Check to see if given ruby is installed. ''' default = __salt__['rbenv.default'](runas=user) for version in __salt__['rbenv.versions'](user): if version == ruby: ret['result'] = True ret['comment'] = 'Requested ruby exists' ret['default'] = default == ruby break return ret
def _check_and_install_ruby(ret, ruby, default=False, user=None): ''' Verify that ruby is installed, install if unavailable ''' ret = _ruby_installed(ret, ruby, user=user) if not ret['result']: if __salt__['rbenv.install_ruby'](ruby, runas=user): ret['result'] = True ret['changes'][ruby] = 'Installed' ret['comment'] = 'Successfully installed ruby' ret['default'] = default else: ret['result'] = False ret['comment'] = 'Failed to install ruby' return ret if default: __salt__['rbenv.default'](ruby, runas=user) return ret
def installed(name, default=False, user=None): ''' Verify that the specified ruby is installed with rbenv. Rbenv is installed if necessary. name The version of ruby to install default : False Whether to make this ruby the default. user: None The user to run rbenv as. .. versionadded:: 0.17.0 .. versionadded:: 0.16.0 ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} rbenv_installed_ret = copy.deepcopy(ret) if name.startswith('ruby-'): name = re.sub(r'^ruby-', '', name) if __opts__['test']: ret = _ruby_installed(ret, name, user=user) if not ret['result']: ret['comment'] = 'Ruby {0} is set to be installed'.format(name) else: ret['comment'] = 'Ruby {0} is already installed'.format(name) return ret rbenv_installed_ret = _check_and_install_rbenv(rbenv_installed_ret, user) if rbenv_installed_ret['result'] is False: ret['result'] = False ret['comment'] = 'Rbenv failed to install' return ret else: return _check_and_install_ruby(ret, name, default, user=user)
def _check_and_uninstall_ruby(ret, ruby, user=None): ''' Verify that ruby is uninstalled ''' ret = _ruby_installed(ret, ruby, user=user) if ret['result']: if ret['default']: __salt__['rbenv.default']('system', runas=user) if __salt__['rbenv.uninstall_ruby'](ruby, runas=user): ret['result'] = True ret['changes'][ruby] = 'Uninstalled' ret['comment'] = 'Successfully removed ruby' return ret else: ret['result'] = False ret['comment'] = 'Failed to uninstall ruby' return ret else: ret['result'] = True ret['comment'] = 'Ruby {0} is already absent'.format(ruby) return ret
def absent(name, user=None): ''' Verify that the specified ruby is not installed with rbenv. Rbenv is installed if necessary. name The version of ruby to uninstall user: None The user to run rbenv as. .. versionadded:: 0.17.0 .. versionadded:: 0.16.0 ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if name.startswith('ruby-'): name = re.sub(r'^ruby-', '', name) ret = _check_rbenv(ret, user) if ret['result'] is False: ret['result'] = True ret['comment'] = 'Rbenv not installed, {0} not either'.format(name) return ret else: if __opts__['test']: ret = _ruby_installed(ret, name, user=user) if ret['result']: ret['result'] = None ret['comment'] = 'Ruby {0} is set to be uninstalled'.format(name) else: ret['result'] = True ret['comment'] = 'Ruby {0} is already uninstalled'.format(name) return ret return _check_and_uninstall_ruby(ret, name, user=user)
def _check_and_install_rbenv(ret, user=None): ''' Verify that rbenv is installed, install if unavailable ''' ret = _check_rbenv(ret, user) if ret['result'] is False: if __salt__['rbenv.install'](user): ret['result'] = True ret['comment'] = 'Rbenv installed' else: ret['result'] = False ret['comment'] = 'Rbenv failed to install' else: ret['result'] = True ret['comment'] = 'Rbenv is already installed' return ret
def install_rbenv(name, user=None): ''' Install rbenv if not installed. Allows you to require rbenv be installed prior to installing the plugins. Useful if you want to install rbenv plugins via the git or file modules and need them installed before installing any rubies. Use the rbenv.root configuration option to set the path for rbenv if you want a system wide install that is not in a user home dir. user: None The user to run rbenv as. ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if __opts__['test']: ret = _check_rbenv(ret, user=user) if ret['result'] is False: ret['result'] = None ret['comment'] = 'Rbenv is set to be installed' else: ret['result'] = True ret['comment'] = 'Rbenv is already installed' return ret return _check_and_install_rbenv(ret, user)
def build_rule(table=None, chain=None, command=None, position='', full=None, family='ipv4', **kwargs): ''' Build a well-formatted nftables rule based on kwargs. A `table` and `chain` are not required, unless `full` is True. If `full` is `True`, then `table`, `chain` and `command` are required. `command` may be specified as either insert, append, or delete. This will return the nftables command, exactly as it would be used from the command line. If a position is required (as with `insert` or `delete`), it may be specified as `position`. This will only be useful if `full` is True. If `connstate` is passed in, it will automatically be changed to `state`. CLI Examples: .. code-block:: bash salt '*' nftables.build_rule match=state \\ connstate=RELATED,ESTABLISHED jump=ACCEPT salt '*' nftables.build_rule filter input command=insert position=3 \\ full=True match=state state=related,established jump=accept IPv6: salt '*' nftables.build_rule match=state \\ connstate=related,established jump=accept \\ family=ipv6 salt '*' nftables.build_rule filter input command=insert position=3 \\ full=True match=state state=related,established jump=accept \\ family=ipv6 ''' ret = {'comment': '', 'rule': '', 'result': False} if 'target' in kwargs: kwargs['jump'] = kwargs['target'] del kwargs['target'] for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']: if ignore in kwargs: del kwargs[ignore] rule = '' proto = '' nft_family = _NFTABLES_FAMILIES[family] if 'if' in kwargs: rule += 'meta iifname {0} '.format(kwargs['if']) del kwargs['if'] if 'of' in kwargs: rule += 'meta oifname {0} '.format(kwargs['of']) del kwargs['of'] if 'proto' in kwargs: proto = kwargs['proto'] if 'state' in kwargs: del kwargs['state'] if 'connstate' in kwargs: rule += 'ct state {{ {0}}} '.format(kwargs['connstate']) del kwargs['connstate'] if 'dport' in kwargs: kwargs['dport'] = six.text_type(kwargs['dport']) if ':' in kwargs['dport']: kwargs['dport'] = kwargs['dport'].replace(':', '-') rule += 'dport {{ {0} }} '.format(kwargs['dport']) del kwargs['dport'] if 'sport' in kwargs: kwargs['sport'] = six.text_type(kwargs['sport']) if ':' in kwargs['sport']: kwargs['sport'] = kwargs['sport'].replace(':', '-') rule += 'sport {{ {0} }} '.format(kwargs['sport']) del kwargs['sport'] if 'dports' in kwargs: # nftables reverse sorts the ports from # high to low, create rule like this # so that the check will work _dports = kwargs['dports'].split(',') _dports = [int(x) for x in _dports] _dports.sort(reverse=True) kwargs['dports'] = ', '.join(six.text_type(x) for x in _dports) rule += 'dport {{ {0} }} '.format(kwargs['dports']) del kwargs['dports'] if 'sports' in kwargs: # nftables reverse sorts the ports from # high to low, create rule like this # so that the check will work _sports = kwargs['sports'].split(',') _sports = [int(x) for x in _sports] _sports.sort(reverse=True) kwargs['sports'] = ', '.join(six.text_type(x) for x in _sports) rule += 'sport {{ {0} }} '.format(kwargs['sports']) del kwargs['sports'] # Jumps should appear last, except for any arguments that are passed to # jumps, which of course need to follow. after_jump = [] if 'jump' in kwargs: after_jump.append('{0} '.format(kwargs['jump'])) del kwargs['jump'] if 'j' in kwargs: after_jump.append('{0} '.format(kwargs['j'])) del kwargs['j'] if 'to-port' in kwargs: after_jump.append('--to-port {0} '.format(kwargs['to-port'])) del kwargs['to-port'] if 'to-ports' in kwargs: after_jump.append('--to-ports {0} '.format(kwargs['to-ports'])) del kwargs['to-ports'] if 'to-destination' in kwargs: after_jump.append('--to-destination {0} '.format(kwargs['to-destination'])) del kwargs['to-destination'] if 'reject-with' in kwargs: after_jump.append('--reject-with {0} '.format(kwargs['reject-with'])) del kwargs['reject-with'] for item in after_jump: rule += item # Strip trailing spaces off rule rule = rule.strip() # Insert the protocol prior to dport or sport rule = rule.replace('dport', '{0} dport'.format(proto)) rule = rule.replace('sport', '{0} sport'.format(proto)) ret['rule'] = rule if full in ['True', 'true']: if not table: ret['comment'] = 'Table needs to be specified' return ret if not chain: ret['comment'] = 'Chain needs to be specified' return ret if not command: ret['comment'] = 'Command needs to be specified' return ret if command in ['Insert', 'insert', 'INSERT']: if position: ret['rule'] = '{0} insert rule {1} {2} {3} ' \ 'position {4} {5}'.format(_nftables_cmd(), nft_family, table, chain, position, rule) else: ret['rule'] = '{0} insert rule ' \ '{1} {2} {3} {4}'.format(_nftables_cmd(), nft_family, table, chain, rule) else: ret['rule'] = '{0} {1} rule {2} {3} {4} {5}'.format(_nftables_cmd(), command, nft_family, table, chain, rule) if ret['rule']: ret['comment'] = 'Successfully built rule' ret['result'] = True return ret
def get_saved_rules(conf_file=None): ''' Return a data structure of the rules in the conf file CLI Example: .. code-block:: bash salt '*' nftables.get_saved_rules ''' if _conf() and not conf_file: conf_file = _conf() with salt.utils.files.fopen(conf_file) as fp_: lines = salt.utils.data.decode(fp_.readlines()) rules = [] for line in lines: tmpline = line.strip() if not tmpline: continue if tmpline.startswith('#'): continue rules.append(line) return rules
def get_rules(family='ipv4'): ''' Return a data structure of the current, in-memory rules CLI Example: .. code-block:: bash salt '*' nftables.get_rules salt '*' nftables.get_rules family=ipv6 ''' nft_family = _NFTABLES_FAMILIES[family] rules = [] cmd = '{0} --numeric --numeric --numeric ' \ 'list tables {1}'. format(_nftables_cmd(), nft_family) out = __salt__['cmd.run'](cmd, python_shell=False) if not out: return rules tables = re.split('\n+', out) for table in tables: table_name = table.split(' ')[1] cmd = '{0} --numeric --numeric --numeric ' \ 'list table {1} {2}'.format(_nftables_cmd(), nft_family, table_name) out = __salt__['cmd.run'](cmd, python_shell=False) rules.append(out) return rules
def save(filename=None, family='ipv4'): ''' Save the current in-memory rules to disk CLI Example: .. code-block:: bash salt '*' nftables.save /etc/nftables ''' if _conf() and not filename: filename = _conf() nft_families = ['ip', 'ip6', 'arp', 'bridge'] rules = "#! nft -f\n" for family in nft_families: out = get_rules(family) if out: rules += '\n' rules = rules + '\n'.join(out) rules = rules + '\n' try: with salt.utils.files.fopen(filename, 'wb') as _fh: # Write out any changes _fh.writelines(salt.utils.data.encode(rules)) except (IOError, OSError) as exc: raise CommandExecutionError( 'Problem writing to configuration file: {0}'.format(exc) ) return rules
def get_rule_handle(table='filter', chain=None, rule=None, family='ipv4'): ''' Get the handle for a particular rule This function accepts a rule in a standard nftables command format, starting with the chain. Trying to force users to adapt to a new method of creating rules would be irritating at best, and we already have a parser that can handle it. CLI Example: .. code-block:: bash salt '*' nftables.get_rule_handle filter input \\ rule='tcp dport 22 log accept' IPv6: salt '*' nftables.get_rule_handle filter input \\ rule='tcp dport 22 log accept' \\ family=ipv6 ''' ret = {'comment': '', 'result': False} if not chain: ret['comment'] = 'Chain needs to be specified' return ret if not rule: ret['comment'] = 'Rule needs to be specified' return ret res = check_table(table, family=family) if not res['result']: return res res = check_chain(table, chain, family=family) if not res['result']: return res res = check(table, chain, rule, family=family) if not res['result']: return res nft_family = _NFTABLES_FAMILIES[family] cmd = '{0} --numeric --numeric --numeric --handle list chain {1} {2} {3}'.\ format(_nftables_cmd(), nft_family, table, chain) out = __salt__['cmd.run'](cmd, python_shell=False) rules = re.split('\n+', out) pat = re.compile(r'{0} # handle (?P<handle>\d+)'.format(rule)) for r in rules: match = pat.search(r) if match: return {'result': True, 'handle': match.group('handle')} return {'result': False, 'comment': 'Could not find rule {0}'.format(rule)}
def check(table='filter', chain=None, rule=None, family='ipv4'): ''' Check for the existence of a rule in the table and chain This function accepts a rule in a standard nftables command format, starting with the chain. Trying to force users to adapt to a new method of creating rules would be irritating at best, and we already have a parser that can handle it. CLI Example: .. code-block:: bash salt '*' nftables.check filter input \\ rule='tcp dport 22 log accept' IPv6: salt '*' nftables.check filter input \\ rule='tcp dport 22 log accept' \\ family=ipv6 ''' ret = {'comment': '', 'result': False} if not chain: ret['comment'] = 'Chain needs to be specified' return ret if not rule: ret['comment'] = 'Rule needs to be specified' return ret res = check_table(table, family=family) if not res['result']: return res res = check_chain(table, chain, family=family) if not res['result']: return res nft_family = _NFTABLES_FAMILIES[family] cmd = '{0} --handle --numeric --numeric --numeric list chain {1} {2} {3}'.\ format(_nftables_cmd(), nft_family, table, chain) search_rule = '{0} #'.format(rule) out = __salt__['cmd.run'](cmd, python_shell=False).find(search_rule) if out == -1: ret['comment'] = 'Rule {0} in chain {1} in table {2} in family {3} does not exist'.\ format(rule, chain, table, family) else: ret['comment'] = 'Rule {0} in chain {1} in table {2} in family {3} exists'.\ format(rule, chain, table, family) ret['result'] = True return ret
def check_table(table=None, family='ipv4'): ''' Check for the existence of a table CLI Example:: salt '*' nftables.check_table nat ''' ret = {'comment': '', 'result': False} if not table: ret['comment'] = 'Table needs to be specified' return ret nft_family = _NFTABLES_FAMILIES[family] cmd = '{0} list tables {1}' . format(_nftables_cmd(), nft_family) out = __salt__['cmd.run'](cmd, python_shell=False).find('table {0} {1}'.format(nft_family, table)) if out == -1: ret['comment'] = 'Table {0} in family {1} does not exist'.\ format(table, family) else: ret['comment'] = 'Table {0} in family {1} exists'.\ format(table, family) ret['result'] = True return ret
def new_chain(table='filter', chain=None, table_type=None, hook=None, priority=None, family='ipv4'): ''' .. versionadded:: 2014.7.0 Create new chain to the specified table. CLI Example: .. code-block:: bash salt '*' nftables.new_chain filter input salt '*' nftables.new_chain filter input \\ table_type=filter hook=input priority=0 salt '*' nftables.new_chain filter foo IPv6: salt '*' nftables.new_chain filter input family=ipv6 salt '*' nftables.new_chain filter input \\ table_type=filter hook=input priority=0 family=ipv6 salt '*' nftables.new_chain filter foo family=ipv6 ''' ret = {'comment': '', 'result': False} if not chain: ret['comment'] = 'Chain needs to be specified' return ret res = check_table(table, family=family) if not res['result']: return res res = check_chain(table, chain, family=family) if res['result']: ret['comment'] = 'Chain {0} in table {1} in family {2} already exists'.\ format(chain, table, family) return ret nft_family = _NFTABLES_FAMILIES[family] cmd = '{0} add chain {1} {2} {3}'.\ format(_nftables_cmd(), nft_family, table, chain) if table_type or hook or priority: if table_type and hook and six.text_type(priority): cmd = r'{0} \{{ type {1} hook {2} priority {3}\; \}}'.\ format(cmd, table_type, hook, priority) else: # Specify one, require all ret['comment'] = 'Table_type, hook, and priority required.' return ret out = __salt__['cmd.run'](cmd, python_shell=False) if not out: ret['comment'] = 'Chain {0} in table {1} in family {2} created'.\ format(chain, table, family) ret['result'] = True else: ret['comment'] = 'Chain {0} in table {1} in family {2} could not be created'.\ format(chain, table, family) return ret
def flush(table='filter', chain='', family='ipv4'): ''' Flush the chain in the specified table, flush all chains in the specified table if chain is not specified. CLI Example: .. code-block:: bash salt '*' nftables.flush filter salt '*' nftables.flush filter input IPv6: salt '*' nftables.flush filter input family=ipv6 ''' ret = {'comment': 'Failed to flush rules from chain {0} in table {1}.'.format(chain, table), 'result': False} res = check_table(table, family=family) if not res['result']: return res nft_family = _NFTABLES_FAMILIES[family] if chain: res = check_chain(table, chain, family=family) if not res['result']: return res cmd = '{0} flush chain {1} {2} {3}'.\ format(_nftables_cmd(), nft_family, table, chain) comment = 'from chain {0} in table {1} in family {2}.'.\ format(chain, table, family) else: cmd = '{0} flush table {1} {2}'.\ format(_nftables_cmd(), nft_family, table) comment = 'from table {0} in family {1}.'.\ format(table, family) out = __salt__['cmd.run'](cmd, python_shell=False) if len(out) == 0: ret['result'] = True ret['comment'] = 'Flushed rules {0}'.format(comment) else: ret['comment'] = 'Failed to flush rules {0}'.format(comment) return ret
def rewrite_single_shorthand_state_decl(data): # pylint: disable=C0103 ''' Rewrite all state declarations that look like this:: state_id_decl: state.func into:: state_id_decl: state.func: [] ''' for sid, states in six.iteritems(data): if isinstance(states, six.string_types): data[sid] = {states: []}
def _relative_to_abs_sls(relative, sls): ''' Convert ``relative`` sls reference into absolute, relative to ``sls``. ''' levels, suffix = re.match(r'^(\.+)(.*)$', relative).groups() level_count = len(levels) p_comps = sls.split('.') if level_count > len(p_comps): raise SaltRenderError( 'Attempted relative include goes beyond top level package' ) return '.'.join(p_comps[:-level_count] + [suffix])
def nvlist(thelist, names=None): ''' Given a list of items:: - whatever - name1: value1 - name2: - key: value - key: value return a generator that yields each (item, key, value) tuple, skipping items that are not name-value's(dictionaries) or those not in the list of matching names. The item in the returned tuple is the single-key dictionary. ''' # iterate over the list under the state dict. for nvitem in thelist: if isinstance(nvitem, dict): # then nvitem is a name-value item(a dict) of the list. name, value = next(six.iteritems(nvitem)) if names is None or name in names: yield nvitem, name, value
def nvlist2(thelist, names=None): ''' Like nvlist but applied one more time to each returned value. So, given a list, args, of arguments to a state like this:: - name: echo test - cwd: / - require: - file: test.sh nvlist2(args, ['require']) would yield the tuple, (dict_item, 'file', 'test.sh') where dict_item is the single-key dictionary of {'file': 'test.sh'}. ''' for _, _, value in nvlist(thelist, names): for each in nvlist(value): yield each
def _get_api_params(api_url=None, page_id=None, api_key=None, api_version=None): ''' Retrieve the API params from the config file. ''' statuspage_cfg = __salt__['config.get']('statuspage') if not statuspage_cfg: statuspage_cfg = {} return { 'api_url': api_url or statuspage_cfg.get('api_url') or BASE_URL, # optional 'api_page_id': page_id or statuspage_cfg.get('page_id'), # mandatory 'api_key': api_key or statuspage_cfg.get('api_key'), # mandatory 'api_version': api_version or statuspage_cfg.get('api_version') or DEFAULT_VERSION }
def _validate_api_params(params): ''' Validate the API params as specified in the config file. ''' # page_id and API key are mandatory and they must be string/unicode return (isinstance(params['api_page_id'], (six.string_types, six.text_type)) and isinstance(params['api_key'], (six.string_types, six.text_type)))
def _http_request(url, method='GET', headers=None, data=None): ''' Make the HTTP request and return the body as python object. ''' req = requests.request(method, url, headers=headers, data=data) ret = _default_ret() ok_status = METHOD_OK_STATUS.get(method, 200) if req.status_code != ok_status: ret.update({ 'comment': req.json().get('error', '') }) return ret ret.update({ 'result': True, 'out': req.json() if method != 'DELETE' else None # no body when DELETE }) return ret
def retrieve(endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None): ''' Retrieve a specific endpoint from the Statuspage API. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. CLI Example: .. code-block:: bash salt 'minion' statuspage.retrieve components Example output: .. code-block:: bash minion: ---------- comment: out: |_ ---------- backfilled: False created_at: 2015-01-26T20:25:02.702Z id: kh2qwjbheqdc36 impact: major impact_override: None incident_updates: |_ ---------- affected_components: None body: We are currently investigating this issue. created_at: 2015-01-26T20:25:02.849Z display_at: 2015-01-26T20:25:02.849Z id: zvx7xz2z5skr incident_id: kh2qwjbheqdc36 status: investigating twitter_updated_at: None updated_at: 2015-01-26T20:25:02.849Z wants_twitter_update: False monitoring_at: None name: just testing some stuff page_id: ksdhgfyiuhaa postmortem_body: None postmortem_body_last_updated_at: None postmortem_ignored: False postmortem_notified_subscribers: False postmortem_notified_twitter: False postmortem_published_at: None resolved_at: None scheduled_auto_completed: False scheduled_auto_in_progress: False scheduled_for: None scheduled_remind_prior: False scheduled_reminded_at: None scheduled_until: None shortlink: http://stspg.io/voY status: investigating updated_at: 2015-01-26T20:25:13.379Z result: True ''' params = _get_api_params(api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not _validate_api_params(params): log.error('Invalid API params.') log.error(params) return { 'result': False, 'comment': 'Invalid API params. See log for details' } headers = _get_headers(params) retrieve_url = '{base_url}/v{version}/pages/{page_id}/{endpoint}.json'.format( base_url=params['api_url'], version=params['api_version'], page_id=params['api_page_id'], endpoint=endpoint ) return _http_request(retrieve_url, headers=headers)
def update(endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. CLI Example: .. code-block:: bash salt 'minion' statuspage.update id=dz959yz2nd4l status=resolved Example output: .. code-block:: bash minion: ---------- comment: out: ---------- created_at: 2017-01-03T15:25:30.718Z description: None group_id: 993vgplshj12 id: dz959yz2nd4l name: Management Portal page_id: xzwjjdw87vpf position: 11 status: resolved updated_at: 2017-01-05T15:34:27.676Z result: True ''' endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) return { 'result': False, 'comment': 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) } params = _get_api_params(api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not _validate_api_params(params): log.error('Invalid API params.') log.error(params) return { 'result': False, 'comment': 'Invalid API params. See log for details' } headers = _get_headers(params) update_url = '{base_url}/v{version}/pages/{page_id}/{endpoint}/{id}.json'.format( base_url=params['api_url'], version=params['api_version'], page_id=params['api_page_id'], endpoint=endpoint, id=id ) change_request = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__') or karg in UPDATE_FORBIDDEN_FILEDS: continue change_request_key = '{endpoint_sg}[{karg}]'.format( endpoint_sg=endpoint_sg, karg=karg ) change_request[change_request_key] = warg return _http_request(update_url, method='PATCH', headers=headers, data=change_request)
def delete(endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. CLI Example: .. code-block:: bash salt 'minion' statuspage.delete endpoint='components' id='ftgks51sfs2d' Example output: .. code-block:: bash minion: ---------- comment: out: None result: True ''' params = _get_api_params(api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not _validate_api_params(params): log.error('Invalid API params.') log.error(params) return { 'result': False, 'comment': 'Invalid API params. See log for details' } endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) return { 'result': False, 'comment': 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) } headers = _get_headers(params) delete_url = '{base_url}/v{version}/pages/{page_id}/{endpoint}/{id}.json'.format( base_url=params['api_url'], version=params['api_version'], page_id=params['api_page_id'], endpoint=endpoint, id=id ) return _http_request(delete_url, method='DELETE', headers=headers)
def _get_repo_options(fromrepo=None, packagesite=None): ''' Return a list of tuples to seed the "env" list, which is used to set environment variables for any pkg_add commands that are spawned. If ``fromrepo`` or ``packagesite`` are None, then their corresponding config parameter will be looked up with config.get. If both ``fromrepo`` and ``packagesite`` are None, and neither freebsdpkg.PACKAGEROOT nor freebsdpkg.PACKAGESITE are specified, then an empty list is returned, and it is assumed that the system defaults (or environment variables) will be used. ''' root = fromrepo if fromrepo is not None \ else __salt__['config.get']('freebsdpkg.PACKAGEROOT', None) site = packagesite if packagesite is not None \ else __salt__['config.get']('freebsdpkg.PACKAGESITE', None) ret = {} if root is not None: ret['PACKAGEROOT'] = root if site is not None: ret['PACKAGESITE'] = site return ret
def _match(names): ''' Since pkg_delete requires the full "pkgname-version" string, this function will attempt to match the package name with its version. Returns a list of partial matches and package names that match the "pkgname-version" string required by pkg_delete, and a list of errors encountered. ''' pkgs = list_pkgs(versions_as_list=True) errors = [] # Look for full matches full_pkg_strings = [] out = __salt__['cmd.run_stdout'](['pkg_info'], output_loglevel='trace', python_shell=False) for line in out.splitlines(): try: full_pkg_strings.append(line.split()[0]) except IndexError: continue full_matches = [x for x in names if x in full_pkg_strings] # Look for pkgname-only matches matches = [] ambiguous = [] for name in set(names) - set(full_matches): cver = pkgs.get(name) if cver is not None: if len(cver) == 1: matches.append('{0}-{1}'.format(name, cver[0])) else: ambiguous.append(name) errors.append( 'Ambiguous package \'{0}\'. Full name/version required. ' 'Possible matches: {1}'.format( name, ', '.join(['{0}-{1}'.format(name, x) for x in cver]) ) ) # Find packages that did not match anything not_matched = \ set(names) - set(matches) - set(full_matches) - set(ambiguous) for name in not_matched: errors.append('Package \'{0}\' not found'.format(name)) return matches + full_matches, errors