repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/modules/bigip.py
|
create_virtual
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L1237-L1523
|
[
"def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n",
"def _build_session(username, password, trans_label=None):\n '''\n Create a session to be used when connecting to iControl REST.\n '''\n\n bigip = requests.session()\n bigip.auth = (username, password)\n bigip.verify = False\n bigip.headers.update({'Content-Type': 'application/json'})\n\n if trans_label:\n #pull the trans id from the grain\n trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))\n\n if trans_id:\n bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})\n else:\n bigip.headers.update({'X-F5-REST-Coordination-Id': None})\n\n return bigip\n",
"def _load_response(response):\n '''\n Load the response from json data, return the dictionary or raw text\n '''\n\n try:\n data = salt.utils.json.loads(response.text)\n except ValueError:\n data = response.text\n\n ret = {'code': response.status_code, 'content': data}\n\n return ret\n",
"def _load_connection_error(hostname, error):\n '''\n Format and Return a connection error\n '''\n\n ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n\n return ret\n",
"def _loop_payload(params):\n '''\n Pass in a dictionary of parameters, loop through them and build a payload containing,\n parameters who's values are not None.\n '''\n\n #construct the payload\n payload = {}\n\n #set the payload\n for param, value in six.iteritems(params):\n if value is not None:\n payload[param] = value\n\n return payload\n",
"def _build_list(option_value, item_kind):\n '''\n pass in an option to check for a list of items, create a list of dictionary of items to set\n for this option\n '''\n #specify profiles if provided\n if option_value is not None:\n\n items = []\n\n #if user specified none, return an empty list\n if option_value == 'none':\n return items\n\n #was a list already passed in?\n if not isinstance(option_value, list):\n values = option_value.split(',')\n else:\n values = option_value\n\n for value in values:\n # sometimes the bigip just likes a plain ol list of items\n if item_kind is None:\n items.append(value)\n # other times it's picky and likes key value pairs...\n else:\n items.append({'kind': item_kind, 'name': value})\n return items\n return None\n",
"def _determine_toggles(payload, toggles):\n '''\n BigIP can't make up its mind if it likes yes / no or true or false.\n Figure out what it likes to hear without confusing the user.\n '''\n\n for toggle, definition in six.iteritems(toggles):\n #did the user specify anything?\n if definition['value'] is not None:\n #test for yes_no toggle\n if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no':\n payload[toggle] = 'yes'\n elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no':\n payload[toggle] = 'no'\n\n #test for true_false toggle\n if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false':\n payload[toggle] = True\n elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false':\n payload[toggle] = False\n\n return payload\n"
] |
# -*- coding: utf-8 -*-
'''
An execution module which can manipulate an f5 bigip via iControl REST
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.json
# Import third party libs
try:
import requests
import requests.exceptions
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
# Import 3rd-party libs
from salt.ext import six
# Import salt libs
import salt.exceptions
# Define the module's virtual name
__virtualname__ = 'bigip'
def __virtual__():
'''
Only return if requests is installed
'''
if HAS_LIBS:
return __virtualname__
return (False, 'The bigip execution module cannot be loaded: '
'python requests library not available.')
BIG_IP_URL_BASE = 'https://{host}/mgmt/tm'
def _build_session(username, password, trans_label=None):
'''
Create a session to be used when connecting to iControl REST.
'''
bigip = requests.session()
bigip.auth = (username, password)
bigip.verify = False
bigip.headers.update({'Content-Type': 'application/json'})
if trans_label:
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))
if trans_id:
bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})
else:
bigip.headers.update({'X-F5-REST-Coordination-Id': None})
return bigip
def _load_response(response):
'''
Load the response from json data, return the dictionary or raw text
'''
try:
data = salt.utils.json.loads(response.text)
except ValueError:
data = response.text
ret = {'code': response.status_code, 'content': data}
return ret
def _load_connection_error(hostname, error):
'''
Format and Return a connection error
'''
ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)}
return ret
def _loop_payload(params):
'''
Pass in a dictionary of parameters, loop through them and build a payload containing,
parameters who's values are not None.
'''
#construct the payload
payload = {}
#set the payload
for param, value in six.iteritems(params):
if value is not None:
payload[param] = value
return payload
def _build_list(option_value, item_kind):
'''
pass in an option to check for a list of items, create a list of dictionary of items to set
for this option
'''
#specify profiles if provided
if option_value is not None:
items = []
#if user specified none, return an empty list
if option_value == 'none':
return items
#was a list already passed in?
if not isinstance(option_value, list):
values = option_value.split(',')
else:
values = option_value
for value in values:
# sometimes the bigip just likes a plain ol list of items
if item_kind is None:
items.append(value)
# other times it's picky and likes key value pairs...
else:
items.append({'kind': item_kind, 'name': value})
return items
return None
def _determine_toggles(payload, toggles):
'''
BigIP can't make up its mind if it likes yes / no or true or false.
Figure out what it likes to hear without confusing the user.
'''
for toggle, definition in six.iteritems(toggles):
#did the user specify anything?
if definition['value'] is not None:
#test for yes_no toggle
if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no':
payload[toggle] = 'yes'
elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no':
payload[toggle] = 'no'
#test for true_false toggle
if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false':
payload[toggle] = True
elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false':
payload[toggle] = False
return payload
def _set_value(value):
'''
A function to detect if user is trying to pass a dictionary or list. parse it and return a
dictionary list or a string
'''
#don't continue if already an acceptable data-type
if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list):
return value
#check if json
if value.startswith('j{') and value.endswith('}j'):
value = value.replace('j{', '{')
value = value.replace('}j', '}')
try:
return salt.utils.json.loads(value)
except Exception:
raise salt.exceptions.CommandExecutionError
#detect list of dictionaries
if '|' in value and r'\|' not in value:
values = value.split('|')
items = []
for value in values:
items.append(_set_value(value))
return items
#parse out dictionary if detected
if ':' in value and r'\:' not in value:
options = {}
#split out pairs
key_pairs = value.split(',')
for key_pair in key_pairs:
k = key_pair.split(':')[0]
v = key_pair.split(':')[1]
options[k] = v
return options
#try making a list
elif ',' in value and r'\,' not in value:
value_items = value.split(',')
return value_items
#just return a string
else:
#remove escape chars if added
if r'\|' in value:
value = value.replace(r'\|', '|')
if r'\:' in value:
value = value.replace(r'\:', ':')
if r'\,' in value:
value = value.replace(r'\,', ',')
return value
def start_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and start a new transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
The name / alias for this transaction. The actual transaction
id will be stored within a grain called ``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.start_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
payload = {}
#post to REST to get trans id
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/transaction',
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
#extract the trans_id
data = _load_response(response)
if data['code'] == 200:
trans_id = data['content']['transId']
__salt__['grains.setval']('bigip_f5_trans', {label: trans_id})
return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id,
label=label)
else:
return data
def list_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and list an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
the label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.list_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
#post to REST to get trans id
try:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id))
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def commit_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and commit an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
the label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.commit_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
payload = {}
payload['state'] = 'VALIDATING'
#patch to REST to get trans id
try:
response = bigip_session.patch(
BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id),
data=salt.utils.json.dumps(payload)
)
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def delete_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and delete an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
The label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.delete_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
#patch to REST to get trans id
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id))
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def list_node(hostname, username, password, name=None, trans_label=None):
'''
A function to connect to a bigip device and list all nodes or a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list. If no name is specified than all nodes
will be listed.
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.list_node bigip admin admin my-node
'''
#build sessions
bigip_session = _build_session(username, password, trans_label)
#get to REST
try:
if name:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_node(hostname, username, password, name, address, trans_label=None):
'''
A function to connect to a bigip device and create a node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node
address
The address of the node
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.create_node bigip admin admin 10.1.1.2
'''
#build session
bigip_session = _build_session(username, password, trans_label)
#construct the payload
payload = {}
payload['name'] = name
payload['address'] = address
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node',
data=salt.utils.json.dumps(payload))
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
state=None,
trans_label=None):
'''
A function to connect to a bigip device and modify an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
state
[user-down | user-up ]
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled
'''
params = {
'connection-limit': connection_limit,
'description': description,
'dynamic-ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate-limit': rate_limit,
'ratio': ratio,
'session': session,
'state': state,
}
#build session
bigip_session = _build_session(username, password, trans_label)
#build payload
payload = _loop_payload(params)
payload['name'] = name
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_node(hostname, username, password, name, trans_label=None):
'''
A function to connect to a bigip device and delete a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.delete_node bigip admin admin my-node
'''
#build session
bigip_session = _build_session(username, password, trans_label)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(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_pool(hostname, username, password, name=None):
'''
A function to connect to a bigip device and list all pools or a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list. If no name is specified then all pools
will be listed.
CLI Example::
salt '*' bigip.list_pool bigip admin admin my-pool
'''
#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/pool/{name}/?expandSubcollections=true'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
A function to connect to a bigip device and create a pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create.
members
List of comma delimited pool members to add to the pool.
i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
CLI Example::
salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http
'''
params = {
'description': description,
'gateway-failsafe-device': gateway_failsafe_device,
'ignore-persisted-weight': ignore_persisted_weight,
'ip-tos-to-client': ip_tos_to_client,
'ip-tos-to-server': ip_tos_to_server,
'link-qos-to-client': link_qos_to_client,
'link-qos-to-server': link_qos_to_server,
'load-balancing-mode': load_balancing_mode,
'min-active-members': min_active_members,
'min-up-members': min_up_members,
'min-up-members-action': min_up_members_action,
'min-up-members-checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue-on-connection-limit': queue_on_connection_limit,
'queue-depth-limit': queue_depth_limit,
'queue-time-limit': queue_time_limit,
'reselect-tries': reselect_tries,
'service-down-action': service_down_action,
'slow-ramp-time': slow_ramp_time
}
# some options take yes no others take true false. Figure out when to use which without
# confusing the end user
toggles = {
'allow-nat': {'type': 'yes_no', 'value': allow_nat},
'allow-snat': {'type': 'yes_no', 'value': allow_snat}
}
#build payload
payload = _loop_payload(params)
payload['name'] = name
#determine toggles
payload = _determine_toggles(payload, toggles)
#specify members if provided
if members is not None:
payload['members'] = _build_list(members, 'ltm:pool:members')
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool',
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
A function to connect to a bigip device and modify an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify.
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[yes | no]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_on_connection_limit
[enabled | disabled]
queue_depth_limit
[integer]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
CLI Example::
salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1
'''
params = {
'description': description,
'gateway-failsafe-device': gateway_failsafe_device,
'ignore-persisted-weight': ignore_persisted_weight,
'ip-tos-to-client': ip_tos_to_client,
'ip-tos-to-server': ip_tos_to_server,
'link-qos-to-client': link_qos_to_client,
'link-qos-to-server': link_qos_to_server,
'load-balancing-mode': load_balancing_mode,
'min-active-members': min_active_members,
'min-up-members': min_up_members,
'min-up_members-action': min_up_members_action,
'min-up-members-checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue-on-connection-limit': queue_on_connection_limit,
'queue-depth-limit': queue_depth_limit,
'queue-time-limit': queue_time_limit,
'reselect-tries': reselect_tries,
'service-down-action': service_down_action,
'slow-ramp-time': slow_ramp_time
}
# some options take yes no others take true false. Figure out when to use which without
# confusing the end user
toggles = {
'allow-nat': {'type': 'yes_no', 'value': allow_nat},
'allow-snat': {'type': 'yes_no', 'value': allow_snat}
}
#build payload
payload = _loop_payload(params)
payload['name'] = name
#determine toggles
payload = _determine_toggles(payload, toggles)
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and delete a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
CLI Example::
salt '*' bigip.delete_node bigip admin admin my-pool
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(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 replace_pool_members(hostname, username, password, name, members):
'''
A function to connect to a bigip device and replace members of an existing pool with new members.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
List of comma delimited pool members to replace existing members with.
i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80
CLI Example::
salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80
'''
payload = {}
payload['name'] = name
#specify members if provided
if members is not None:
if isinstance(members, six.string_types):
members = members.split(',')
pool_members = []
for member in members:
#check to see if already a dictionary ( for states)
if isinstance(member, dict):
#check for state alternative name 'member_state', replace with state
if 'member_state' in member.keys():
member['state'] = member.pop('member_state')
#replace underscore with dash
for key in member:
new_key = key.replace('_', '-')
member[new_key] = member.pop(key)
pool_members.append(member)
#parse string passed via execution command (for executions)
else:
pool_members.append({'name': member, 'address': member.split(':')[0]})
payload['members'] = pool_members
#build session
bigip_session = _build_session(username, password)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the member to add
i.e. 10.1.1.2:80
CLI Example:
.. code-block:: bash
salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80
'''
# for states
if isinstance(member, dict):
#check for state alternative name 'member_state', replace with state
if 'member_state' in member.keys():
member['state'] = member.pop('member_state')
#replace underscore with dash
for key in member:
new_key = key.replace('_', '-')
member[new_key] = member.pop(key)
payload = member
# for execution
else:
payload = {'name': member, 'address': member.split(':')[0]}
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
state=None):
'''
A function to connect to a bigip device and modify an existing member of a pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the member to modify i.e. 10.1.1.2:80
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
state
[ user-up | user-down ]
CLI Example::
salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled
'''
params = {
'connection-limit': connection_limit,
'description': description,
'dynamic-ratio': dynamic_ratio,
'inherit-profile': inherit_profile,
'logging': logging,
'monitor': monitor,
'priority-group': priority_group,
'profiles': profiles,
'rate-limit': rate_limit,
'ratio': ratio,
'session': session,
'state': state
}
#build session
bigip_session = _build_session(username, password)
#build payload
payload = _loop_payload(params)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and delete a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the pool member to delete
CLI Example::
salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member))
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_virtual(hostname, username, password, name=None):
'''
A function to connect to a bigip device and list all virtuals or a specific virtual.
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 list. If no name is specified than all
virtuals will be listed.
CLI Example::
salt '*' bigip.list_virtual bigip admin admin my-virtual
'''
#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/virtual/{name}/?expandSubcollections=true'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_virtual(hostname, username, password, name,
destination=None,
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):
'''
A function to connect to a bigip device and modify an existing 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 modify
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_limitr_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 | disable]
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 Example::
salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none
salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule
'''
params = {
'destination': destination,
'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
#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:
if 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 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)
#determine state
if state is not None:
if state == 'enabled':
payload['enabled'] = True
elif state == 'disabled':
payload['disabled'] = True
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_virtual(hostname, username, password, name):
'''
A function to connect to a bigip device and delete a specific virtual.
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 delete
CLI Example::
salt '*' bigip.delete_virtual bigip admin admin my-virtual
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(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_monitor(hostname, username, password, monitor_type, name=None, ):
'''
A function to connect to a bigip device and list an existing monitor. If no name is provided than all
monitors 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
monitor_type
The type of monitor(s) to list
name
The name of the monitor to list
CLI Example::
salt '*' bigip.list_monitor bigip admin admin http my-http-monitor
'''
#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/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type))
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
CLI Example::
salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5
'''
#build session
bigip_session = _build_session(username, password)
#construct the payload
payload = {}
payload['name'] = name
#there's a ton of different monitors and a ton of options for each type of monitor.
#this logic relies that the end user knows which options are meant for which monitor types
for key, value in six.iteritems(kwargs):
if not key.startswith('__'):
if key not in ['hostname', 'username', 'password', 'type']:
key = key.replace('_', '-')
payload[key] = value
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and modify an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to modify
name
The name of the monitor to modify
kwargs
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
CLI Example::
salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6
'''
#build session
bigip_session = _build_session(username, password)
#construct the payload
payload = {}
#there's a ton of different monitors and a ton of options for each type of monitor.
#this logic relies that the end user knows which options are meant for which monitor types
for key, value in six.iteritems(kwargs):
if not key.startswith('__'):
if key not in ['hostname', 'username', 'password', 'type', 'name']:
key = key.replace('_', '-')
payload[key] = value
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_monitor(hostname, username, password, monitor_type, name):
'''
A function to connect to a bigip device and delete an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to delete
name
The name of the monitor to delete
CLI Example::
salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor
'''
#build sessions
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_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_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 modify_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
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.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http'
salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \
enforcement=maxHeaderCount:3200,maxRequests:10
salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \
ciphers='DEFAULT\:!SSLv3'
cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'
'''
#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)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name),
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)
|
saltstack/salt
|
salt/modules/bigip.py
|
list_profile
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L2004-L2038
|
[
"def _build_session(username, password, trans_label=None):\n '''\n Create a session to be used when connecting to iControl REST.\n '''\n\n bigip = requests.session()\n bigip.auth = (username, password)\n bigip.verify = False\n bigip.headers.update({'Content-Type': 'application/json'})\n\n if trans_label:\n #pull the trans id from the grain\n trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))\n\n if trans_id:\n bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})\n else:\n bigip.headers.update({'X-F5-REST-Coordination-Id': None})\n\n return bigip\n",
"def _load_response(response):\n '''\n Load the response from json data, return the dictionary or raw text\n '''\n\n try:\n data = salt.utils.json.loads(response.text)\n except ValueError:\n data = response.text\n\n ret = {'code': response.status_code, 'content': data}\n\n return ret\n",
"def _load_connection_error(hostname, error):\n '''\n Format and Return a connection error\n '''\n\n ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
An execution module which can manipulate an f5 bigip via iControl REST
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.json
# Import third party libs
try:
import requests
import requests.exceptions
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
# Import 3rd-party libs
from salt.ext import six
# Import salt libs
import salt.exceptions
# Define the module's virtual name
__virtualname__ = 'bigip'
def __virtual__():
'''
Only return if requests is installed
'''
if HAS_LIBS:
return __virtualname__
return (False, 'The bigip execution module cannot be loaded: '
'python requests library not available.')
BIG_IP_URL_BASE = 'https://{host}/mgmt/tm'
def _build_session(username, password, trans_label=None):
'''
Create a session to be used when connecting to iControl REST.
'''
bigip = requests.session()
bigip.auth = (username, password)
bigip.verify = False
bigip.headers.update({'Content-Type': 'application/json'})
if trans_label:
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))
if trans_id:
bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})
else:
bigip.headers.update({'X-F5-REST-Coordination-Id': None})
return bigip
def _load_response(response):
'''
Load the response from json data, return the dictionary or raw text
'''
try:
data = salt.utils.json.loads(response.text)
except ValueError:
data = response.text
ret = {'code': response.status_code, 'content': data}
return ret
def _load_connection_error(hostname, error):
'''
Format and Return a connection error
'''
ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)}
return ret
def _loop_payload(params):
'''
Pass in a dictionary of parameters, loop through them and build a payload containing,
parameters who's values are not None.
'''
#construct the payload
payload = {}
#set the payload
for param, value in six.iteritems(params):
if value is not None:
payload[param] = value
return payload
def _build_list(option_value, item_kind):
'''
pass in an option to check for a list of items, create a list of dictionary of items to set
for this option
'''
#specify profiles if provided
if option_value is not None:
items = []
#if user specified none, return an empty list
if option_value == 'none':
return items
#was a list already passed in?
if not isinstance(option_value, list):
values = option_value.split(',')
else:
values = option_value
for value in values:
# sometimes the bigip just likes a plain ol list of items
if item_kind is None:
items.append(value)
# other times it's picky and likes key value pairs...
else:
items.append({'kind': item_kind, 'name': value})
return items
return None
def _determine_toggles(payload, toggles):
'''
BigIP can't make up its mind if it likes yes / no or true or false.
Figure out what it likes to hear without confusing the user.
'''
for toggle, definition in six.iteritems(toggles):
#did the user specify anything?
if definition['value'] is not None:
#test for yes_no toggle
if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no':
payload[toggle] = 'yes'
elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no':
payload[toggle] = 'no'
#test for true_false toggle
if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false':
payload[toggle] = True
elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false':
payload[toggle] = False
return payload
def _set_value(value):
'''
A function to detect if user is trying to pass a dictionary or list. parse it and return a
dictionary list or a string
'''
#don't continue if already an acceptable data-type
if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list):
return value
#check if json
if value.startswith('j{') and value.endswith('}j'):
value = value.replace('j{', '{')
value = value.replace('}j', '}')
try:
return salt.utils.json.loads(value)
except Exception:
raise salt.exceptions.CommandExecutionError
#detect list of dictionaries
if '|' in value and r'\|' not in value:
values = value.split('|')
items = []
for value in values:
items.append(_set_value(value))
return items
#parse out dictionary if detected
if ':' in value and r'\:' not in value:
options = {}
#split out pairs
key_pairs = value.split(',')
for key_pair in key_pairs:
k = key_pair.split(':')[0]
v = key_pair.split(':')[1]
options[k] = v
return options
#try making a list
elif ',' in value and r'\,' not in value:
value_items = value.split(',')
return value_items
#just return a string
else:
#remove escape chars if added
if r'\|' in value:
value = value.replace(r'\|', '|')
if r'\:' in value:
value = value.replace(r'\:', ':')
if r'\,' in value:
value = value.replace(r'\,', ',')
return value
def start_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and start a new transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
The name / alias for this transaction. The actual transaction
id will be stored within a grain called ``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.start_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
payload = {}
#post to REST to get trans id
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/transaction',
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
#extract the trans_id
data = _load_response(response)
if data['code'] == 200:
trans_id = data['content']['transId']
__salt__['grains.setval']('bigip_f5_trans', {label: trans_id})
return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id,
label=label)
else:
return data
def list_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and list an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
the label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.list_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
#post to REST to get trans id
try:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id))
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def commit_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and commit an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
the label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.commit_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
payload = {}
payload['state'] = 'VALIDATING'
#patch to REST to get trans id
try:
response = bigip_session.patch(
BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id),
data=salt.utils.json.dumps(payload)
)
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def delete_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and delete an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
The label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.delete_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
#patch to REST to get trans id
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id))
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def list_node(hostname, username, password, name=None, trans_label=None):
'''
A function to connect to a bigip device and list all nodes or a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list. If no name is specified than all nodes
will be listed.
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.list_node bigip admin admin my-node
'''
#build sessions
bigip_session = _build_session(username, password, trans_label)
#get to REST
try:
if name:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_node(hostname, username, password, name, address, trans_label=None):
'''
A function to connect to a bigip device and create a node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node
address
The address of the node
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.create_node bigip admin admin 10.1.1.2
'''
#build session
bigip_session = _build_session(username, password, trans_label)
#construct the payload
payload = {}
payload['name'] = name
payload['address'] = address
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node',
data=salt.utils.json.dumps(payload))
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
state=None,
trans_label=None):
'''
A function to connect to a bigip device and modify an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
state
[user-down | user-up ]
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled
'''
params = {
'connection-limit': connection_limit,
'description': description,
'dynamic-ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate-limit': rate_limit,
'ratio': ratio,
'session': session,
'state': state,
}
#build session
bigip_session = _build_session(username, password, trans_label)
#build payload
payload = _loop_payload(params)
payload['name'] = name
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_node(hostname, username, password, name, trans_label=None):
'''
A function to connect to a bigip device and delete a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.delete_node bigip admin admin my-node
'''
#build session
bigip_session = _build_session(username, password, trans_label)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(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_pool(hostname, username, password, name=None):
'''
A function to connect to a bigip device and list all pools or a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list. If no name is specified then all pools
will be listed.
CLI Example::
salt '*' bigip.list_pool bigip admin admin my-pool
'''
#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/pool/{name}/?expandSubcollections=true'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
A function to connect to a bigip device and create a pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create.
members
List of comma delimited pool members to add to the pool.
i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
CLI Example::
salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http
'''
params = {
'description': description,
'gateway-failsafe-device': gateway_failsafe_device,
'ignore-persisted-weight': ignore_persisted_weight,
'ip-tos-to-client': ip_tos_to_client,
'ip-tos-to-server': ip_tos_to_server,
'link-qos-to-client': link_qos_to_client,
'link-qos-to-server': link_qos_to_server,
'load-balancing-mode': load_balancing_mode,
'min-active-members': min_active_members,
'min-up-members': min_up_members,
'min-up-members-action': min_up_members_action,
'min-up-members-checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue-on-connection-limit': queue_on_connection_limit,
'queue-depth-limit': queue_depth_limit,
'queue-time-limit': queue_time_limit,
'reselect-tries': reselect_tries,
'service-down-action': service_down_action,
'slow-ramp-time': slow_ramp_time
}
# some options take yes no others take true false. Figure out when to use which without
# confusing the end user
toggles = {
'allow-nat': {'type': 'yes_no', 'value': allow_nat},
'allow-snat': {'type': 'yes_no', 'value': allow_snat}
}
#build payload
payload = _loop_payload(params)
payload['name'] = name
#determine toggles
payload = _determine_toggles(payload, toggles)
#specify members if provided
if members is not None:
payload['members'] = _build_list(members, 'ltm:pool:members')
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool',
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
A function to connect to a bigip device and modify an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify.
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[yes | no]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_on_connection_limit
[enabled | disabled]
queue_depth_limit
[integer]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
CLI Example::
salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1
'''
params = {
'description': description,
'gateway-failsafe-device': gateway_failsafe_device,
'ignore-persisted-weight': ignore_persisted_weight,
'ip-tos-to-client': ip_tos_to_client,
'ip-tos-to-server': ip_tos_to_server,
'link-qos-to-client': link_qos_to_client,
'link-qos-to-server': link_qos_to_server,
'load-balancing-mode': load_balancing_mode,
'min-active-members': min_active_members,
'min-up-members': min_up_members,
'min-up_members-action': min_up_members_action,
'min-up-members-checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue-on-connection-limit': queue_on_connection_limit,
'queue-depth-limit': queue_depth_limit,
'queue-time-limit': queue_time_limit,
'reselect-tries': reselect_tries,
'service-down-action': service_down_action,
'slow-ramp-time': slow_ramp_time
}
# some options take yes no others take true false. Figure out when to use which without
# confusing the end user
toggles = {
'allow-nat': {'type': 'yes_no', 'value': allow_nat},
'allow-snat': {'type': 'yes_no', 'value': allow_snat}
}
#build payload
payload = _loop_payload(params)
payload['name'] = name
#determine toggles
payload = _determine_toggles(payload, toggles)
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and delete a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
CLI Example::
salt '*' bigip.delete_node bigip admin admin my-pool
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(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 replace_pool_members(hostname, username, password, name, members):
'''
A function to connect to a bigip device and replace members of an existing pool with new members.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
List of comma delimited pool members to replace existing members with.
i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80
CLI Example::
salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80
'''
payload = {}
payload['name'] = name
#specify members if provided
if members is not None:
if isinstance(members, six.string_types):
members = members.split(',')
pool_members = []
for member in members:
#check to see if already a dictionary ( for states)
if isinstance(member, dict):
#check for state alternative name 'member_state', replace with state
if 'member_state' in member.keys():
member['state'] = member.pop('member_state')
#replace underscore with dash
for key in member:
new_key = key.replace('_', '-')
member[new_key] = member.pop(key)
pool_members.append(member)
#parse string passed via execution command (for executions)
else:
pool_members.append({'name': member, 'address': member.split(':')[0]})
payload['members'] = pool_members
#build session
bigip_session = _build_session(username, password)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the member to add
i.e. 10.1.1.2:80
CLI Example:
.. code-block:: bash
salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80
'''
# for states
if isinstance(member, dict):
#check for state alternative name 'member_state', replace with state
if 'member_state' in member.keys():
member['state'] = member.pop('member_state')
#replace underscore with dash
for key in member:
new_key = key.replace('_', '-')
member[new_key] = member.pop(key)
payload = member
# for execution
else:
payload = {'name': member, 'address': member.split(':')[0]}
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
state=None):
'''
A function to connect to a bigip device and modify an existing member of a pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the member to modify i.e. 10.1.1.2:80
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
state
[ user-up | user-down ]
CLI Example::
salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled
'''
params = {
'connection-limit': connection_limit,
'description': description,
'dynamic-ratio': dynamic_ratio,
'inherit-profile': inherit_profile,
'logging': logging,
'monitor': monitor,
'priority-group': priority_group,
'profiles': profiles,
'rate-limit': rate_limit,
'ratio': ratio,
'session': session,
'state': state
}
#build session
bigip_session = _build_session(username, password)
#build payload
payload = _loop_payload(params)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and delete a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the pool member to delete
CLI Example::
salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member))
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_virtual(hostname, username, password, name=None):
'''
A function to connect to a bigip device and list all virtuals or a specific virtual.
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 list. If no name is specified than all
virtuals will be listed.
CLI Example::
salt '*' bigip.list_virtual bigip admin admin my-virtual
'''
#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/virtual/{name}/?expandSubcollections=true'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
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 modify_virtual(hostname, username, password, name,
destination=None,
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):
'''
A function to connect to a bigip device and modify an existing 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 modify
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_limitr_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 | disable]
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 Example::
salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none
salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule
'''
params = {
'destination': destination,
'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
#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:
if 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 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)
#determine state
if state is not None:
if state == 'enabled':
payload['enabled'] = True
elif state == 'disabled':
payload['disabled'] = True
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_virtual(hostname, username, password, name):
'''
A function to connect to a bigip device and delete a specific virtual.
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 delete
CLI Example::
salt '*' bigip.delete_virtual bigip admin admin my-virtual
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(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_monitor(hostname, username, password, monitor_type, name=None, ):
'''
A function to connect to a bigip device and list an existing monitor. If no name is provided than all
monitors 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
monitor_type
The type of monitor(s) to list
name
The name of the monitor to list
CLI Example::
salt '*' bigip.list_monitor bigip admin admin http my-http-monitor
'''
#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/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type))
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
CLI Example::
salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5
'''
#build session
bigip_session = _build_session(username, password)
#construct the payload
payload = {}
payload['name'] = name
#there's a ton of different monitors and a ton of options for each type of monitor.
#this logic relies that the end user knows which options are meant for which monitor types
for key, value in six.iteritems(kwargs):
if not key.startswith('__'):
if key not in ['hostname', 'username', 'password', 'type']:
key = key.replace('_', '-')
payload[key] = value
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and modify an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to modify
name
The name of the monitor to modify
kwargs
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
CLI Example::
salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6
'''
#build session
bigip_session = _build_session(username, password)
#construct the payload
payload = {}
#there's a ton of different monitors and a ton of options for each type of monitor.
#this logic relies that the end user knows which options are meant for which monitor types
for key, value in six.iteritems(kwargs):
if not key.startswith('__'):
if key not in ['hostname', 'username', 'password', 'type', 'name']:
key = key.replace('_', '-')
payload[key] = value
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_monitor(hostname, username, password, monitor_type, name):
'''
A function to connect to a bigip device and delete an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to delete
name
The name of the monitor to delete
CLI Example::
salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor
'''
#build sessions
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_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 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 modify_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
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.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http'
salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \
enforcement=maxHeaderCount:3200,maxRequests:10
salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \
ciphers='DEFAULT\:!SSLv3'
cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'
'''
#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)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name),
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)
|
saltstack/salt
|
salt/modules/bigip.py
|
create_profile
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L2041-L2119
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n",
"def _build_session(username, password, trans_label=None):\n '''\n Create a session to be used when connecting to iControl REST.\n '''\n\n bigip = requests.session()\n bigip.auth = (username, password)\n bigip.verify = False\n bigip.headers.update({'Content-Type': 'application/json'})\n\n if trans_label:\n #pull the trans id from the grain\n trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))\n\n if trans_id:\n bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})\n else:\n bigip.headers.update({'X-F5-REST-Coordination-Id': None})\n\n return bigip\n",
"def _load_response(response):\n '''\n Load the response from json data, return the dictionary or raw text\n '''\n\n try:\n data = salt.utils.json.loads(response.text)\n except ValueError:\n data = response.text\n\n ret = {'code': response.status_code, 'content': data}\n\n return ret\n",
"def _load_connection_error(hostname, error):\n '''\n Format and Return a connection error\n '''\n\n ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n\n return ret\n",
"def _set_value(value):\n '''\n A function to detect if user is trying to pass a dictionary or list. parse it and return a\n dictionary list or a string\n '''\n #don't continue if already an acceptable data-type\n if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list):\n return value\n\n #check if json\n if value.startswith('j{') and value.endswith('}j'):\n\n value = value.replace('j{', '{')\n value = value.replace('}j', '}')\n\n try:\n return salt.utils.json.loads(value)\n except Exception:\n raise salt.exceptions.CommandExecutionError\n\n #detect list of dictionaries\n if '|' in value and r'\\|' not in value:\n values = value.split('|')\n items = []\n for value in values:\n items.append(_set_value(value))\n return items\n\n #parse out dictionary if detected\n if ':' in value and r'\\:' not in value:\n options = {}\n #split out pairs\n key_pairs = value.split(',')\n for key_pair in key_pairs:\n k = key_pair.split(':')[0]\n v = key_pair.split(':')[1]\n options[k] = v\n return options\n\n #try making a list\n elif ',' in value and r'\\,' not in value:\n value_items = value.split(',')\n return value_items\n\n #just return a string\n else:\n\n #remove escape chars if added\n if r'\\|' in value:\n value = value.replace(r'\\|', '|')\n\n if r'\\:' in value:\n value = value.replace(r'\\:', ':')\n\n if r'\\,' in value:\n value = value.replace(r'\\,', ',')\n\n return value\n"
] |
# -*- coding: utf-8 -*-
'''
An execution module which can manipulate an f5 bigip via iControl REST
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.json
# Import third party libs
try:
import requests
import requests.exceptions
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
# Import 3rd-party libs
from salt.ext import six
# Import salt libs
import salt.exceptions
# Define the module's virtual name
__virtualname__ = 'bigip'
def __virtual__():
'''
Only return if requests is installed
'''
if HAS_LIBS:
return __virtualname__
return (False, 'The bigip execution module cannot be loaded: '
'python requests library not available.')
BIG_IP_URL_BASE = 'https://{host}/mgmt/tm'
def _build_session(username, password, trans_label=None):
'''
Create a session to be used when connecting to iControl REST.
'''
bigip = requests.session()
bigip.auth = (username, password)
bigip.verify = False
bigip.headers.update({'Content-Type': 'application/json'})
if trans_label:
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))
if trans_id:
bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})
else:
bigip.headers.update({'X-F5-REST-Coordination-Id': None})
return bigip
def _load_response(response):
'''
Load the response from json data, return the dictionary or raw text
'''
try:
data = salt.utils.json.loads(response.text)
except ValueError:
data = response.text
ret = {'code': response.status_code, 'content': data}
return ret
def _load_connection_error(hostname, error):
'''
Format and Return a connection error
'''
ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)}
return ret
def _loop_payload(params):
'''
Pass in a dictionary of parameters, loop through them and build a payload containing,
parameters who's values are not None.
'''
#construct the payload
payload = {}
#set the payload
for param, value in six.iteritems(params):
if value is not None:
payload[param] = value
return payload
def _build_list(option_value, item_kind):
'''
pass in an option to check for a list of items, create a list of dictionary of items to set
for this option
'''
#specify profiles if provided
if option_value is not None:
items = []
#if user specified none, return an empty list
if option_value == 'none':
return items
#was a list already passed in?
if not isinstance(option_value, list):
values = option_value.split(',')
else:
values = option_value
for value in values:
# sometimes the bigip just likes a plain ol list of items
if item_kind is None:
items.append(value)
# other times it's picky and likes key value pairs...
else:
items.append({'kind': item_kind, 'name': value})
return items
return None
def _determine_toggles(payload, toggles):
'''
BigIP can't make up its mind if it likes yes / no or true or false.
Figure out what it likes to hear without confusing the user.
'''
for toggle, definition in six.iteritems(toggles):
#did the user specify anything?
if definition['value'] is not None:
#test for yes_no toggle
if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no':
payload[toggle] = 'yes'
elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no':
payload[toggle] = 'no'
#test for true_false toggle
if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false':
payload[toggle] = True
elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false':
payload[toggle] = False
return payload
def _set_value(value):
'''
A function to detect if user is trying to pass a dictionary or list. parse it and return a
dictionary list or a string
'''
#don't continue if already an acceptable data-type
if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list):
return value
#check if json
if value.startswith('j{') and value.endswith('}j'):
value = value.replace('j{', '{')
value = value.replace('}j', '}')
try:
return salt.utils.json.loads(value)
except Exception:
raise salt.exceptions.CommandExecutionError
#detect list of dictionaries
if '|' in value and r'\|' not in value:
values = value.split('|')
items = []
for value in values:
items.append(_set_value(value))
return items
#parse out dictionary if detected
if ':' in value and r'\:' not in value:
options = {}
#split out pairs
key_pairs = value.split(',')
for key_pair in key_pairs:
k = key_pair.split(':')[0]
v = key_pair.split(':')[1]
options[k] = v
return options
#try making a list
elif ',' in value and r'\,' not in value:
value_items = value.split(',')
return value_items
#just return a string
else:
#remove escape chars if added
if r'\|' in value:
value = value.replace(r'\|', '|')
if r'\:' in value:
value = value.replace(r'\:', ':')
if r'\,' in value:
value = value.replace(r'\,', ',')
return value
def start_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and start a new transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
The name / alias for this transaction. The actual transaction
id will be stored within a grain called ``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.start_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
payload = {}
#post to REST to get trans id
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/transaction',
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
#extract the trans_id
data = _load_response(response)
if data['code'] == 200:
trans_id = data['content']['transId']
__salt__['grains.setval']('bigip_f5_trans', {label: trans_id})
return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id,
label=label)
else:
return data
def list_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and list an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
the label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.list_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
#post to REST to get trans id
try:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id))
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def commit_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and commit an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
the label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.commit_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
payload = {}
payload['state'] = 'VALIDATING'
#patch to REST to get trans id
try:
response = bigip_session.patch(
BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id),
data=salt.utils.json.dumps(payload)
)
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def delete_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and delete an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
The label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.delete_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
#patch to REST to get trans id
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id))
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def list_node(hostname, username, password, name=None, trans_label=None):
'''
A function to connect to a bigip device and list all nodes or a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list. If no name is specified than all nodes
will be listed.
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.list_node bigip admin admin my-node
'''
#build sessions
bigip_session = _build_session(username, password, trans_label)
#get to REST
try:
if name:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_node(hostname, username, password, name, address, trans_label=None):
'''
A function to connect to a bigip device and create a node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node
address
The address of the node
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.create_node bigip admin admin 10.1.1.2
'''
#build session
bigip_session = _build_session(username, password, trans_label)
#construct the payload
payload = {}
payload['name'] = name
payload['address'] = address
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node',
data=salt.utils.json.dumps(payload))
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
state=None,
trans_label=None):
'''
A function to connect to a bigip device and modify an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
state
[user-down | user-up ]
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled
'''
params = {
'connection-limit': connection_limit,
'description': description,
'dynamic-ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate-limit': rate_limit,
'ratio': ratio,
'session': session,
'state': state,
}
#build session
bigip_session = _build_session(username, password, trans_label)
#build payload
payload = _loop_payload(params)
payload['name'] = name
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_node(hostname, username, password, name, trans_label=None):
'''
A function to connect to a bigip device and delete a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.delete_node bigip admin admin my-node
'''
#build session
bigip_session = _build_session(username, password, trans_label)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(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_pool(hostname, username, password, name=None):
'''
A function to connect to a bigip device and list all pools or a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list. If no name is specified then all pools
will be listed.
CLI Example::
salt '*' bigip.list_pool bigip admin admin my-pool
'''
#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/pool/{name}/?expandSubcollections=true'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
A function to connect to a bigip device and create a pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create.
members
List of comma delimited pool members to add to the pool.
i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
CLI Example::
salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http
'''
params = {
'description': description,
'gateway-failsafe-device': gateway_failsafe_device,
'ignore-persisted-weight': ignore_persisted_weight,
'ip-tos-to-client': ip_tos_to_client,
'ip-tos-to-server': ip_tos_to_server,
'link-qos-to-client': link_qos_to_client,
'link-qos-to-server': link_qos_to_server,
'load-balancing-mode': load_balancing_mode,
'min-active-members': min_active_members,
'min-up-members': min_up_members,
'min-up-members-action': min_up_members_action,
'min-up-members-checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue-on-connection-limit': queue_on_connection_limit,
'queue-depth-limit': queue_depth_limit,
'queue-time-limit': queue_time_limit,
'reselect-tries': reselect_tries,
'service-down-action': service_down_action,
'slow-ramp-time': slow_ramp_time
}
# some options take yes no others take true false. Figure out when to use which without
# confusing the end user
toggles = {
'allow-nat': {'type': 'yes_no', 'value': allow_nat},
'allow-snat': {'type': 'yes_no', 'value': allow_snat}
}
#build payload
payload = _loop_payload(params)
payload['name'] = name
#determine toggles
payload = _determine_toggles(payload, toggles)
#specify members if provided
if members is not None:
payload['members'] = _build_list(members, 'ltm:pool:members')
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool',
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
A function to connect to a bigip device and modify an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify.
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[yes | no]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_on_connection_limit
[enabled | disabled]
queue_depth_limit
[integer]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
CLI Example::
salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1
'''
params = {
'description': description,
'gateway-failsafe-device': gateway_failsafe_device,
'ignore-persisted-weight': ignore_persisted_weight,
'ip-tos-to-client': ip_tos_to_client,
'ip-tos-to-server': ip_tos_to_server,
'link-qos-to-client': link_qos_to_client,
'link-qos-to-server': link_qos_to_server,
'load-balancing-mode': load_balancing_mode,
'min-active-members': min_active_members,
'min-up-members': min_up_members,
'min-up_members-action': min_up_members_action,
'min-up-members-checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue-on-connection-limit': queue_on_connection_limit,
'queue-depth-limit': queue_depth_limit,
'queue-time-limit': queue_time_limit,
'reselect-tries': reselect_tries,
'service-down-action': service_down_action,
'slow-ramp-time': slow_ramp_time
}
# some options take yes no others take true false. Figure out when to use which without
# confusing the end user
toggles = {
'allow-nat': {'type': 'yes_no', 'value': allow_nat},
'allow-snat': {'type': 'yes_no', 'value': allow_snat}
}
#build payload
payload = _loop_payload(params)
payload['name'] = name
#determine toggles
payload = _determine_toggles(payload, toggles)
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and delete a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
CLI Example::
salt '*' bigip.delete_node bigip admin admin my-pool
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(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 replace_pool_members(hostname, username, password, name, members):
'''
A function to connect to a bigip device and replace members of an existing pool with new members.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
List of comma delimited pool members to replace existing members with.
i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80
CLI Example::
salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80
'''
payload = {}
payload['name'] = name
#specify members if provided
if members is not None:
if isinstance(members, six.string_types):
members = members.split(',')
pool_members = []
for member in members:
#check to see if already a dictionary ( for states)
if isinstance(member, dict):
#check for state alternative name 'member_state', replace with state
if 'member_state' in member.keys():
member['state'] = member.pop('member_state')
#replace underscore with dash
for key in member:
new_key = key.replace('_', '-')
member[new_key] = member.pop(key)
pool_members.append(member)
#parse string passed via execution command (for executions)
else:
pool_members.append({'name': member, 'address': member.split(':')[0]})
payload['members'] = pool_members
#build session
bigip_session = _build_session(username, password)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the member to add
i.e. 10.1.1.2:80
CLI Example:
.. code-block:: bash
salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80
'''
# for states
if isinstance(member, dict):
#check for state alternative name 'member_state', replace with state
if 'member_state' in member.keys():
member['state'] = member.pop('member_state')
#replace underscore with dash
for key in member:
new_key = key.replace('_', '-')
member[new_key] = member.pop(key)
payload = member
# for execution
else:
payload = {'name': member, 'address': member.split(':')[0]}
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
state=None):
'''
A function to connect to a bigip device and modify an existing member of a pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the member to modify i.e. 10.1.1.2:80
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
state
[ user-up | user-down ]
CLI Example::
salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled
'''
params = {
'connection-limit': connection_limit,
'description': description,
'dynamic-ratio': dynamic_ratio,
'inherit-profile': inherit_profile,
'logging': logging,
'monitor': monitor,
'priority-group': priority_group,
'profiles': profiles,
'rate-limit': rate_limit,
'ratio': ratio,
'session': session,
'state': state
}
#build session
bigip_session = _build_session(username, password)
#build payload
payload = _loop_payload(params)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and delete a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the pool member to delete
CLI Example::
salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member))
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_virtual(hostname, username, password, name=None):
'''
A function to connect to a bigip device and list all virtuals or a specific virtual.
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 list. If no name is specified than all
virtuals will be listed.
CLI Example::
salt '*' bigip.list_virtual bigip admin admin my-virtual
'''
#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/virtual/{name}/?expandSubcollections=true'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
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 modify_virtual(hostname, username, password, name,
destination=None,
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):
'''
A function to connect to a bigip device and modify an existing 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 modify
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_limitr_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 | disable]
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 Example::
salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none
salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule
'''
params = {
'destination': destination,
'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
#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:
if 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 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)
#determine state
if state is not None:
if state == 'enabled':
payload['enabled'] = True
elif state == 'disabled':
payload['disabled'] = True
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_virtual(hostname, username, password, name):
'''
A function to connect to a bigip device and delete a specific virtual.
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 delete
CLI Example::
salt '*' bigip.delete_virtual bigip admin admin my-virtual
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(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_monitor(hostname, username, password, monitor_type, name=None, ):
'''
A function to connect to a bigip device and list an existing monitor. If no name is provided than all
monitors 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
monitor_type
The type of monitor(s) to list
name
The name of the monitor to list
CLI Example::
salt '*' bigip.list_monitor bigip admin admin http my-http-monitor
'''
#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/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type))
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
CLI Example::
salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5
'''
#build session
bigip_session = _build_session(username, password)
#construct the payload
payload = {}
payload['name'] = name
#there's a ton of different monitors and a ton of options for each type of monitor.
#this logic relies that the end user knows which options are meant for which monitor types
for key, value in six.iteritems(kwargs):
if not key.startswith('__'):
if key not in ['hostname', 'username', 'password', 'type']:
key = key.replace('_', '-')
payload[key] = value
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and modify an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to modify
name
The name of the monitor to modify
kwargs
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
CLI Example::
salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6
'''
#build session
bigip_session = _build_session(username, password)
#construct the payload
payload = {}
#there's a ton of different monitors and a ton of options for each type of monitor.
#this logic relies that the end user knows which options are meant for which monitor types
for key, value in six.iteritems(kwargs):
if not key.startswith('__'):
if key not in ['hostname', 'username', 'password', 'type', 'name']:
key = key.replace('_', '-')
payload[key] = value
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_monitor(hostname, username, password, monitor_type, name):
'''
A function to connect to a bigip device and delete an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to delete
name
The name of the monitor to delete
CLI Example::
salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor
'''
#build sessions
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_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_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 modify_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
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.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http'
salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \
enforcement=maxHeaderCount:3200,maxRequests:10
salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \
ciphers='DEFAULT\:!SSLv3'
cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'
'''
#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)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name),
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)
|
saltstack/salt
|
salt/modules/bigip.py
|
delete_profile
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L2210-L2243
|
[
"def _build_session(username, password, trans_label=None):\n '''\n Create a session to be used when connecting to iControl REST.\n '''\n\n bigip = requests.session()\n bigip.auth = (username, password)\n bigip.verify = False\n bigip.headers.update({'Content-Type': 'application/json'})\n\n if trans_label:\n #pull the trans id from the grain\n trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))\n\n if trans_id:\n bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})\n else:\n bigip.headers.update({'X-F5-REST-Coordination-Id': None})\n\n return bigip\n",
"def _load_response(response):\n '''\n Load the response from json data, return the dictionary or raw text\n '''\n\n try:\n data = salt.utils.json.loads(response.text)\n except ValueError:\n data = response.text\n\n ret = {'code': response.status_code, 'content': data}\n\n return ret\n",
"def _load_connection_error(hostname, error):\n '''\n Format and Return a connection error\n '''\n\n ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
An execution module which can manipulate an f5 bigip via iControl REST
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.json
# Import third party libs
try:
import requests
import requests.exceptions
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
# Import 3rd-party libs
from salt.ext import six
# Import salt libs
import salt.exceptions
# Define the module's virtual name
__virtualname__ = 'bigip'
def __virtual__():
'''
Only return if requests is installed
'''
if HAS_LIBS:
return __virtualname__
return (False, 'The bigip execution module cannot be loaded: '
'python requests library not available.')
BIG_IP_URL_BASE = 'https://{host}/mgmt/tm'
def _build_session(username, password, trans_label=None):
'''
Create a session to be used when connecting to iControl REST.
'''
bigip = requests.session()
bigip.auth = (username, password)
bigip.verify = False
bigip.headers.update({'Content-Type': 'application/json'})
if trans_label:
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))
if trans_id:
bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})
else:
bigip.headers.update({'X-F5-REST-Coordination-Id': None})
return bigip
def _load_response(response):
'''
Load the response from json data, return the dictionary or raw text
'''
try:
data = salt.utils.json.loads(response.text)
except ValueError:
data = response.text
ret = {'code': response.status_code, 'content': data}
return ret
def _load_connection_error(hostname, error):
'''
Format and Return a connection error
'''
ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)}
return ret
def _loop_payload(params):
'''
Pass in a dictionary of parameters, loop through them and build a payload containing,
parameters who's values are not None.
'''
#construct the payload
payload = {}
#set the payload
for param, value in six.iteritems(params):
if value is not None:
payload[param] = value
return payload
def _build_list(option_value, item_kind):
'''
pass in an option to check for a list of items, create a list of dictionary of items to set
for this option
'''
#specify profiles if provided
if option_value is not None:
items = []
#if user specified none, return an empty list
if option_value == 'none':
return items
#was a list already passed in?
if not isinstance(option_value, list):
values = option_value.split(',')
else:
values = option_value
for value in values:
# sometimes the bigip just likes a plain ol list of items
if item_kind is None:
items.append(value)
# other times it's picky and likes key value pairs...
else:
items.append({'kind': item_kind, 'name': value})
return items
return None
def _determine_toggles(payload, toggles):
'''
BigIP can't make up its mind if it likes yes / no or true or false.
Figure out what it likes to hear without confusing the user.
'''
for toggle, definition in six.iteritems(toggles):
#did the user specify anything?
if definition['value'] is not None:
#test for yes_no toggle
if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no':
payload[toggle] = 'yes'
elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no':
payload[toggle] = 'no'
#test for true_false toggle
if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false':
payload[toggle] = True
elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false':
payload[toggle] = False
return payload
def _set_value(value):
'''
A function to detect if user is trying to pass a dictionary or list. parse it and return a
dictionary list or a string
'''
#don't continue if already an acceptable data-type
if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list):
return value
#check if json
if value.startswith('j{') and value.endswith('}j'):
value = value.replace('j{', '{')
value = value.replace('}j', '}')
try:
return salt.utils.json.loads(value)
except Exception:
raise salt.exceptions.CommandExecutionError
#detect list of dictionaries
if '|' in value and r'\|' not in value:
values = value.split('|')
items = []
for value in values:
items.append(_set_value(value))
return items
#parse out dictionary if detected
if ':' in value and r'\:' not in value:
options = {}
#split out pairs
key_pairs = value.split(',')
for key_pair in key_pairs:
k = key_pair.split(':')[0]
v = key_pair.split(':')[1]
options[k] = v
return options
#try making a list
elif ',' in value and r'\,' not in value:
value_items = value.split(',')
return value_items
#just return a string
else:
#remove escape chars if added
if r'\|' in value:
value = value.replace(r'\|', '|')
if r'\:' in value:
value = value.replace(r'\:', ':')
if r'\,' in value:
value = value.replace(r'\,', ',')
return value
def start_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and start a new transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
The name / alias for this transaction. The actual transaction
id will be stored within a grain called ``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.start_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
payload = {}
#post to REST to get trans id
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/transaction',
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
#extract the trans_id
data = _load_response(response)
if data['code'] == 200:
trans_id = data['content']['transId']
__salt__['grains.setval']('bigip_f5_trans', {label: trans_id})
return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id,
label=label)
else:
return data
def list_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and list an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
the label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.list_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
#post to REST to get trans id
try:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id))
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def commit_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and commit an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
the label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.commit_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
payload = {}
payload['state'] = 'VALIDATING'
#patch to REST to get trans id
try:
response = bigip_session.patch(
BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id),
data=salt.utils.json.dumps(payload)
)
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def delete_transaction(hostname, username, password, label):
'''
A function to connect to a bigip device and delete an existing transaction.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
label
The label of this transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.delete_transaction bigip admin admin my_transaction
'''
#build the session
bigip_session = _build_session(username, password)
#pull the trans id from the grain
trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label))
if trans_id:
#patch to REST to get trans id
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id))
return _load_response(response)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
else:
return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \
' bigip.start_transaction function'
def list_node(hostname, username, password, name=None, trans_label=None):
'''
A function to connect to a bigip device and list all nodes or a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list. If no name is specified than all nodes
will be listed.
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.list_node bigip admin admin my-node
'''
#build sessions
bigip_session = _build_session(username, password, trans_label)
#get to REST
try:
if name:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_node(hostname, username, password, name, address, trans_label=None):
'''
A function to connect to a bigip device and create a node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node
address
The address of the node
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.create_node bigip admin admin 10.1.1.2
'''
#build session
bigip_session = _build_session(username, password, trans_label)
#construct the payload
payload = {}
payload['name'] = name
payload['address'] = address
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node',
data=salt.utils.json.dumps(payload))
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
state=None,
trans_label=None):
'''
A function to connect to a bigip device and modify an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
state
[user-down | user-up ]
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled
'''
params = {
'connection-limit': connection_limit,
'description': description,
'dynamic-ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate-limit': rate_limit,
'ratio': ratio,
'session': session,
'state': state,
}
#build session
bigip_session = _build_session(username, password, trans_label)
#build payload
payload = _loop_payload(params)
payload['name'] = name
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_node(hostname, username, password, name, trans_label=None):
'''
A function to connect to a bigip device and delete a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
trans_label
The label of the transaction stored within the grain:
``bigip_f5_trans:<label>``
CLI Example::
salt '*' bigip.delete_node bigip admin admin my-node
'''
#build session
bigip_session = _build_session(username, password, trans_label)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(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_pool(hostname, username, password, name=None):
'''
A function to connect to a bigip device and list all pools or a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list. If no name is specified then all pools
will be listed.
CLI Example::
salt '*' bigip.list_pool bigip admin admin my-pool
'''
#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/pool/{name}/?expandSubcollections=true'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
A function to connect to a bigip device and create a pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create.
members
List of comma delimited pool members to add to the pool.
i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
CLI Example::
salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http
'''
params = {
'description': description,
'gateway-failsafe-device': gateway_failsafe_device,
'ignore-persisted-weight': ignore_persisted_weight,
'ip-tos-to-client': ip_tos_to_client,
'ip-tos-to-server': ip_tos_to_server,
'link-qos-to-client': link_qos_to_client,
'link-qos-to-server': link_qos_to_server,
'load-balancing-mode': load_balancing_mode,
'min-active-members': min_active_members,
'min-up-members': min_up_members,
'min-up-members-action': min_up_members_action,
'min-up-members-checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue-on-connection-limit': queue_on_connection_limit,
'queue-depth-limit': queue_depth_limit,
'queue-time-limit': queue_time_limit,
'reselect-tries': reselect_tries,
'service-down-action': service_down_action,
'slow-ramp-time': slow_ramp_time
}
# some options take yes no others take true false. Figure out when to use which without
# confusing the end user
toggles = {
'allow-nat': {'type': 'yes_no', 'value': allow_nat},
'allow-snat': {'type': 'yes_no', 'value': allow_snat}
}
#build payload
payload = _loop_payload(params)
payload['name'] = name
#determine toggles
payload = _determine_toggles(payload, toggles)
#specify members if provided
if members is not None:
payload['members'] = _build_list(members, 'ltm:pool:members')
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool',
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
A function to connect to a bigip device and modify an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify.
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[yes | no]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_on_connection_limit
[enabled | disabled]
queue_depth_limit
[integer]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
CLI Example::
salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1
'''
params = {
'description': description,
'gateway-failsafe-device': gateway_failsafe_device,
'ignore-persisted-weight': ignore_persisted_weight,
'ip-tos-to-client': ip_tos_to_client,
'ip-tos-to-server': ip_tos_to_server,
'link-qos-to-client': link_qos_to_client,
'link-qos-to-server': link_qos_to_server,
'load-balancing-mode': load_balancing_mode,
'min-active-members': min_active_members,
'min-up-members': min_up_members,
'min-up_members-action': min_up_members_action,
'min-up-members-checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue-on-connection-limit': queue_on_connection_limit,
'queue-depth-limit': queue_depth_limit,
'queue-time-limit': queue_time_limit,
'reselect-tries': reselect_tries,
'service-down-action': service_down_action,
'slow-ramp-time': slow_ramp_time
}
# some options take yes no others take true false. Figure out when to use which without
# confusing the end user
toggles = {
'allow-nat': {'type': 'yes_no', 'value': allow_nat},
'allow-snat': {'type': 'yes_no', 'value': allow_snat}
}
#build payload
payload = _loop_payload(params)
payload['name'] = name
#determine toggles
payload = _determine_toggles(payload, toggles)
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and delete a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
CLI Example::
salt '*' bigip.delete_node bigip admin admin my-pool
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(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 replace_pool_members(hostname, username, password, name, members):
'''
A function to connect to a bigip device and replace members of an existing pool with new members.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
List of comma delimited pool members to replace existing members with.
i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80
CLI Example::
salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80
'''
payload = {}
payload['name'] = name
#specify members if provided
if members is not None:
if isinstance(members, six.string_types):
members = members.split(',')
pool_members = []
for member in members:
#check to see if already a dictionary ( for states)
if isinstance(member, dict):
#check for state alternative name 'member_state', replace with state
if 'member_state' in member.keys():
member['state'] = member.pop('member_state')
#replace underscore with dash
for key in member:
new_key = key.replace('_', '-')
member[new_key] = member.pop(key)
pool_members.append(member)
#parse string passed via execution command (for executions)
else:
pool_members.append({'name': member, 'address': member.split(':')[0]})
payload['members'] = pool_members
#build session
bigip_session = _build_session(username, password)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the member to add
i.e. 10.1.1.2:80
CLI Example:
.. code-block:: bash
salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80
'''
# for states
if isinstance(member, dict):
#check for state alternative name 'member_state', replace with state
if 'member_state' in member.keys():
member['state'] = member.pop('member_state')
#replace underscore with dash
for key in member:
new_key = key.replace('_', '-')
member[new_key] = member.pop(key)
payload = member
# for execution
else:
payload = {'name': member, 'address': member.split(':')[0]}
#build session
bigip_session = _build_session(username, password)
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
state=None):
'''
A function to connect to a bigip device and modify an existing member of a pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the member to modify i.e. 10.1.1.2:80
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
state
[ user-up | user-down ]
CLI Example::
salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled
'''
params = {
'connection-limit': connection_limit,
'description': description,
'dynamic-ratio': dynamic_ratio,
'inherit-profile': inherit_profile,
'logging': logging,
'monitor': monitor,
'priority-group': priority_group,
'profiles': profiles,
'rate-limit': rate_limit,
'ratio': ratio,
'session': session,
'state': state
}
#build session
bigip_session = _build_session(username, password)
#build payload
payload = _loop_payload(params)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and delete a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The name of the pool member to delete
CLI Example::
salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member))
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_virtual(hostname, username, password, name=None):
'''
A function to connect to a bigip device and list all virtuals or a specific virtual.
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 list. If no name is specified than all
virtuals will be listed.
CLI Example::
salt '*' bigip.list_virtual bigip admin admin my-virtual
'''
#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/virtual/{name}/?expandSubcollections=true'.format(name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual')
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
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 modify_virtual(hostname, username, password, name,
destination=None,
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):
'''
A function to connect to a bigip device and modify an existing 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 modify
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_limitr_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 | disable]
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 Example::
salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none
salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule
'''
params = {
'destination': destination,
'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
#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:
if 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 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)
#determine state
if state is not None:
if state == 'enabled':
payload['enabled'] = True
elif state == 'disabled':
payload['disabled'] = True
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_virtual(hostname, username, password, name):
'''
A function to connect to a bigip device and delete a specific virtual.
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 delete
CLI Example::
salt '*' bigip.delete_virtual bigip admin admin my-virtual
'''
#build session
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(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_monitor(hostname, username, password, monitor_type, name=None, ):
'''
A function to connect to a bigip device and list an existing monitor. If no name is provided than all
monitors 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
monitor_type
The type of monitor(s) to list
name
The name of the monitor to list
CLI Example::
salt '*' bigip.list_monitor bigip admin admin http my-http-monitor
'''
#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/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name))
else:
response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type))
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
CLI Example::
salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5
'''
#build session
bigip_session = _build_session(username, password)
#construct the payload
payload = {}
payload['name'] = name
#there's a ton of different monitors and a ton of options for each type of monitor.
#this logic relies that the end user knows which options are meant for which monitor types
for key, value in six.iteritems(kwargs):
if not key.startswith('__'):
if key not in ['hostname', 'username', 'password', 'type']:
key = key.replace('_', '-')
payload[key] = value
#post to REST
try:
response = bigip_session.post(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and modify an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to modify
name
The name of the monitor to modify
kwargs
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
CLI Example::
salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6
'''
#build session
bigip_session = _build_session(username, password)
#construct the payload
payload = {}
#there's a ton of different monitors and a ton of options for each type of monitor.
#this logic relies that the end user knows which options are meant for which monitor types
for key, value in six.iteritems(kwargs):
if not key.startswith('__'):
if key not in ['hostname', 'username', 'password', 'type', 'name']:
key = key.replace('_', '-')
payload[key] = value
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
def delete_monitor(hostname, username, password, monitor_type, name):
'''
A function to connect to a bigip device and delete an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to delete
name
The name of the monitor to delete
CLI Example::
salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor
'''
#build sessions
bigip_session = _build_session(username, password)
#delete to REST
try:
response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_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_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 modify_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
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.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http'
salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \
enforcement=maxHeaderCount:3200,maxRequests:10
salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \
ciphers='DEFAULT\:!SSLv3'
cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'
'''
#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)
#put to REST
try:
response = bigip_session.put(
BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name),
data=salt.utils.json.dumps(payload)
)
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
|
saltstack/salt
|
salt/modules/beacons.py
|
list_
|
python
|
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': {}}
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/beacons.py#L30-L89
|
[
"def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n",
"def safe_dump(data, stream=None, **kwargs):\n '''\n Use a custom dumper to ensure that defaultdict and OrderedDict are\n represented properly. Ensure that unicode strings are encoded unless\n explicitly told not to.\n '''\n if 'allow_unicode' not in kwargs:\n kwargs['allow_unicode'] = True\n return yaml.dump(data, stream, Dumper=SafeOrderedDumper, **kwargs)\n",
"def get_event(self,\n wait=5,\n tag='',\n full=False,\n match_type=None,\n no_block=False,\n auto_reconnect=False):\n '''\n Get a single publication.\n If no publication is available, then block for up to ``wait`` seconds.\n Return publication if it is available or ``None`` if no publication is\n available.\n\n If wait is 0, then block forever.\n\n tag\n Only return events matching the given tag. If not specified, or set\n to an empty string, all events are returned. It is recommended to\n always be selective on what is to be returned in the event that\n multiple requests are being multiplexed.\n\n match_type\n Set the function to match the search tag with event tags.\n - 'startswith' : search for event tags that start with tag\n - 'endswith' : search for event tags that end with tag\n - 'find' : search for event tags that contain tag\n - 'regex' : regex search '^' + tag event tags\n - 'fnmatch' : fnmatch tag event tags matching\n Default is opts['event_match_type'] or 'startswith'\n\n .. versionadded:: 2015.8.0\n\n no_block\n Define if getting the event should be a blocking call or not.\n Defaults to False to keep backwards compatibility.\n\n .. versionadded:: 2015.8.0\n\n Notes:\n\n Searches cached publications first. If no cached publications are found\n that match the given tag specification, new publications are received\n and checked.\n\n If a publication is received that does not match the tag specification,\n it is DISCARDED unless it is subscribed to via subscribe() which will\n cause it to be cached.\n\n If a caller is not going to call get_event immediately after sending a\n request, it MUST subscribe the result to ensure the response is not lost\n should other regions of code call get_event for other purposes.\n '''\n assert self._run_io_loop_sync\n\n match_func = self._get_match_func(match_type)\n\n ret = self._check_pending(tag, match_func)\n if ret is None:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n if auto_reconnect:\n raise_errors = self.raise_errors\n self.raise_errors = True\n while True:\n try:\n ret = self._get_event(wait, tag, match_func, no_block)\n break\n except tornado.iostream.StreamClosedError:\n self.close_pub()\n self.connect_pub(timeout=wait)\n continue\n self.raise_errors = raise_errors\n else:\n ret = self._get_event(wait, tag, match_func, no_block)\n\n if ret is None or full:\n return ret\n else:\n return ret['data']\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing the Salt beacons on a minion
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import os
# Import Salt libs
import salt.ext.six as six
import salt.utils.event
import salt.utils.files
import salt.utils.yaml
from salt.ext.six.moves import map
# Get logging started
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list',
'reload_': 'reload'
}
def list_available(return_yaml=True, **kwargs):
'''
List the beacons currently available on the minion.
Args:
return_yaml (bool):
Whether to return YAML formatted output, default ``True``.
returns:
list: List of currently available Beacons.
CLI Example:
.. code-block:: bash
salt '*' beacons.list_available
'''
beacons = None
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'list_available'},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_list_available_complete',
wait=kwargs.get('timeout', 30))
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_available '
'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 delete(name, **kwargs):
'''
Delete a beacon item.
Args:
name (str): Name of the beacon to delete.
Returns:
dict: Boolean and status message on success or failure of delete.
CLI Example:
.. code-block:: bash
salt '*' beacons.delete ps
salt '*' beacons.delete load
'''
ret = {'comment': 'Failed to delete beacon {0}.'.format(name),
'result': False}
if 'test' in kwargs and kwargs['test']:
ret['result'] = True
ret['comment'] = 'Beacon: {0} would be deleted.'.format(name)
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'name': name,
'func': 'delete'},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_delete_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if name not in beacons:
ret['result'] = True
ret['comment'] = 'Deleted beacon: {0}.'.format(name)
return ret
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))
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 delete 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(**kwargs):
'''
Enable all beacons on the minion.
Returns:
bool: Boolean and status message on success or failure of enable.
CLI Example:
.. code-block:: bash
salt '*' beacons.enable
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be enabled.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'enable'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_enabled_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if 'enabled' in beacons and beacons['enabled']:
ret['result'] = True
ret['comment'] = 'Enabled beacons on minion.'
else:
ret['result'] = False
ret['comment'] = 'Failed to enable beacons on minion.'
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. Beacons enable job ' \
'failed.'
return ret
def disable(**kwargs):
'''
Disable all beacons jobs on the minion.
Returns:
dict: Boolean and status message on success or failure of disable.
CLI Example:
.. code-block:: bash
salt '*' beacons.disable
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be disabled.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'disable'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_disabled_complete',
wait=kwargs.get('timeout', 30))
log.debug('event_ret %s', event_ret)
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if 'enabled' in beacons and not beacons['enabled']:
ret['result'] = True
ret['comment'] = 'Disabled beacons on minion.'
else:
ret['result'] = False
ret['comment'] = 'Failed to disable beacons on minion.'
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. Beacons disable ' \
'job failed.'
return ret
def _get_beacon_config_dict(beacon_config):
beacon_config_dict = {}
if isinstance(beacon_config, list):
list(map(beacon_config_dict.update, beacon_config))
else:
beacon_config_dict = beacon_config
return beacon_config_dict
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 disable_beacon(name, **kwargs):
'''
Disable a beacon on the minion.
Args:
name (str): Name of the beacon to disable.
Returns:
dict: Boolean and status message on success or failure of disable.
CLI Example:
.. code-block:: bash
salt '*' beacons.disable_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'] = 'Beacons would be disabled.'
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': 'disable_beacon',
'name': name},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_disabled_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 not beacon_config_dict['enabled']:
ret['result'] = True
ret['comment'] = 'Disabled beacon {0} on minion.' \
''.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to disable beacon on minion.'
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 disable job ' \
'failed.'
return ret
def reset(**kwargs):
'''
Reset the beacon configuration on the minion.
CLI Example:
.. code-block:: bash
salt '*' beacons.reset
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be reset.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'reset'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_reset_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
ret['result'] = True
ret['comment'] = 'Beacon configuration reset.'
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 reset job ' \
'failed.'
return ret
|
saltstack/salt
|
salt/modules/beacons.py
|
add
|
python
|
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
|
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'}}]"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/beacons.py#L141-L241
|
[
"def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n",
"def list_(return_yaml=True,\n include_pillar=True,\n include_opts=True,\n **kwargs):\n '''\n List the beacons currently configured on the minion.\n\n Args:\n\n return_yaml (bool):\n Whether to return YAML formatted output, default ``True``.\n\n include_pillar (bool):\n Whether to include beacons that are configured in pillar, default\n is ``True``.\n\n include_opts (bool):\n Whether to include beacons that are configured in opts, default is\n ``True``.\n\n Returns:\n list: List of currently configured Beacons.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' beacons.list\n\n '''\n beacons = None\n\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list',\n 'include_pillar': include_pillar,\n 'include_opts': include_opts},\n 'manage_beacons')\n if res:\n event_ret = eventer.get_event(\n tag='/salt/minion/minion_beacons_list_complete',\n wait=kwargs.get('timeout', 30))\n log.debug('event_ret %s', event_ret)\n if event_ret and event_ret['complete']:\n beacons = event_ret['beacons']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event\n # system\n ret = {'comment': 'Event module not available. Beacon list failed.',\n 'result': False}\n return ret\n\n if beacons:\n if return_yaml:\n tmp = {'beacons': beacons}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return beacons\n else:\n return {'beacons': {}}\n",
"def list_available(return_yaml=True, **kwargs):\n '''\n List the beacons currently available on the minion.\n\n Args:\n\n return_yaml (bool):\n Whether to return YAML formatted output, default ``True``.\n\n returns:\n list: List of currently available Beacons.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' beacons.list_available\n\n '''\n beacons = None\n\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list_available'},\n 'manage_beacons')\n if res:\n event_ret = eventer.get_event(\n tag='/salt/minion/minion_beacons_list_available_complete',\n wait=kwargs.get('timeout', 30))\n if event_ret and event_ret['complete']:\n beacons = event_ret['beacons']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event\n # system\n ret = {'comment': 'Event module not available. Beacon list_available '\n 'failed.',\n 'result': False}\n return ret\n\n if beacons:\n if return_yaml:\n tmp = {'beacons': beacons}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return beacons\n else:\n return {'beacons': {}}\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing the Salt beacons on a minion
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import os
# Import Salt libs
import salt.ext.six as six
import salt.utils.event
import salt.utils.files
import salt.utils.yaml
from salt.ext.six.moves import map
# Get logging started
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list',
'reload_': 'reload'
}
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 list_available(return_yaml=True, **kwargs):
'''
List the beacons currently available on the minion.
Args:
return_yaml (bool):
Whether to return YAML formatted output, default ``True``.
returns:
list: List of currently available Beacons.
CLI Example:
.. code-block:: bash
salt '*' beacons.list_available
'''
beacons = None
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'list_available'},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_list_available_complete',
wait=kwargs.get('timeout', 30))
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_available '
'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 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 delete(name, **kwargs):
'''
Delete a beacon item.
Args:
name (str): Name of the beacon to delete.
Returns:
dict: Boolean and status message on success or failure of delete.
CLI Example:
.. code-block:: bash
salt '*' beacons.delete ps
salt '*' beacons.delete load
'''
ret = {'comment': 'Failed to delete beacon {0}.'.format(name),
'result': False}
if 'test' in kwargs and kwargs['test']:
ret['result'] = True
ret['comment'] = 'Beacon: {0} would be deleted.'.format(name)
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'name': name,
'func': 'delete'},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_delete_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if name not in beacons:
ret['result'] = True
ret['comment'] = 'Deleted beacon: {0}.'.format(name)
return ret
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))
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 delete 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(**kwargs):
'''
Enable all beacons on the minion.
Returns:
bool: Boolean and status message on success or failure of enable.
CLI Example:
.. code-block:: bash
salt '*' beacons.enable
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be enabled.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'enable'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_enabled_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if 'enabled' in beacons and beacons['enabled']:
ret['result'] = True
ret['comment'] = 'Enabled beacons on minion.'
else:
ret['result'] = False
ret['comment'] = 'Failed to enable beacons on minion.'
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. Beacons enable job ' \
'failed.'
return ret
def disable(**kwargs):
'''
Disable all beacons jobs on the minion.
Returns:
dict: Boolean and status message on success or failure of disable.
CLI Example:
.. code-block:: bash
salt '*' beacons.disable
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be disabled.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'disable'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_disabled_complete',
wait=kwargs.get('timeout', 30))
log.debug('event_ret %s', event_ret)
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if 'enabled' in beacons and not beacons['enabled']:
ret['result'] = True
ret['comment'] = 'Disabled beacons on minion.'
else:
ret['result'] = False
ret['comment'] = 'Failed to disable beacons on minion.'
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. Beacons disable ' \
'job failed.'
return ret
def _get_beacon_config_dict(beacon_config):
beacon_config_dict = {}
if isinstance(beacon_config, list):
list(map(beacon_config_dict.update, beacon_config))
else:
beacon_config_dict = beacon_config
return beacon_config_dict
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 disable_beacon(name, **kwargs):
'''
Disable a beacon on the minion.
Args:
name (str): Name of the beacon to disable.
Returns:
dict: Boolean and status message on success or failure of disable.
CLI Example:
.. code-block:: bash
salt '*' beacons.disable_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'] = 'Beacons would be disabled.'
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': 'disable_beacon',
'name': name},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_disabled_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 not beacon_config_dict['enabled']:
ret['result'] = True
ret['comment'] = 'Disabled beacon {0} on minion.' \
''.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to disable beacon on minion.'
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 disable job ' \
'failed.'
return ret
def reset(**kwargs):
'''
Reset the beacon configuration on the minion.
CLI Example:
.. code-block:: bash
salt '*' beacons.reset
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be reset.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'reset'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_reset_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
ret['result'] = True
ret['comment'] = 'Beacon configuration reset.'
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 reset job ' \
'failed.'
return ret
|
saltstack/salt
|
salt/modules/beacons.py
|
modify
|
python
|
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
|
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'}]"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/beacons.py#L244-L361
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n",
"def list_(return_yaml=True,\n include_pillar=True,\n include_opts=True,\n **kwargs):\n '''\n List the beacons currently configured on the minion.\n\n Args:\n\n return_yaml (bool):\n Whether to return YAML formatted output, default ``True``.\n\n include_pillar (bool):\n Whether to include beacons that are configured in pillar, default\n is ``True``.\n\n include_opts (bool):\n Whether to include beacons that are configured in opts, default is\n ``True``.\n\n Returns:\n list: List of currently configured Beacons.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' beacons.list\n\n '''\n beacons = None\n\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list',\n 'include_pillar': include_pillar,\n 'include_opts': include_opts},\n 'manage_beacons')\n if res:\n event_ret = eventer.get_event(\n tag='/salt/minion/minion_beacons_list_complete',\n wait=kwargs.get('timeout', 30))\n log.debug('event_ret %s', event_ret)\n if event_ret and event_ret['complete']:\n beacons = event_ret['beacons']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event\n # system\n ret = {'comment': 'Event module not available. Beacon list failed.',\n 'result': False}\n return ret\n\n if beacons:\n if return_yaml:\n tmp = {'beacons': beacons}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return beacons\n else:\n return {'beacons': {}}\n",
"def get_event(self,\n wait=5,\n tag='',\n full=False,\n match_type=None,\n no_block=False,\n auto_reconnect=False):\n '''\n Get a single publication.\n If no publication is available, then block for up to ``wait`` seconds.\n Return publication if it is available or ``None`` if no publication is\n available.\n\n If wait is 0, then block forever.\n\n tag\n Only return events matching the given tag. If not specified, or set\n to an empty string, all events are returned. It is recommended to\n always be selective on what is to be returned in the event that\n multiple requests are being multiplexed.\n\n match_type\n Set the function to match the search tag with event tags.\n - 'startswith' : search for event tags that start with tag\n - 'endswith' : search for event tags that end with tag\n - 'find' : search for event tags that contain tag\n - 'regex' : regex search '^' + tag event tags\n - 'fnmatch' : fnmatch tag event tags matching\n Default is opts['event_match_type'] or 'startswith'\n\n .. versionadded:: 2015.8.0\n\n no_block\n Define if getting the event should be a blocking call or not.\n Defaults to False to keep backwards compatibility.\n\n .. versionadded:: 2015.8.0\n\n Notes:\n\n Searches cached publications first. If no cached publications are found\n that match the given tag specification, new publications are received\n and checked.\n\n If a publication is received that does not match the tag specification,\n it is DISCARDED unless it is subscribed to via subscribe() which will\n cause it to be cached.\n\n If a caller is not going to call get_event immediately after sending a\n request, it MUST subscribe the result to ensure the response is not lost\n should other regions of code call get_event for other purposes.\n '''\n assert self._run_io_loop_sync\n\n match_func = self._get_match_func(match_type)\n\n ret = self._check_pending(tag, match_func)\n if ret is None:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n if auto_reconnect:\n raise_errors = self.raise_errors\n self.raise_errors = True\n while True:\n try:\n ret = self._get_event(wait, tag, match_func, no_block)\n break\n except tornado.iostream.StreamClosedError:\n self.close_pub()\n self.connect_pub(timeout=wait)\n continue\n self.raise_errors = raise_errors\n else:\n ret = self._get_event(wait, tag, match_func, no_block)\n\n if ret is None or full:\n return ret\n else:\n return ret['data']\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing the Salt beacons on a minion
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import os
# Import Salt libs
import salt.ext.six as six
import salt.utils.event
import salt.utils.files
import salt.utils.yaml
from salt.ext.six.moves import map
# Get logging started
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list',
'reload_': 'reload'
}
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 list_available(return_yaml=True, **kwargs):
'''
List the beacons currently available on the minion.
Args:
return_yaml (bool):
Whether to return YAML formatted output, default ``True``.
returns:
list: List of currently available Beacons.
CLI Example:
.. code-block:: bash
salt '*' beacons.list_available
'''
beacons = None
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'list_available'},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_list_available_complete',
wait=kwargs.get('timeout', 30))
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_available '
'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 delete(name, **kwargs):
'''
Delete a beacon item.
Args:
name (str): Name of the beacon to delete.
Returns:
dict: Boolean and status message on success or failure of delete.
CLI Example:
.. code-block:: bash
salt '*' beacons.delete ps
salt '*' beacons.delete load
'''
ret = {'comment': 'Failed to delete beacon {0}.'.format(name),
'result': False}
if 'test' in kwargs and kwargs['test']:
ret['result'] = True
ret['comment'] = 'Beacon: {0} would be deleted.'.format(name)
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'name': name,
'func': 'delete'},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_delete_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if name not in beacons:
ret['result'] = True
ret['comment'] = 'Deleted beacon: {0}.'.format(name)
return ret
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))
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 delete 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(**kwargs):
'''
Enable all beacons on the minion.
Returns:
bool: Boolean and status message on success or failure of enable.
CLI Example:
.. code-block:: bash
salt '*' beacons.enable
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be enabled.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'enable'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_enabled_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if 'enabled' in beacons and beacons['enabled']:
ret['result'] = True
ret['comment'] = 'Enabled beacons on minion.'
else:
ret['result'] = False
ret['comment'] = 'Failed to enable beacons on minion.'
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. Beacons enable job ' \
'failed.'
return ret
def disable(**kwargs):
'''
Disable all beacons jobs on the minion.
Returns:
dict: Boolean and status message on success or failure of disable.
CLI Example:
.. code-block:: bash
salt '*' beacons.disable
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be disabled.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'disable'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_disabled_complete',
wait=kwargs.get('timeout', 30))
log.debug('event_ret %s', event_ret)
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if 'enabled' in beacons and not beacons['enabled']:
ret['result'] = True
ret['comment'] = 'Disabled beacons on minion.'
else:
ret['result'] = False
ret['comment'] = 'Failed to disable beacons on minion.'
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. Beacons disable ' \
'job failed.'
return ret
def _get_beacon_config_dict(beacon_config):
beacon_config_dict = {}
if isinstance(beacon_config, list):
list(map(beacon_config_dict.update, beacon_config))
else:
beacon_config_dict = beacon_config
return beacon_config_dict
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 disable_beacon(name, **kwargs):
'''
Disable a beacon on the minion.
Args:
name (str): Name of the beacon to disable.
Returns:
dict: Boolean and status message on success or failure of disable.
CLI Example:
.. code-block:: bash
salt '*' beacons.disable_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'] = 'Beacons would be disabled.'
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': 'disable_beacon',
'name': name},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_disabled_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 not beacon_config_dict['enabled']:
ret['result'] = True
ret['comment'] = 'Disabled beacon {0} on minion.' \
''.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to disable beacon on minion.'
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 disable job ' \
'failed.'
return ret
def reset(**kwargs):
'''
Reset the beacon configuration on the minion.
CLI Example:
.. code-block:: bash
salt '*' beacons.reset
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be reset.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'reset'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_reset_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
ret['result'] = True
ret['comment'] = 'Beacon configuration reset.'
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 reset job ' \
'failed.'
return ret
|
saltstack/salt
|
salt/modules/beacons.py
|
save
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/beacons.py#L422-L459
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def safe_dump(data, stream=None, **kwargs):\n '''\n Use a custom dumper to ensure that defaultdict and OrderedDict are\n represented properly. Ensure that unicode strings are encoded unless\n explicitly told not to.\n '''\n if 'allow_unicode' not in kwargs:\n kwargs['allow_unicode'] = True\n return yaml.dump(data, stream, Dumper=SafeOrderedDumper, **kwargs)\n",
"def list_(return_yaml=True,\n include_pillar=True,\n include_opts=True,\n **kwargs):\n '''\n List the beacons currently configured on the minion.\n\n Args:\n\n return_yaml (bool):\n Whether to return YAML formatted output, default ``True``.\n\n include_pillar (bool):\n Whether to include beacons that are configured in pillar, default\n is ``True``.\n\n include_opts (bool):\n Whether to include beacons that are configured in opts, default is\n ``True``.\n\n Returns:\n list: List of currently configured Beacons.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' beacons.list\n\n '''\n beacons = None\n\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list',\n 'include_pillar': include_pillar,\n 'include_opts': include_opts},\n 'manage_beacons')\n if res:\n event_ret = eventer.get_event(\n tag='/salt/minion/minion_beacons_list_complete',\n wait=kwargs.get('timeout', 30))\n log.debug('event_ret %s', event_ret)\n if event_ret and event_ret['complete']:\n beacons = event_ret['beacons']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event\n # system\n ret = {'comment': 'Event module not available. Beacon list failed.',\n 'result': False}\n return ret\n\n if beacons:\n if return_yaml:\n tmp = {'beacons': beacons}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return beacons\n else:\n return {'beacons': {}}\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing the Salt beacons on a minion
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import os
# Import Salt libs
import salt.ext.six as six
import salt.utils.event
import salt.utils.files
import salt.utils.yaml
from salt.ext.six.moves import map
# Get logging started
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list',
'reload_': 'reload'
}
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 list_available(return_yaml=True, **kwargs):
'''
List the beacons currently available on the minion.
Args:
return_yaml (bool):
Whether to return YAML formatted output, default ``True``.
returns:
list: List of currently available Beacons.
CLI Example:
.. code-block:: bash
salt '*' beacons.list_available
'''
beacons = None
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'list_available'},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_list_available_complete',
wait=kwargs.get('timeout', 30))
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_available '
'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 delete(name, **kwargs):
'''
Delete a beacon item.
Args:
name (str): Name of the beacon to delete.
Returns:
dict: Boolean and status message on success or failure of delete.
CLI Example:
.. code-block:: bash
salt '*' beacons.delete ps
salt '*' beacons.delete load
'''
ret = {'comment': 'Failed to delete beacon {0}.'.format(name),
'result': False}
if 'test' in kwargs and kwargs['test']:
ret['result'] = True
ret['comment'] = 'Beacon: {0} would be deleted.'.format(name)
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'name': name,
'func': 'delete'},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_delete_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if name not in beacons:
ret['result'] = True
ret['comment'] = 'Deleted beacon: {0}.'.format(name)
return ret
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))
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 delete failed.'
return ret
def enable(**kwargs):
'''
Enable all beacons on the minion.
Returns:
bool: Boolean and status message on success or failure of enable.
CLI Example:
.. code-block:: bash
salt '*' beacons.enable
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be enabled.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'enable'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_enabled_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if 'enabled' in beacons and beacons['enabled']:
ret['result'] = True
ret['comment'] = 'Enabled beacons on minion.'
else:
ret['result'] = False
ret['comment'] = 'Failed to enable beacons on minion.'
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. Beacons enable job ' \
'failed.'
return ret
def disable(**kwargs):
'''
Disable all beacons jobs on the minion.
Returns:
dict: Boolean and status message on success or failure of disable.
CLI Example:
.. code-block:: bash
salt '*' beacons.disable
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be disabled.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'disable'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_disabled_complete',
wait=kwargs.get('timeout', 30))
log.debug('event_ret %s', event_ret)
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if 'enabled' in beacons and not beacons['enabled']:
ret['result'] = True
ret['comment'] = 'Disabled beacons on minion.'
else:
ret['result'] = False
ret['comment'] = 'Failed to disable beacons on minion.'
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. Beacons disable ' \
'job failed.'
return ret
def _get_beacon_config_dict(beacon_config):
beacon_config_dict = {}
if isinstance(beacon_config, list):
list(map(beacon_config_dict.update, beacon_config))
else:
beacon_config_dict = beacon_config
return beacon_config_dict
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 disable_beacon(name, **kwargs):
'''
Disable a beacon on the minion.
Args:
name (str): Name of the beacon to disable.
Returns:
dict: Boolean and status message on success or failure of disable.
CLI Example:
.. code-block:: bash
salt '*' beacons.disable_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'] = 'Beacons would be disabled.'
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': 'disable_beacon',
'name': name},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_disabled_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 not beacon_config_dict['enabled']:
ret['result'] = True
ret['comment'] = 'Disabled beacon {0} on minion.' \
''.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to disable beacon on minion.'
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 disable job ' \
'failed.'
return ret
def reset(**kwargs):
'''
Reset the beacon configuration on the minion.
CLI Example:
.. code-block:: bash
salt '*' beacons.reset
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be reset.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'reset'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_reset_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
ret['result'] = True
ret['comment'] = 'Beacon configuration reset.'
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 reset job ' \
'failed.'
return ret
|
saltstack/salt
|
salt/modules/beacons.py
|
enable_beacon
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/beacons.py#L563-L634
|
[
"def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n",
"def list_(return_yaml=True,\n include_pillar=True,\n include_opts=True,\n **kwargs):\n '''\n List the beacons currently configured on the minion.\n\n Args:\n\n return_yaml (bool):\n Whether to return YAML formatted output, default ``True``.\n\n include_pillar (bool):\n Whether to include beacons that are configured in pillar, default\n is ``True``.\n\n include_opts (bool):\n Whether to include beacons that are configured in opts, default is\n ``True``.\n\n Returns:\n list: List of currently configured Beacons.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' beacons.list\n\n '''\n beacons = None\n\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list',\n 'include_pillar': include_pillar,\n 'include_opts': include_opts},\n 'manage_beacons')\n if res:\n event_ret = eventer.get_event(\n tag='/salt/minion/minion_beacons_list_complete',\n wait=kwargs.get('timeout', 30))\n log.debug('event_ret %s', event_ret)\n if event_ret and event_ret['complete']:\n beacons = event_ret['beacons']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event\n # system\n ret = {'comment': 'Event module not available. Beacon list failed.',\n 'result': False}\n return ret\n\n if beacons:\n if return_yaml:\n tmp = {'beacons': beacons}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return beacons\n else:\n return {'beacons': {}}\n",
"def _get_beacon_config_dict(beacon_config):\n beacon_config_dict = {}\n if isinstance(beacon_config, list):\n list(map(beacon_config_dict.update, beacon_config))\n else:\n beacon_config_dict = beacon_config\n\n return beacon_config_dict\n",
"def get_event(self,\n wait=5,\n tag='',\n full=False,\n match_type=None,\n no_block=False,\n auto_reconnect=False):\n '''\n Get a single publication.\n If no publication is available, then block for up to ``wait`` seconds.\n Return publication if it is available or ``None`` if no publication is\n available.\n\n If wait is 0, then block forever.\n\n tag\n Only return events matching the given tag. If not specified, or set\n to an empty string, all events are returned. It is recommended to\n always be selective on what is to be returned in the event that\n multiple requests are being multiplexed.\n\n match_type\n Set the function to match the search tag with event tags.\n - 'startswith' : search for event tags that start with tag\n - 'endswith' : search for event tags that end with tag\n - 'find' : search for event tags that contain tag\n - 'regex' : regex search '^' + tag event tags\n - 'fnmatch' : fnmatch tag event tags matching\n Default is opts['event_match_type'] or 'startswith'\n\n .. versionadded:: 2015.8.0\n\n no_block\n Define if getting the event should be a blocking call or not.\n Defaults to False to keep backwards compatibility.\n\n .. versionadded:: 2015.8.0\n\n Notes:\n\n Searches cached publications first. If no cached publications are found\n that match the given tag specification, new publications are received\n and checked.\n\n If a publication is received that does not match the tag specification,\n it is DISCARDED unless it is subscribed to via subscribe() which will\n cause it to be cached.\n\n If a caller is not going to call get_event immediately after sending a\n request, it MUST subscribe the result to ensure the response is not lost\n should other regions of code call get_event for other purposes.\n '''\n assert self._run_io_loop_sync\n\n match_func = self._get_match_func(match_type)\n\n ret = self._check_pending(tag, match_func)\n if ret is None:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n if auto_reconnect:\n raise_errors = self.raise_errors\n self.raise_errors = True\n while True:\n try:\n ret = self._get_event(wait, tag, match_func, no_block)\n break\n except tornado.iostream.StreamClosedError:\n self.close_pub()\n self.connect_pub(timeout=wait)\n continue\n self.raise_errors = raise_errors\n else:\n ret = self._get_event(wait, tag, match_func, no_block)\n\n if ret is None or full:\n return ret\n else:\n return ret['data']\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing the Salt beacons on a minion
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import os
# Import Salt libs
import salt.ext.six as six
import salt.utils.event
import salt.utils.files
import salt.utils.yaml
from salt.ext.six.moves import map
# Get logging started
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list',
'reload_': 'reload'
}
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 list_available(return_yaml=True, **kwargs):
'''
List the beacons currently available on the minion.
Args:
return_yaml (bool):
Whether to return YAML formatted output, default ``True``.
returns:
list: List of currently available Beacons.
CLI Example:
.. code-block:: bash
salt '*' beacons.list_available
'''
beacons = None
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'list_available'},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_list_available_complete',
wait=kwargs.get('timeout', 30))
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_available '
'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 delete(name, **kwargs):
'''
Delete a beacon item.
Args:
name (str): Name of the beacon to delete.
Returns:
dict: Boolean and status message on success or failure of delete.
CLI Example:
.. code-block:: bash
salt '*' beacons.delete ps
salt '*' beacons.delete load
'''
ret = {'comment': 'Failed to delete beacon {0}.'.format(name),
'result': False}
if 'test' in kwargs and kwargs['test']:
ret['result'] = True
ret['comment'] = 'Beacon: {0} would be deleted.'.format(name)
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'name': name,
'func': 'delete'},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_delete_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if name not in beacons:
ret['result'] = True
ret['comment'] = 'Deleted beacon: {0}.'.format(name)
return ret
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))
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 delete 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(**kwargs):
'''
Enable all beacons on the minion.
Returns:
bool: Boolean and status message on success or failure of enable.
CLI Example:
.. code-block:: bash
salt '*' beacons.enable
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be enabled.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'enable'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_enabled_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if 'enabled' in beacons and beacons['enabled']:
ret['result'] = True
ret['comment'] = 'Enabled beacons on minion.'
else:
ret['result'] = False
ret['comment'] = 'Failed to enable beacons on minion.'
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. Beacons enable job ' \
'failed.'
return ret
def disable(**kwargs):
'''
Disable all beacons jobs on the minion.
Returns:
dict: Boolean and status message on success or failure of disable.
CLI Example:
.. code-block:: bash
salt '*' beacons.disable
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be disabled.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'disable'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacons_disabled_complete',
wait=kwargs.get('timeout', 30))
log.debug('event_ret %s', event_ret)
if event_ret and event_ret['complete']:
beacons = event_ret['beacons']
if 'enabled' in beacons and not beacons['enabled']:
ret['result'] = True
ret['comment'] = 'Disabled beacons on minion.'
else:
ret['result'] = False
ret['comment'] = 'Failed to disable beacons on minion.'
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. Beacons disable ' \
'job failed.'
return ret
def _get_beacon_config_dict(beacon_config):
beacon_config_dict = {}
if isinstance(beacon_config, list):
list(map(beacon_config_dict.update, beacon_config))
else:
beacon_config_dict = beacon_config
return beacon_config_dict
def disable_beacon(name, **kwargs):
'''
Disable a beacon on the minion.
Args:
name (str): Name of the beacon to disable.
Returns:
dict: Boolean and status message on success or failure of disable.
CLI Example:
.. code-block:: bash
salt '*' beacons.disable_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'] = 'Beacons would be disabled.'
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': 'disable_beacon',
'name': name},
'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_disabled_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 not beacon_config_dict['enabled']:
ret['result'] = True
ret['comment'] = 'Disabled beacon {0} on minion.' \
''.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to disable beacon on minion.'
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 disable job ' \
'failed.'
return ret
def reset(**kwargs):
'''
Reset the beacon configuration on the minion.
CLI Example:
.. code-block:: bash
salt '*' beacons.reset
'''
ret = {'comment': [],
'result': True}
if 'test' in kwargs and kwargs['test']:
ret['comment'] = 'Beacons would be reset.'
else:
try:
eventer = salt.utils.event.get_event('minion', opts=__opts__)
res = __salt__['event.fire']({'func': 'reset'}, 'manage_beacons')
if res:
event_ret = eventer.get_event(
tag='/salt/minion/minion_beacon_reset_complete',
wait=kwargs.get('timeout', 30))
if event_ret and event_ret['complete']:
ret['result'] = True
ret['comment'] = 'Beacon configuration reset.'
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 reset job ' \
'failed.'
return ret
|
saltstack/salt
|
salt/sdb/rest.py
|
set_
|
python
|
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)
|
Set a key/value pair in the REST interface
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/rest.py#L83-L87
|
[
"def query(key, value=None, service=None, profile=None): # pylint: disable=W0613\n '''\n Get a value from the REST interface\n '''\n comps = key.split('?')\n key = comps[0]\n key_vars = {}\n for pair in comps[1].split('&'):\n pair_key, pair_val = pair.split('=')\n key_vars[pair_key] = pair_val\n\n renderer = __opts__.get('renderer', 'jinja|yaml')\n rend = salt.loader.render(__opts__, {})\n blacklist = __opts__.get('renderer_blacklist')\n whitelist = __opts__.get('renderer_whitelist')\n url = compile_template(\n ':string:',\n rend,\n renderer,\n blacklist,\n whitelist,\n input_data=profile[key]['url'],\n **key_vars\n )\n\n extras = {}\n for item in profile[key]:\n if item not in ('backend', 'url'):\n extras[item] = profile[key][item]\n\n result = http.query(\n url,\n decode=True,\n **extras\n )\n\n return result['dict']\n"
] |
# -*- coding: utf-8 -*-
'''
Generic REST API SDB Module
:maintainer: SaltStack
:maturity: New
:platform: all
.. versionadded:: 2015.8.0
This module allows access to a REST interface using an ``sdb://`` URI.
Like all REST modules, the REST module requires a configuration profile to
be configured in either the minion or master configuration file. This profile
requires very little. In the example:
.. code-block:: yaml
my-rest-api:
driver: rest
urls:
url: https://api.github.com/
keys:
url: https://api.github.com/users/{{user}}/keys
backend: requests
The ``driver`` refers to the REST module, and must be set to ``rest`` in order
to use this driver. Each of the other items inside this block refers to a
separate set of HTTP items, including a URL and any options associated with it.
The options used here should match the options available in
``salt.utils.http.query()``.
In order to call the ``urls`` item in the example, the following reference can
be made inside a configuration file:
.. code-block:: yaml
github_urls: sdb://my-rest-api/urls
Key/Value pairs may also be used with this driver, and merged into the URL using
the configured renderer (``jinja``, by default). For instance, in order to use
the ``keys`` item in the example, the following reference can be made:
.. code-block:: yaml
github_urls: sdb://my-rest-api/keys?user=myuser
This will cause the following URL to actually be called:
.. code-block:: yaml
https://api.github.com/users/myuser/keys
Key/Value pairs will NOT be passed through as GET data. If GET data needs to be
sent to the URL, then it should be configured in the SDB configuration block.
For instance:
.. code-block:: yaml
another-rest-api:
driver: rest
user_data:
url: https://api.example.com/users/
params:
user: myuser
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.loader
import salt.utils.http as http
from salt.template import compile_template
log = logging.getLogger(__name__)
__func_alias__ = {
'set_': 'set'
}
def get(key, service=None, profile=None): # pylint: disable=W0613
'''
Get a value from the REST interface
'''
return query(key, None, 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']
|
saltstack/salt
|
salt/sdb/rest.py
|
query
|
python
|
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']
|
Get a value from the REST interface
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/rest.py#L97-L133
|
[
"def compile_template(template,\n renderers,\n default,\n blacklist,\n whitelist,\n saltenv='base',\n sls='',\n input_data='',\n **kwargs):\n '''\n Take the path to a template and return the high data structure\n derived from the template.\n\n Helpers:\n\n :param mask_value:\n Mask value for debugging purposes (prevent sensitive information etc)\n example: \"mask_value=\"pass*\". All \"passwd\", \"password\", \"pass\" will\n be masked (as text).\n '''\n\n # if any error occurs, we return an empty dictionary\n ret = {}\n\n log.debug('compile template: %s', template)\n\n if 'env' in kwargs:\n # \"env\" is not supported; Use \"saltenv\".\n kwargs.pop('env')\n\n if template != ':string:':\n # Template was specified incorrectly\n if not isinstance(template, six.string_types):\n log.error('Template was specified incorrectly: %s', template)\n return ret\n # Template does not exist\n if not os.path.isfile(template):\n log.error('Template does not exist: %s', template)\n return ret\n # Template is an empty file\n if salt.utils.files.is_empty(template):\n log.debug('Template is an empty file: %s', template)\n return ret\n\n with codecs.open(template, encoding=SLS_ENCODING) as ifile:\n # data input to the first render function in the pipe\n input_data = ifile.read()\n if not input_data.strip():\n # Template is nothing but whitespace\n log.error('Template is nothing but whitespace: %s', template)\n return ret\n\n # Get the list of render funcs in the render pipe line.\n render_pipe = template_shebang(template, renderers, default, blacklist, whitelist, input_data)\n\n windows_newline = '\\r\\n' in input_data\n\n input_data = StringIO(input_data)\n for render, argline in render_pipe:\n if salt.utils.stringio.is_readable(input_data):\n input_data.seek(0) # pylint: disable=no-member\n render_kwargs = dict(renderers=renderers, tmplpath=template)\n render_kwargs.update(kwargs)\n if argline:\n render_kwargs['argline'] = argline\n start = time.time()\n ret = render(input_data, saltenv, sls, **render_kwargs)\n log.profile(\n 'Time (in seconds) to render \\'%s\\' using \\'%s\\' renderer: %s',\n template,\n render.__module__.split('.')[-1],\n time.time() - start\n )\n if ret is None:\n # The file is empty or is being written elsewhere\n time.sleep(0.01)\n ret = render(input_data, saltenv, sls, **render_kwargs)\n input_data = ret\n if log.isEnabledFor(logging.GARBAGE): # pylint: disable=no-member\n # If ret is not a StringIO (which means it was rendered using\n # yaml, mako, or another engine which renders to a data\n # structure) we don't want to log this.\n if salt.utils.stringio.is_readable(ret):\n log.debug('Rendered data from file: %s:\\n%s', template,\n salt.utils.sanitizers.mask_args_value(salt.utils.data.decode(ret.read()),\n kwargs.get('mask_value'))) # pylint: disable=no-member\n ret.seek(0) # pylint: disable=no-member\n\n # Preserve newlines from original template\n if windows_newline:\n if salt.utils.stringio.is_readable(ret):\n is_stringio = True\n contents = ret.read()\n else:\n is_stringio = False\n contents = ret\n\n if isinstance(contents, six.string_types):\n if '\\r\\n' not in contents:\n contents = contents.replace('\\n', '\\r\\n')\n ret = StringIO(contents) if is_stringio else contents\n else:\n if is_stringio:\n ret.seek(0)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Generic REST API SDB Module
:maintainer: SaltStack
:maturity: New
:platform: all
.. versionadded:: 2015.8.0
This module allows access to a REST interface using an ``sdb://`` URI.
Like all REST modules, the REST module requires a configuration profile to
be configured in either the minion or master configuration file. This profile
requires very little. In the example:
.. code-block:: yaml
my-rest-api:
driver: rest
urls:
url: https://api.github.com/
keys:
url: https://api.github.com/users/{{user}}/keys
backend: requests
The ``driver`` refers to the REST module, and must be set to ``rest`` in order
to use this driver. Each of the other items inside this block refers to a
separate set of HTTP items, including a URL and any options associated with it.
The options used here should match the options available in
``salt.utils.http.query()``.
In order to call the ``urls`` item in the example, the following reference can
be made inside a configuration file:
.. code-block:: yaml
github_urls: sdb://my-rest-api/urls
Key/Value pairs may also be used with this driver, and merged into the URL using
the configured renderer (``jinja``, by default). For instance, in order to use
the ``keys`` item in the example, the following reference can be made:
.. code-block:: yaml
github_urls: sdb://my-rest-api/keys?user=myuser
This will cause the following URL to actually be called:
.. code-block:: yaml
https://api.github.com/users/myuser/keys
Key/Value pairs will NOT be passed through as GET data. If GET data needs to be
sent to the URL, then it should be configured in the SDB configuration block.
For instance:
.. code-block:: yaml
another-rest-api:
driver: rest
user_data:
url: https://api.example.com/users/
params:
user: myuser
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.loader
import salt.utils.http as http
from salt.template import compile_template
log = logging.getLogger(__name__)
__func_alias__ = {
'set_': 'set'
}
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 get(key, service=None, profile=None): # pylint: disable=W0613
'''
Get a value from the REST interface
'''
return query(key, None, service, profile)
|
saltstack/salt
|
salt/states/event.py
|
send
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/event.py#L13-L66
| null |
# -*- coding: utf-8 -*-
'''
Send events through Salt's event system during state runs
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# import salt libs
import salt.utils.functools
def wait(name, sfun=None):
'''
Fire an event on the Salt master event bus if called from a watch statement
.. versionadded:: 2014.7.0
Example:
.. code-block:: jinja
# Stand up a new web server.
apache:
pkg:
- installed
- name: httpd
service:
- running
- enable: True
- name: httpd
# Notify the load balancer to update the pool once Apache is running.
refresh_pool:
event:
- wait
- name: mycompany/loadbalancer/pool/update
- data:
new_web_server_ip: {{ grains['ipv4'] | first() }}
- watch:
- pkg: apache
'''
# Noop. The state system will call the mod_watch function instead.
return {'name': name, 'changes': {}, 'result': True, 'comment': ''}
mod_watch = salt.utils.functools.alias_function(send, 'mod_watch')
fire_master = salt.utils.functools.alias_function(send, 'fire_master')
|
saltstack/salt
|
salt/states/neutron_secgroup_rule.py
|
_rule_compare
|
python
|
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
|
Compare the common keys between security group rules against eachother
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/neutron_secgroup_rule.py#L44-L53
| null |
# -*- coding: utf-8 -*-
'''
Management of OpenStack Neutron Security Group Rules
====================================================
.. versionadded:: 2018.3.0
:depends: shade
:configuration: see :py:mod:`salt.modules.neutronng` for setup instructions
Example States
.. code-block:: yaml
create security group rule:
neutron_secgroup_rule.present:
- name: security_group1
- project_name: Project1
- protocol: icmp
delete security group:
neutron_secgroup_rule.absent:
- name_or_id: security_group1
create security group with optional params:
neutron_secgroup_rule.present:
- name: security_group1
- description: "Very Secure Security Group"
- project_id: 1dcac318a83b4610b7a7f7ba01465548
'''
from __future__ import absolute_import, print_function, unicode_literals
__virtualname__ = 'neutron_secgroup_rule'
def __virtual__():
if 'neutronng.list_subnets' in __salt__:
return __virtualname__
return (False, 'The neutronng execution module failed to load:\
shade python module is not available')
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
|
saltstack/salt
|
salt/states/neutron_secgroup_rule.py
|
present
|
python
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/neutron_secgroup_rule.py#L56-L128
|
[
"def _rule_compare(rule1, rule2):\n '''\n Compare the common keys between security group rules against eachother\n '''\n\n commonkeys = set(rule1.keys()).intersection(rule2.keys())\n for key in commonkeys:\n if rule1[key] != rule2[key]:\n return False\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Management of OpenStack Neutron Security Group Rules
====================================================
.. versionadded:: 2018.3.0
:depends: shade
:configuration: see :py:mod:`salt.modules.neutronng` for setup instructions
Example States
.. code-block:: yaml
create security group rule:
neutron_secgroup_rule.present:
- name: security_group1
- project_name: Project1
- protocol: icmp
delete security group:
neutron_secgroup_rule.absent:
- name_or_id: security_group1
create security group with optional params:
neutron_secgroup_rule.present:
- name: security_group1
- description: "Very Secure Security Group"
- project_id: 1dcac318a83b4610b7a7f7ba01465548
'''
from __future__ import absolute_import, print_function, unicode_literals
__virtualname__ = 'neutron_secgroup_rule'
def __virtual__():
if 'neutronng.list_subnets' in __salt__:
return __virtualname__
return (False, 'The neutronng execution module failed to load:\
shade python module is not available')
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 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
|
saltstack/salt
|
salt/states/neutron_secgroup_rule.py
|
absent
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/neutron_secgroup_rule.py#L131-L180
|
[
"def _rule_compare(rule1, rule2):\n '''\n Compare the common keys between security group rules against eachother\n '''\n\n commonkeys = set(rule1.keys()).intersection(rule2.keys())\n for key in commonkeys:\n if rule1[key] != rule2[key]:\n return False\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Management of OpenStack Neutron Security Group Rules
====================================================
.. versionadded:: 2018.3.0
:depends: shade
:configuration: see :py:mod:`salt.modules.neutronng` for setup instructions
Example States
.. code-block:: yaml
create security group rule:
neutron_secgroup_rule.present:
- name: security_group1
- project_name: Project1
- protocol: icmp
delete security group:
neutron_secgroup_rule.absent:
- name_or_id: security_group1
create security group with optional params:
neutron_secgroup_rule.present:
- name: security_group1
- description: "Very Secure Security Group"
- project_id: 1dcac318a83b4610b7a7f7ba01465548
'''
from __future__ import absolute_import, print_function, unicode_literals
__virtualname__ = 'neutron_secgroup_rule'
def __virtual__():
if 'neutronng.list_subnets' in __salt__:
return __virtualname__
return (False, 'The neutronng execution module failed to load:\
shade python module is not available')
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
|
saltstack/salt
|
salt/states/http.py
|
query
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/http.py#L23-L153
| null |
# -*- coding: utf-8 -*-
'''
HTTP monitoring states
Perform an HTTP query and statefully return the result
.. versionadded:: 2015.5.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import re
import time
__monitor__ = [
'query',
]
log = logging.getLogger(__name__)
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'])
|
saltstack/salt
|
salt/states/http.py
|
wait_for_successful_query
|
python
|
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'])
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/http.py#L156-L195
|
[
"def query(name, match=None, match_type='string', status=None, status_type='string', wait_for=None, **kwargs):\n '''\n Perform an HTTP query and statefully return the result\n\n Passes through all the parameters described in the\n :py:func:`utils.http.query function <salt.utils.http.query>`:\n\n name\n The name of the query.\n\n match\n Specifies a pattern to look for in the return text. By default, this will\n perform a string comparison of looking for the value of match in the return\n text.\n\n match_type\n Specifies the type of pattern matching to use on match. Default is ``string``, but\n can also be set to ``pcre`` to use regular expression matching if a more\n complex pattern matching is required.\n\n .. note::\n\n Despite the name of ``match_type`` for this argument, this setting\n actually uses Python's ``re.search()`` function rather than Python's\n ``re.match()`` function.\n\n status\n The status code for a URL for which to be checked. Can be used instead of\n or in addition to the ``match`` setting.\n\n status_type\n Specifies the type of pattern matching to use for status. Default is ``string``, but\n can also be set to ``pcre`` to use regular expression matching if a more\n complex pattern matching is required.\n\n .. versionadded:: Neon\n\n .. note::\n\n Despite the name of ``match_type`` for this argument, this setting\n actually uses Python's ``re.search()`` function rather than Python's\n ``re.match()`` function.\n\n If both ``match`` and ``status`` options are set, both settings will be checked.\n However, note that if only one option is ``True`` and the other is ``False``,\n then ``False`` will be returned. If this case is reached, the comments in the\n return data will contain troubleshooting information.\n\n For more information about the ``http.query`` state, refer to the\n :ref:`HTTP Tutorial <tutorial-http>`.\n\n .. code-block:: yaml\n\n query_example:\n http.query:\n - name: 'http://example.com/'\n - status: 200\n\n '''\n # Monitoring state, but changes may be made over HTTP\n ret = {'name': name,\n 'result': None,\n 'comment': '',\n 'changes': {},\n 'data': {}} # Data field for monitoring state\n\n if match is None and status is None:\n ret['result'] = False\n ret['comment'] += (\n ' Either match text (match) or a status code (status) is required.'\n )\n return ret\n\n if 'decode' not in kwargs:\n kwargs['decode'] = False\n kwargs['text'] = True\n kwargs['status'] = True\n if __opts__['test']:\n kwargs['test'] = True\n\n if wait_for:\n data = __salt__['http.wait_for_successful_query'](name, wait_for=wait_for, **kwargs)\n else:\n data = __salt__['http.query'](name, **kwargs)\n\n if match is not None:\n if match_type == 'string':\n if str(match) in data.get('text', ''):\n ret['result'] = True\n ret['comment'] += ' Match text \"{0}\" was found.'.format(match)\n else:\n ret['result'] = False\n ret['comment'] += ' Match text \"{0}\" was not found.'.format(match)\n elif match_type == 'pcre':\n if re.search(str(match), str(data.get('text', ''))):\n ret['result'] = True\n ret['comment'] += ' Match pattern \"{0}\" was found.'.format(match)\n else:\n ret['result'] = False\n ret['comment'] += ' Match pattern \"{0}\" was not found.'.format(match)\n\n if status is not None:\n if status_type == 'string':\n if str(data.get('status', '')) == str(status):\n ret['comment'] += ' Status {0} was found.'.format(status)\n if ret['result'] is None:\n ret['result'] = True\n else:\n ret['comment'] += ' Status {0} was not found.'.format(status)\n ret['result'] = False\n elif status_type == 'pcre':\n if re.search(str(status), str(data.get('status', ''))):\n ret['comment'] += ' Status pattern \"{0}\" was found.'.format(status)\n if ret['result'] is None:\n ret['result'] = True\n else:\n ret['comment'] += ' Status pattern \"{0}\" was not found.'.format(status)\n ret['result'] = False\n\n # cleanup spaces in comment\n ret['comment'] = ret['comment'].strip()\n\n if __opts__['test'] is True:\n ret['result'] = None\n ret['comment'] += ' (TEST MODE'\n if 'test_url' in kwargs:\n ret['comment'] += ', TEST URL WAS: {0}'.format(kwargs['test_url'])\n ret['comment'] += ')'\n\n ret['data'] = data\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
HTTP monitoring states
Perform an HTTP query and statefully return the result
.. versionadded:: 2015.5.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import re
import time
__monitor__ = [
'query',
]
log = logging.getLogger(__name__)
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
|
saltstack/salt
|
salt/modules/dracr.py
|
__parse_drac
|
python
|
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
|
Parse Dell DRAC output
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L43-L64
| null |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
__execute_cmd
|
python
|
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
|
Execute rac commands
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L67-L101
| null |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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_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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
__execute_ret
|
python
|
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
|
Execute rac commands
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L104-L151
| null |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
get_property
|
python
|
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
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L154-L183
|
[
"def __execute_ret(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n if module == 'ALL':\n modswitch = '-a '\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n else:\n fmtlines = []\n for l in cmd['stdout'].splitlines():\n if l.startswith('Security Alert'):\n continue\n if l.startswith('RAC1168:'):\n break\n if l.startswith('RAC1169:'):\n break\n if l.startswith('Continuing execution'):\n continue\n\n if not l.strip():\n continue\n fmtlines.append(l)\n if '=' in l:\n continue\n cmd['stdout'] = '\\n'.join(fmtlines)\n\n return cmd\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
set_property
|
python
|
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
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L186-L220
|
[
"def __execute_ret(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n if module == 'ALL':\n modswitch = '-a '\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n else:\n fmtlines = []\n for l in cmd['stdout'].splitlines():\n if l.startswith('Security Alert'):\n continue\n if l.startswith('RAC1168:'):\n break\n if l.startswith('RAC1169:'):\n break\n if l.startswith('Continuing execution'):\n continue\n\n if not l.strip():\n continue\n fmtlines.append(l)\n if '=' in l:\n continue\n cmd['stdout'] = '\\n'.join(fmtlines)\n\n return cmd\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
ensure_property_set
|
python
|
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
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L223-L255
|
[
"def get_property(host=None, admin_username=None, admin_password=None, property=None):\n '''\n .. versionadded:: Fluorine\n\n Return specific property\n\n host\n The chassis host.\n\n admin_username\n The username used to access the chassis.\n\n admin_password\n The password used to access the chassis.\n\n property:\n The property which should be get.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt dell dracr.get_property property=System.ServerOS.HostName\n '''\n if property is None:\n raise SaltException('No property specified!')\n ret = __execute_ret('get \\'{0}\\''.format(property), host=host,\n admin_username=admin_username,\n admin_password=admin_password)\n return ret\n",
"def set_property(host=None, admin_username=None, admin_password=None, property=None, value=None):\n '''\n .. versionadded:: Fluorine\n\n Set specific property\n\n host\n The chassis host.\n\n admin_username\n The username used to access the chassis.\n\n admin_password\n The password used to access the chassis.\n\n property:\n The property which should be set.\n\n value:\n The value which should be set to property.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt dell dracr.set_property property=System.ServerOS.HostName value=Pretty-server\n '''\n if property is None:\n raise SaltException('No property specified!')\n elif value is None:\n raise SaltException('No value specified!')\n ret = __execute_ret('set \\'{0}\\' \\'{1}\\''.format(property, value), host=host,\n admin_username=admin_username,\n admin_password=admin_password)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
system_info
|
python
|
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'])
|
Return System information
CLI Example:
.. code-block:: bash
salt dell dracr.system_info
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L280-L301
|
[
"def __parse_drac(output):\n '''\n Parse Dell DRAC output\n '''\n drac = {}\n section = ''\n\n for i in output.splitlines():\n if i.strip().endswith(':') and '=' not in i:\n section = i[0:-1]\n drac[section] = {}\n if i.rstrip() and '=' in i:\n if section in drac:\n drac[section].update(dict(\n [[prop.strip() for prop in i.split('=')]]\n ))\n else:\n section = i.strip()\n if section not in drac and section:\n drac[section] = {}\n\n return drac\n",
"def __execute_ret(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n if module == 'ALL':\n modswitch = '-a '\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n else:\n fmtlines = []\n for l in cmd['stdout'].splitlines():\n if l.startswith('Security Alert'):\n continue\n if l.startswith('RAC1168:'):\n break\n if l.startswith('RAC1169:'):\n break\n if l.startswith('Continuing execution'):\n continue\n\n if not l.strip():\n continue\n fmtlines.append(l)\n if '=' in l:\n continue\n cmd['stdout'] = '\\n'.join(fmtlines)\n\n return cmd\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
return ret
def set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
network_info
|
python
|
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'])
|
Return Network Configuration
CLI Example:
.. code-block:: bash
salt dell dracr.network_info
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L342-L380
|
[
"def inventory(host=None, admin_username=None, admin_password=None):\n def mapit(x, y):\n return {x: y}\n\n fields = {}\n fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',\n 'updateable']\n fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']\n fields['cmc'] = ['name', 'cmc_version', 'updateable']\n fields['chassis'] = ['name', 'fw_version', 'fqdd']\n\n rawinv = __execute_ret('getversion', host=host,\n admin_username=admin_username,\n admin_password=admin_password)\n\n if rawinv['retcode'] != 0:\n return rawinv\n\n in_server = False\n in_switch = False\n in_cmc = False\n in_chassis = False\n ret = {}\n ret['server'] = {}\n ret['switch'] = {}\n ret['cmc'] = {}\n ret['chassis'] = {}\n for l in rawinv['stdout'].splitlines():\n if l.startswith('<Server>'):\n in_server = True\n in_switch = False\n in_cmc = False\n in_chassis = False\n continue\n\n if l.startswith('<Switch>'):\n in_server = False\n in_switch = True\n in_cmc = False\n in_chassis = False\n continue\n\n if l.startswith('<CMC>'):\n in_server = False\n in_switch = False\n in_cmc = True\n in_chassis = False\n continue\n\n if l.startswith('<Chassis Infrastructure>'):\n in_server = False\n in_switch = False\n in_cmc = False\n in_chassis = True\n continue\n\n if not l:\n continue\n\n line = re.split(' +', l.strip())\n\n if in_server:\n ret['server'][line[0]] = dict(\n (k, v) for d in map(mapit, fields['server'], line) for (k, v)\n in d.items())\n if in_switch:\n ret['switch'][line[0]] = dict(\n (k, v) for d in map(mapit, fields['switch'], line) for (k, v)\n in d.items())\n if in_cmc:\n ret['cmc'][line[0]] = dict(\n (k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in\n d.items())\n if in_chassis:\n ret['chassis'][line[0]] = dict(\n (k, v) for d in map(mapit, fields['chassis'], line) for k, v in\n d.items())\n\n return ret\n",
"def __parse_drac(output):\n '''\n Parse Dell DRAC output\n '''\n drac = {}\n section = ''\n\n for i in output.splitlines():\n if i.strip().endswith(':') and '=' not in i:\n section = i[0:-1]\n drac[section] = {}\n if i.rstrip() and '=' in i:\n if section in drac:\n drac[section].update(dict(\n [[prop.strip() for prop in i.split('=')]]\n ))\n else:\n section = i.strip()\n if section not in drac and section:\n drac[section] = {}\n\n return drac\n",
"def __execute_ret(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n if module == 'ALL':\n modswitch = '-a '\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n else:\n fmtlines = []\n for l in cmd['stdout'].splitlines():\n if l.startswith('Security Alert'):\n continue\n if l.startswith('RAC1168:'):\n break\n if l.startswith('RAC1169:'):\n break\n if l.startswith('Continuing execution'):\n continue\n\n if not l.strip():\n continue\n fmtlines.append(l)\n if '=' in l:\n continue\n cmd['stdout'] = '\\n'.join(fmtlines)\n\n return cmd\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
nameservers
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L383-L413
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
syslog
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L416-L447
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
email_alerts
|
python
|
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')
|
Enable/Disable email alerts
CLI Example:
.. code-block:: bash
salt dell dracr.email_alerts True
salt dell dracr.email_alerts False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L450-L472
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
list_users
|
python
|
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
|
List all DRAC users
CLI Example:
.. code-block:: bash
salt dell dracr.list_users
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L475-L517
|
[
"def __execute_ret(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n if module == 'ALL':\n modswitch = '-a '\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n else:\n fmtlines = []\n for l in cmd['stdout'].splitlines():\n if l.startswith('Security Alert'):\n continue\n if l.startswith('RAC1168:'):\n break\n if l.startswith('RAC1169:'):\n break\n if l.startswith('Continuing execution'):\n continue\n\n if not l.strip():\n continue\n fmtlines.append(l)\n if '=' in l:\n continue\n cmd['stdout'] = '\\n'.join(fmtlines)\n\n return cmd\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
delete_user
|
python
|
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
|
Delete a user
CLI Example:
.. code-block:: bash
salt dell dracr.delete_user [USERNAME] [UID - optional]
salt dell dracr.delete_user diana 4
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L520-L547
|
[
"def list_users(host=None,\n admin_username=None,\n admin_password=None,\n module=None):\n '''\n List all DRAC users\n\n CLI Example:\n\n .. code-block:: bash\n\n salt dell dracr.list_users\n '''\n users = {}\n _username = ''\n\n for idx in range(1, 17):\n cmd = __execute_ret('getconfig -g '\n 'cfgUserAdmin -i {0}'.format(idx),\n host=host, admin_username=admin_username,\n admin_password=admin_password)\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n\n for user in cmd['stdout'].splitlines():\n if not user.startswith('cfg'):\n continue\n\n (key, val) = user.split('=')\n\n if key.startswith('cfgUserAdminUserName'):\n _username = val.strip()\n\n if val:\n users[_username] = {'index': idx}\n else:\n break\n else:\n if _username:\n users[_username].update({key: val})\n\n return users\n",
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
change_password
|
python
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L550-L588
|
[
"def list_users(host=None,\n admin_username=None,\n admin_password=None,\n module=None):\n '''\n List all DRAC users\n\n CLI Example:\n\n .. code-block:: bash\n\n salt dell dracr.list_users\n '''\n users = {}\n _username = ''\n\n for idx in range(1, 17):\n cmd = __execute_ret('getconfig -g '\n 'cfgUserAdmin -i {0}'.format(idx),\n host=host, admin_username=admin_username,\n admin_password=admin_password)\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n\n for user in cmd['stdout'].splitlines():\n if not user.startswith('cfg'):\n continue\n\n (key, val) = user.split('=')\n\n if key.startswith('cfgUserAdminUserName'):\n _username = val.strip()\n\n if val:\n users[_username] = {'index': idx}\n else:\n break\n else:\n if _username:\n users[_username].update({key: val})\n\n return users\n",
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
deploy_password
|
python
|
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
)
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L591-L614
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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_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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
deploy_snmp
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L617-L636
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
set_snmp
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L763-L779
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
set_network
|
python
|
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
))
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L782-L799
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
server_power
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L802-L834
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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_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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
server_reboot
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L837-L869
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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_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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
server_poweroff
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L872-L901
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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_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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
server_poweron
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L904-L933
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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_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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
server_hardreset
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L936-L967
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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_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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
server_powerstatus
|
python
|
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
|
return the power status for the passed module
CLI Example:
.. code-block:: bash
salt dell drac.server_powerstatus
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L970-L999
|
[
"def __execute_ret(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n if module == 'ALL':\n modswitch = '-a '\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n else:\n fmtlines = []\n for l in cmd['stdout'].splitlines():\n if l.startswith('Security Alert'):\n continue\n if l.startswith('RAC1168:'):\n break\n if l.startswith('RAC1169:'):\n break\n if l.startswith('Continuing execution'):\n continue\n\n if not l.strip():\n continue\n fmtlines.append(l)\n if '=' in l:\n continue\n cmd['stdout'] = '\\n'.join(fmtlines)\n\n return cmd\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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_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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
server_pxe
|
python
|
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
|
Configure server to PXE perform a one off PXE boot
CLI Example:
.. code-block:: bash
salt dell dracr.server_pxe
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1002-L1026
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
list_slotnames
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1029-L1078
|
[
"def __execute_ret(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n if module == 'ALL':\n modswitch = '-a '\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n else:\n fmtlines = []\n for l in cmd['stdout'].splitlines():\n if l.startswith('Security Alert'):\n continue\n if l.startswith('RAC1168:'):\n break\n if l.startswith('RAC1169:'):\n break\n if l.startswith('Continuing execution'):\n continue\n\n if not l.strip():\n continue\n fmtlines.append(l)\n if '=' in l:\n continue\n cmd['stdout'] = '\\n'.join(fmtlines)\n\n return cmd\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
get_slotname
|
python
|
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']
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1081-L1110
|
[
"def list_slotnames(host=None,\n admin_username=None,\n admin_password=None):\n '''\n List the names of all slots in the chassis.\n\n host\n The chassis host.\n\n admin_username\n The username used to access the chassis.\n\n admin_password\n The password used to access the chassis.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call --local dracr.list_slotnames host=111.222.333.444\n admin_username=root admin_password=secret\n\n '''\n slotraw = __execute_ret('getslotname',\n host=host, admin_username=admin_username,\n admin_password=admin_password)\n\n if slotraw['retcode'] != 0:\n return slotraw\n slots = {}\n stripheader = True\n for l in slotraw['stdout'].splitlines():\n if l.startswith('<'):\n stripheader = False\n continue\n if stripheader:\n continue\n fields = l.split()\n slots[fields[0]] = {}\n slots[fields[0]]['slot'] = fields[0]\n if len(fields) > 1:\n slots[fields[0]]['slotname'] = fields[1]\n else:\n slots[fields[0]]['slotname'] = ''\n if len(fields) > 2:\n slots[fields[0]]['hostname'] = fields[2]\n else:\n slots[fields[0]]['hostname'] = ''\n\n return slots\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
set_slotname
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1113-L1143
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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_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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
set_chassis_name
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1146-L1175
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
get_chassis_name
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1178-L1201
|
[
"def bare_rac_cmd(cmd, host=None,\n admin_username=None, admin_password=None):\n ret = __execute_ret('{0}'.format(cmd),\n host=host,\n admin_username=admin_username,\n admin_password=admin_password)\n\n if ret['retcode'] == 0:\n return ret['stdout']\n else:\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
set_chassis_location
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1285-L1314
|
[
"def __execute_cmd(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n # -a takes 'server' or 'switch' to represent all servers\n # or all switches in a chassis. Allow\n # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'\n if module.startswith('ALL_'):\n modswitch = '-a '\\\n + module[module.index('_') + 1:len(module)].lower()\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return False\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
get_chassis_location
|
python
|
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']
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1317-L1342
|
[
"def system_info(host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Return System information\n\n CLI Example:\n\n .. code-block:: bash\n\n salt dell dracr.system_info\n '''\n cmd = __execute_ret('getsysinfo', host=host,\n admin_username=admin_username,\n admin_password=admin_password,\n module=module)\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n return cmd\n\n return __parse_drac(cmd['stdout'])\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
set_chassis_datacenter
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1345-L1374
|
[
"def set_general(cfg_sec, cfg_var, val, host=None,\n admin_username=None, admin_password=None):\n return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,\n cfg_var, val),\n host=host,\n admin_username=admin_username,\n admin_password=admin_password)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
get_chassis_datacenter
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1377-L1401
|
[
"def get_general(cfg_sec, cfg_var, host=None,\n admin_username=None, admin_password=None):\n ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),\n host=host,\n admin_username=admin_username,\n admin_password=admin_password)\n\n if ret['retcode'] == 0:\n return ret['stdout']\n else:\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
idrac_general
|
python
|
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
|
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'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1426-L1469
|
[
"def network_info(host=None,\n admin_username=None,\n admin_password=None,\n module=None):\n '''\n Return Network Configuration\n\n CLI Example:\n\n .. code-block:: bash\n\n salt dell dracr.network_info\n '''\n\n inv = inventory(host=host, admin_username=admin_username,\n admin_password=admin_password)\n if inv is None:\n cmd = {}\n cmd['retcode'] = -1\n cmd['stdout'] = 'Problem getting switch inventory'\n return cmd\n\n if module not in inv.get('switch') and module not in inv.get('server'):\n cmd = {}\n cmd['retcode'] = -1\n cmd['stdout'] = 'No module {0} found.'.format(module)\n return cmd\n\n cmd = __execute_ret('getniccfg', host=host,\n admin_username=admin_username,\n admin_password=admin_password,\n module=module)\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n\n cmd['stdout'] = 'Network:\\n' + 'Device = ' + module + '\\n' + \\\n cmd['stdout']\n return __parse_drac(cmd['stdout'])\n",
"def __execute_ret(command, host=None,\n admin_username=None, admin_password=None,\n module=None):\n '''\n Execute rac commands\n '''\n if module:\n if module == 'ALL':\n modswitch = '-a '\n else:\n modswitch = '-m {0}'.format(module)\n else:\n modswitch = ''\n if not host:\n # This is a local call\n cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,\n modswitch))\n else:\n cmd = __salt__['cmd.run_all'](\n 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,\n admin_username,\n admin_password,\n command,\n modswitch),\n output_loglevel='quiet')\n\n if cmd['retcode'] != 0:\n log.warning('racadm returned an exit code of %s', cmd['retcode'])\n else:\n fmtlines = []\n for l in cmd['stdout'].splitlines():\n if l.startswith('Security Alert'):\n continue\n if l.startswith('RAC1168:'):\n break\n if l.startswith('RAC1169:'):\n break\n if l.startswith('Continuing execution'):\n continue\n\n if not l.strip():\n continue\n fmtlines.append(l)\n if '=' in l:\n continue\n cmd['stdout'] = '\\n'.join(fmtlines)\n\n return cmd\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def _update_firmware(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
update_firmware
|
python
|
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))
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1506-L1532
|
[
"def _update_firmware(cmd,\n host=None,\n admin_username=None,\n admin_password=None):\n\n if not admin_username:\n admin_username = __pillar__['proxy']['admin_username']\n if not admin_username:\n admin_password = __pillar__['proxy']['admin_password']\n\n ret = __execute_ret(cmd,\n host=host,\n admin_username=admin_username,\n admin_password=admin_password)\n\n if ret['retcode'] == 0:\n return ret['stdout']\n else:\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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 get_idrac_nic()
|
saltstack/salt
|
salt/modules/dracr.py
|
update_firmware_nfs_or_cifs
|
python
|
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))
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dracr.py#L1535-L1577
|
[
"def _update_firmware(cmd,\n host=None,\n admin_username=None,\n admin_password=None):\n\n if not admin_username:\n admin_username = __pillar__['proxy']['admin_username']\n if not admin_username:\n admin_password = __pillar__['proxy']['admin_password']\n\n ret = __execute_ret(cmd,\n host=host,\n admin_username=admin_username,\n admin_password=admin_password)\n\n if ret['retcode'] == 0:\n return ret['stdout']\n else:\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC
.. versionadded:: 2015.8.2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltException
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__proxyenabled__ = ['fx2']
try:
run_all = __salt__['cmd.run_all']
except (NameError, KeyError):
import salt.modules.cmdmod
__salt__ = {
'cmd.run_all': salt.modules.cmdmod.run_all
}
def __virtual__():
if salt.utils.path.which('racadm'):
return True
return (False, 'The drac execution module cannot be loaded: racadm binary not in path.')
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 get_dns_dracname(host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host,
admin_username=admin_username,
admin_password=admin_password)
parsed = __parse_drac(ret['stdout'])
return parsed
def set_dns_dracname(name,
host=None,
admin_username=None,
admin_password=None):
ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name),
host=host,
admin_username=admin_username,
admin_password=admin_password)
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 set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg '
if dhcp:
cmdstr += '-d '
else:
cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway
return __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
def set_nicvlan(vlan=None,
host=None,
admin_username=None,
admin_password=None,
module=None):
cmdstr = 'setniccfg -v '
if vlan:
cmdstr += vlan
ret = __execute_cmd(cmdstr, host=host,
admin_username=admin_username,
admin_password=admin_password,
module=module)
return ret
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 create_user(username, password, permissions,
users=None, host=None,
admin_username=None, admin_password=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell dracr.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
_uids = set()
if users is None:
users = list_users()
if username in users:
log.warning('racadm: user \'%s\' already exists', username)
return False
for idx in six.iterkeys(users):
_uids.add(users[idx]['index'])
uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop()
# Create user account first
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminUserName -i {0} {1}'
.format(uid, username),
host=host, admin_username=admin_username,
admin_password=admin_password):
delete_user(username, uid)
return False
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warning('unable to set user password')
delete_user(username, uid)
return False
# Enable users admin
if not __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminEnable -i {0} 1'.format(uid)):
delete_user(username, uid)
return False
return True
def set_permissions(username, permissions,
uid=None, host=None,
admin_username=None, admin_password=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell dracr.set_permissions [USERNAME] [PRIVILEGES]
[USER INDEX - optional]
salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileges
* login : Login to iDRAC
* drac : Configure iDRAC
* user_management : Configure Users
* clear_logs : Clear Logs
* server_control_commands : Execute Server Control Commands
* console_redirection : Access Console Redirection
* virtual_media : Access Virtual Media
* test_alerts : Test Alerts
* debug_commands : Execute Debug Commands
'''
privileges = {'login': '0x0000001',
'drac': '0x0000002',
'user_management': '0x0000004',
'clear_logs': '0x0000008',
'server_control_commands': '0x0000010',
'console_redirection': '0x0000020',
'virtual_media': '0x0000040',
'test_alerts': '0x0000080',
'debug_commands': '0x0000100'}
permission = 0
# When users don't provide a user ID we need to search for this
if uid is None:
user = list_users()
uid = user[username]['index']
# Generate privilege bit mask
for i in permissions.split(','):
perm = i.strip()
if perm in privileges:
permission += int(privileges[perm], 16)
return __execute_cmd('config -g cfgUserAdmin -o '
'cfgUserAdminPrivilege -i {0} 0x{1:08X}'
.format(uid, permission),
host=host, admin_username=admin_username,
admin_password=admin_password)
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 inventory(host=None, admin_username=None, admin_password=None):
def mapit(x, y):
return {x: y}
fields = {}
fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen',
'updateable']
fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version']
fields['cmc'] = ['name', 'cmc_version', 'updateable']
fields['chassis'] = ['name', 'fw_version', 'fqdd']
rawinv = __execute_ret('getversion', host=host,
admin_username=admin_username,
admin_password=admin_password)
if rawinv['retcode'] != 0:
return rawinv
in_server = False
in_switch = False
in_cmc = False
in_chassis = False
ret = {}
ret['server'] = {}
ret['switch'] = {}
ret['cmc'] = {}
ret['chassis'] = {}
for l in rawinv['stdout'].splitlines():
if l.startswith('<Server>'):
in_server = True
in_switch = False
in_cmc = False
in_chassis = False
continue
if l.startswith('<Switch>'):
in_server = False
in_switch = True
in_cmc = False
in_chassis = False
continue
if l.startswith('<CMC>'):
in_server = False
in_switch = False
in_cmc = True
in_chassis = False
continue
if l.startswith('<Chassis Infrastructure>'):
in_server = False
in_switch = False
in_cmc = False
in_chassis = True
continue
if not l:
continue
line = re.split(' +', l.strip())
if in_server:
ret['server'][line[0]] = dict(
(k, v) for d in map(mapit, fields['server'], line) for (k, v)
in d.items())
if in_switch:
ret['switch'][line[0]] = dict(
(k, v) for d in map(mapit, fields['switch'], line) for (k, v)
in d.items())
if in_cmc:
ret['cmc'][line[0]] = dict(
(k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in
d.items())
if in_chassis:
ret['chassis'][line[0]] = dict(
(k, v) for d in map(mapit, fields['chassis'], line) for k, v in
d.items())
return ret
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 set_general(cfg_sec, cfg_var, val, host=None,
admin_username=None, admin_password=None):
return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec,
cfg_var, val),
host=host,
admin_username=admin_username,
admin_password=admin_password)
def get_general(cfg_sec, cfg_var, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var),
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
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(cmd,
host=None,
admin_username=None,
admin_password=None):
if not admin_username:
admin_username = __pillar__['proxy']['admin_username']
if not admin_username:
admin_password = __pillar__['proxy']['admin_password']
ret = __execute_ret(cmd,
host=host,
admin_username=admin_username,
admin_password=admin_password)
if ret['retcode'] == 0:
return ret['stdout']
else:
return ret
def bare_rac_cmd(cmd, host=None,
admin_username=None, admin_password=None):
ret = __execute_ret('{0}'.format(cmd),
host=host,
admin_username=admin_username,
admin_password=admin_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 get_idrac_nic()
|
saltstack/salt
|
salt/states/msteams.py
|
post_card
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/msteams.py#L39-L99
| null |
# -*- coding: utf-8 -*-
'''
Send a message card to Microsoft Teams
======================================
This state is useful for sending messages to Teams during state runs.
.. versionadded:: 2017.7.0
.. code-block:: yaml
teams-message:
msteams.post_card:
- message: 'This state was executed successfully.'
- hook_url: https://outlook.office.com/webhook/837
The hook_url can be specified in the master or minion configuration like below:
.. code-block:: yaml
msteams:
hook_url: https://outlook.office.com/webhook/837
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
from salt.exceptions import SaltInvocationError
def __virtual__():
'''
Only load if the msteams module is available in __salt__
'''
return 'msteams' if 'msteams.post_card' in __salt__ else False
|
saltstack/salt
|
salt/wheel/key.py
|
accept_dict
|
python
|
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)
|
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']}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/key.py#L121-L158
|
[
"def get_key(opts):\n return Key(opts)\n",
"def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):\n '''\n Accept public keys. If \"match\" is passed, it is evaluated as a glob.\n Pre-gathered matches can also be passed via \"match_dict\".\n '''\n if match is not None:\n matches = self.name_match(match)\n elif match_dict is not None and isinstance(match_dict, dict):\n matches = match_dict\n else:\n matches = {}\n keydirs = [self.PEND]\n if include_rejected:\n keydirs.append(self.REJ)\n if include_denied:\n keydirs.append(self.DEN)\n for keydir in keydirs:\n for key in matches.get(keydir, []):\n try:\n shutil.move(\n os.path.join(\n self.opts['pki_dir'],\n keydir,\n key),\n os.path.join(\n self.opts['pki_dir'],\n self.ACC,\n key)\n )\n eload = {'result': True,\n 'act': 'accept',\n 'id': key}\n self.event.fire_event(eload,\n salt.utils.event.tagify(prefix='key'))\n except (IOError, OSError):\n pass\n return (\n self.name_match(match) if match is not None\n else self.dict_match(matches)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Wheel system wrapper for the Salt key system to be used in interactions with
the Salt Master programmatically.
The key module for the wheel system is meant to provide an internal interface
for other Salt systems to interact with the Salt Master. The following usage
examples assume that a WheelClient is available:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
Note that importing and using the ``WheelClient`` must be performed on the same
machine as the Salt Master and as the same user that runs the Salt Master,
unless :conf_master:`external_auth` is configured and the user is authorized
to execute wheel functions.
The function documentation starts with the ``wheel`` reference from the code
sample above and use the :py:class:`WheelClient` functions to show how they can
be called from a Python interpreter.
The wheel key functions can also be called via a ``salt`` command at the CLI
using the :mod:`saltutil execution module <salt.modules.saltutil>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import hashlib
import logging
# Import salt libs
from salt.key import get_key
import salt.crypt
import salt.utils.crypt
import salt.utils.files
import salt.utils.platform
from salt.utils.sanitizers import clean
__func_alias__ = {
'list_': 'list',
'key_str': 'print',
}
log = logging.getLogger(__name__)
def list_(match):
'''
List all the keys under a named status. Returns a dictionary.
match
The type of keys to list. The ``pre``, ``un``, and ``unaccepted``
options will list unaccepted/unsigned keys. ``acc`` or ``accepted`` will
list accepted/signed keys. ``rej`` or ``rejected`` will list rejected keys.
Finally, ``all`` will list all keys.
.. code-block:: python
>>> wheel.cmd('key.list', ['accepted'])
{'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.list_status(match)
def list_all():
'''
List all the keys. Returns a dictionary containing lists of the minions in
each salt-key category, including ``minions``, ``minions_rejected``,
``minions_denied``, etc. Returns a dictionary.
.. code-block:: python
>>> wheel.cmd('key.list_all')
{'local': ['master.pem', 'master.pub'], 'minions_rejected': [],
'minions_denied': [], 'minions_pre': [],
'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.all_keys()
def name_match(match):
'''
List all the keys based on a glob match
'''
skey = get_key(__opts__)
return skey.name_match(match)
def accept(match, include_rejected=False, include_denied=False):
'''
Accept keys based on a glob match. Returns a dictionary.
match
The glob match of keys to accept.
include_rejected
To include rejected 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('key.accept', ['minion1'])
{'minions': ['minion1']}
'''
skey = get_key(__opts__)
return skey.accept(match, include_rejected=include_rejected, include_denied=include_denied)
def delete(match):
'''
Delete keys based on a glob match. Returns a dictionary.
match
The glob match of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete', 'match': 'minion1'})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match)
def delete_dict(match):
'''
Delete keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match_dict=match)
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 reject_dict(match, include_accepted=False, include_denied=False):
'''
Reject keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to reject.
include_accepted
To include accepted 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
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.reject_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.reject(match_dict=match,
include_accepted=include_accepted,
include_denied=include_denied)
def key_str(match):
r'''
Return information about the key. Returns a dictionary.
match
The key to return information about.
.. code-block:: python
>>> wheel.cmd('key.key_str', ['minion1'])
{'minions': {'minion1': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0B
...
TWugEQpPt\niQIDAQAB\n-----END PUBLIC KEY-----'}}
'''
skey = get_key(__opts__)
return skey.key_str(match)
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)
|
saltstack/salt
|
salt/wheel/key.py
|
reject
|
python
|
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)
|
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'}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/key.py#L200-L221
|
[
"def get_key(opts):\n return Key(opts)\n",
"def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):\n '''\n Reject public keys. If \"match\" is passed, it is evaluated as a glob.\n Pre-gathered matches can also be passed via \"match_dict\".\n '''\n if match is not None:\n matches = self.name_match(match)\n elif match_dict is not None and isinstance(match_dict, dict):\n matches = match_dict\n else:\n matches = {}\n keydirs = [self.PEND]\n if include_accepted:\n keydirs.append(self.ACC)\n if include_denied:\n keydirs.append(self.DEN)\n for keydir in keydirs:\n for key in matches.get(keydir, []):\n try:\n shutil.move(\n os.path.join(\n self.opts['pki_dir'],\n keydir,\n key),\n os.path.join(\n self.opts['pki_dir'],\n self.REJ,\n key)\n )\n eload = {'result': True,\n 'act': 'reject',\n 'id': key}\n self.event.fire_event(eload,\n salt.utils.event.tagify(prefix='key'))\n except (IOError, OSError):\n pass\n self.check_minion_cache()\n if self.opts.get('rotate_aes_key'):\n salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])\n return (\n self.name_match(match) if match is not None\n else self.dict_match(matches)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Wheel system wrapper for the Salt key system to be used in interactions with
the Salt Master programmatically.
The key module for the wheel system is meant to provide an internal interface
for other Salt systems to interact with the Salt Master. The following usage
examples assume that a WheelClient is available:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
Note that importing and using the ``WheelClient`` must be performed on the same
machine as the Salt Master and as the same user that runs the Salt Master,
unless :conf_master:`external_auth` is configured and the user is authorized
to execute wheel functions.
The function documentation starts with the ``wheel`` reference from the code
sample above and use the :py:class:`WheelClient` functions to show how they can
be called from a Python interpreter.
The wheel key functions can also be called via a ``salt`` command at the CLI
using the :mod:`saltutil execution module <salt.modules.saltutil>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import hashlib
import logging
# Import salt libs
from salt.key import get_key
import salt.crypt
import salt.utils.crypt
import salt.utils.files
import salt.utils.platform
from salt.utils.sanitizers import clean
__func_alias__ = {
'list_': 'list',
'key_str': 'print',
}
log = logging.getLogger(__name__)
def list_(match):
'''
List all the keys under a named status. Returns a dictionary.
match
The type of keys to list. The ``pre``, ``un``, and ``unaccepted``
options will list unaccepted/unsigned keys. ``acc`` or ``accepted`` will
list accepted/signed keys. ``rej`` or ``rejected`` will list rejected keys.
Finally, ``all`` will list all keys.
.. code-block:: python
>>> wheel.cmd('key.list', ['accepted'])
{'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.list_status(match)
def list_all():
'''
List all the keys. Returns a dictionary containing lists of the minions in
each salt-key category, including ``minions``, ``minions_rejected``,
``minions_denied``, etc. Returns a dictionary.
.. code-block:: python
>>> wheel.cmd('key.list_all')
{'local': ['master.pem', 'master.pub'], 'minions_rejected': [],
'minions_denied': [], 'minions_pre': [],
'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.all_keys()
def name_match(match):
'''
List all the keys based on a glob match
'''
skey = get_key(__opts__)
return skey.name_match(match)
def accept(match, include_rejected=False, include_denied=False):
'''
Accept keys based on a glob match. Returns a dictionary.
match
The glob match of keys to accept.
include_rejected
To include rejected 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('key.accept', ['minion1'])
{'minions': ['minion1']}
'''
skey = get_key(__opts__)
return skey.accept(match, include_rejected=include_rejected, include_denied=include_denied)
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 delete(match):
'''
Delete keys based on a glob match. Returns a dictionary.
match
The glob match of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete', 'match': 'minion1'})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match)
def delete_dict(match):
'''
Delete keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match_dict=match)
def reject_dict(match, include_accepted=False, include_denied=False):
'''
Reject keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to reject.
include_accepted
To include accepted 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
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.reject_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.reject(match_dict=match,
include_accepted=include_accepted,
include_denied=include_denied)
def key_str(match):
r'''
Return information about the key. Returns a dictionary.
match
The key to return information about.
.. code-block:: python
>>> wheel.cmd('key.key_str', ['minion1'])
{'minions': {'minion1': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0B
...
TWugEQpPt\niQIDAQAB\n-----END PUBLIC KEY-----'}}
'''
skey = get_key(__opts__)
return skey.key_str(match)
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)
|
saltstack/salt
|
salt/wheel/key.py
|
finger
|
python
|
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)
|
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'}}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/key.py#L279-L299
|
[
"def get_key(opts):\n return Key(opts)\n",
"def finger(self, match, hash_type=None):\n '''\n Return the fingerprint for a specified key\n '''\n if hash_type is None:\n hash_type = __opts__['hash_type']\n\n matches = self.name_match(match, True)\n ret = {}\n for status, keys in six.iteritems(matches):\n ret[status] = {}\n for key in keys:\n if status == 'local':\n path = os.path.join(self.opts['pki_dir'], key)\n else:\n path = os.path.join(self.opts['pki_dir'], status, key)\n ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Wheel system wrapper for the Salt key system to be used in interactions with
the Salt Master programmatically.
The key module for the wheel system is meant to provide an internal interface
for other Salt systems to interact with the Salt Master. The following usage
examples assume that a WheelClient is available:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
Note that importing and using the ``WheelClient`` must be performed on the same
machine as the Salt Master and as the same user that runs the Salt Master,
unless :conf_master:`external_auth` is configured and the user is authorized
to execute wheel functions.
The function documentation starts with the ``wheel`` reference from the code
sample above and use the :py:class:`WheelClient` functions to show how they can
be called from a Python interpreter.
The wheel key functions can also be called via a ``salt`` command at the CLI
using the :mod:`saltutil execution module <salt.modules.saltutil>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import hashlib
import logging
# Import salt libs
from salt.key import get_key
import salt.crypt
import salt.utils.crypt
import salt.utils.files
import salt.utils.platform
from salt.utils.sanitizers import clean
__func_alias__ = {
'list_': 'list',
'key_str': 'print',
}
log = logging.getLogger(__name__)
def list_(match):
'''
List all the keys under a named status. Returns a dictionary.
match
The type of keys to list. The ``pre``, ``un``, and ``unaccepted``
options will list unaccepted/unsigned keys. ``acc`` or ``accepted`` will
list accepted/signed keys. ``rej`` or ``rejected`` will list rejected keys.
Finally, ``all`` will list all keys.
.. code-block:: python
>>> wheel.cmd('key.list', ['accepted'])
{'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.list_status(match)
def list_all():
'''
List all the keys. Returns a dictionary containing lists of the minions in
each salt-key category, including ``minions``, ``minions_rejected``,
``minions_denied``, etc. Returns a dictionary.
.. code-block:: python
>>> wheel.cmd('key.list_all')
{'local': ['master.pem', 'master.pub'], 'minions_rejected': [],
'minions_denied': [], 'minions_pre': [],
'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.all_keys()
def name_match(match):
'''
List all the keys based on a glob match
'''
skey = get_key(__opts__)
return skey.name_match(match)
def accept(match, include_rejected=False, include_denied=False):
'''
Accept keys based on a glob match. Returns a dictionary.
match
The glob match of keys to accept.
include_rejected
To include rejected 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('key.accept', ['minion1'])
{'minions': ['minion1']}
'''
skey = get_key(__opts__)
return skey.accept(match, include_rejected=include_rejected, include_denied=include_denied)
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 delete(match):
'''
Delete keys based on a glob match. Returns a dictionary.
match
The glob match of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete', 'match': 'minion1'})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match)
def delete_dict(match):
'''
Delete keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match_dict=match)
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 reject_dict(match, include_accepted=False, include_denied=False):
'''
Reject keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to reject.
include_accepted
To include accepted 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
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.reject_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.reject(match_dict=match,
include_accepted=include_accepted,
include_denied=include_denied)
def key_str(match):
r'''
Return information about the key. Returns a dictionary.
match
The key to return information about.
.. code-block:: python
>>> wheel.cmd('key.key_str', ['minion1'])
{'minions': {'minion1': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0B
...
TWugEQpPt\niQIDAQAB\n-----END PUBLIC KEY-----'}}
'''
skey = get_key(__opts__)
return skey.key_str(match)
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)
|
saltstack/salt
|
salt/wheel/key.py
|
finger_master
|
python
|
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}}
|
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'}}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/key.py#L302-L320
|
[
"def pem_finger(path=None, key=None, sum_type='sha256'):\n '''\n Pass in either a raw pem string, or the path on disk to the location of a\n pem file, and the type of cryptographic hash to use. The default is SHA256.\n The fingerprint of the pem will be returned.\n\n If neither a key nor a path are passed in, a blank string will be returned.\n '''\n if not key:\n if not os.path.isfile(path):\n return ''\n\n with salt.utils.files.fopen(path, 'rb') as fp_:\n key = b''.join([x for x in fp_.readlines() if x.strip()][1:-1])\n\n pre = getattr(hashlib, sum_type)(key).hexdigest()\n finger = ''\n for ind, _ in enumerate(pre):\n if ind % 2:\n # Is odd\n finger += '{0}:'.format(pre[ind])\n else:\n finger += pre[ind]\n return finger.rstrip(':')\n"
] |
# -*- coding: utf-8 -*-
'''
Wheel system wrapper for the Salt key system to be used in interactions with
the Salt Master programmatically.
The key module for the wheel system is meant to provide an internal interface
for other Salt systems to interact with the Salt Master. The following usage
examples assume that a WheelClient is available:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
Note that importing and using the ``WheelClient`` must be performed on the same
machine as the Salt Master and as the same user that runs the Salt Master,
unless :conf_master:`external_auth` is configured and the user is authorized
to execute wheel functions.
The function documentation starts with the ``wheel`` reference from the code
sample above and use the :py:class:`WheelClient` functions to show how they can
be called from a Python interpreter.
The wheel key functions can also be called via a ``salt`` command at the CLI
using the :mod:`saltutil execution module <salt.modules.saltutil>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import hashlib
import logging
# Import salt libs
from salt.key import get_key
import salt.crypt
import salt.utils.crypt
import salt.utils.files
import salt.utils.platform
from salt.utils.sanitizers import clean
__func_alias__ = {
'list_': 'list',
'key_str': 'print',
}
log = logging.getLogger(__name__)
def list_(match):
'''
List all the keys under a named status. Returns a dictionary.
match
The type of keys to list. The ``pre``, ``un``, and ``unaccepted``
options will list unaccepted/unsigned keys. ``acc`` or ``accepted`` will
list accepted/signed keys. ``rej`` or ``rejected`` will list rejected keys.
Finally, ``all`` will list all keys.
.. code-block:: python
>>> wheel.cmd('key.list', ['accepted'])
{'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.list_status(match)
def list_all():
'''
List all the keys. Returns a dictionary containing lists of the minions in
each salt-key category, including ``minions``, ``minions_rejected``,
``minions_denied``, etc. Returns a dictionary.
.. code-block:: python
>>> wheel.cmd('key.list_all')
{'local': ['master.pem', 'master.pub'], 'minions_rejected': [],
'minions_denied': [], 'minions_pre': [],
'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.all_keys()
def name_match(match):
'''
List all the keys based on a glob match
'''
skey = get_key(__opts__)
return skey.name_match(match)
def accept(match, include_rejected=False, include_denied=False):
'''
Accept keys based on a glob match. Returns a dictionary.
match
The glob match of keys to accept.
include_rejected
To include rejected 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('key.accept', ['minion1'])
{'minions': ['minion1']}
'''
skey = get_key(__opts__)
return skey.accept(match, include_rejected=include_rejected, include_denied=include_denied)
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 delete(match):
'''
Delete keys based on a glob match. Returns a dictionary.
match
The glob match of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete', 'match': 'minion1'})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match)
def delete_dict(match):
'''
Delete keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match_dict=match)
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 reject_dict(match, include_accepted=False, include_denied=False):
'''
Reject keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to reject.
include_accepted
To include accepted 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
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.reject_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.reject(match_dict=match,
include_accepted=include_accepted,
include_denied=include_denied)
def key_str(match):
r'''
Return information about the key. Returns a dictionary.
match
The key to return information about.
.. code-block:: python
>>> wheel.cmd('key.key_str', ['minion1'])
{'minions': {'minion1': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0B
...
TWugEQpPt\niQIDAQAB\n-----END PUBLIC KEY-----'}}
'''
skey = get_key(__opts__)
return skey.key_str(match)
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 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)
|
saltstack/salt
|
salt/wheel/key.py
|
gen
|
python
|
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
|
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-----'}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/key.py#L323-L371
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def gen_keys(keydir, keyname, keysize, user=None, passphrase=None):\n '''\n Generate a RSA public keypair for use with salt\n\n :param str keydir: The directory to write the keypair to\n :param str keyname: The type of salt server for whom this key should be written. (i.e. 'master' or 'minion')\n :param int keysize: The number of bits in the key\n :param str user: The user on the system who should own this keypair\n :param str passphrase: The passphrase which should be used to encrypt the private key\n\n :rtype: str\n :return: Path on the filesystem to the RSA private key\n '''\n base = os.path.join(keydir, keyname)\n priv = '{0}.pem'.format(base)\n pub = '{0}.pub'.format(base)\n\n if HAS_M2:\n gen = RSA.gen_key(keysize, 65537, lambda: None)\n else:\n salt.utils.crypt.reinit_crypto()\n gen = RSA.generate(bits=keysize, e=65537)\n if os.path.isfile(priv):\n # Between first checking and the generation another process has made\n # a key! Use the winner's key\n return priv\n\n # Do not try writing anything, if directory has no permissions.\n if not os.access(keydir, os.W_OK):\n raise IOError('Write access denied to \"{0}\" for user \"{1}\".'.format(os.path.abspath(keydir), getpass.getuser()))\n\n with salt.utils.files.set_umask(0o277):\n if HAS_M2:\n # if passphrase is empty or None use no cipher\n if not passphrase:\n gen.save_pem(priv, cipher=None)\n else:\n gen.save_pem(\n priv,\n cipher='des_ede3_cbc',\n callback=lambda x: salt.utils.stringutils.to_bytes(passphrase))\n else:\n with salt.utils.files.fopen(priv, 'wb+') as f:\n f.write(gen.exportKey('PEM', passphrase))\n if HAS_M2:\n gen.save_pub_key(pub)\n else:\n with salt.utils.files.fopen(pub, 'wb+') as f:\n f.write(gen.publickey().exportKey('PEM'))\n os.chmod(priv, 0o400)\n if user:\n try:\n import pwd\n uid = pwd.getpwnam(user).pw_uid\n os.chown(priv, uid, -1)\n os.chown(pub, uid, -1)\n except (KeyError, ImportError, OSError):\n # The specified user was not found, allow the backup systems to\n # report the error\n pass\n return priv\n",
"def filename(value):\n '''\n Remove everything that would affect paths in the filename\n\n :param value:\n :return:\n '''\n return re.sub('[^a-zA-Z0-9.-_ ]', '', os.path.basename(InputSanitizer.trim(value)))\n"
] |
# -*- coding: utf-8 -*-
'''
Wheel system wrapper for the Salt key system to be used in interactions with
the Salt Master programmatically.
The key module for the wheel system is meant to provide an internal interface
for other Salt systems to interact with the Salt Master. The following usage
examples assume that a WheelClient is available:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
Note that importing and using the ``WheelClient`` must be performed on the same
machine as the Salt Master and as the same user that runs the Salt Master,
unless :conf_master:`external_auth` is configured and the user is authorized
to execute wheel functions.
The function documentation starts with the ``wheel`` reference from the code
sample above and use the :py:class:`WheelClient` functions to show how they can
be called from a Python interpreter.
The wheel key functions can also be called via a ``salt`` command at the CLI
using the :mod:`saltutil execution module <salt.modules.saltutil>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import hashlib
import logging
# Import salt libs
from salt.key import get_key
import salt.crypt
import salt.utils.crypt
import salt.utils.files
import salt.utils.platform
from salt.utils.sanitizers import clean
__func_alias__ = {
'list_': 'list',
'key_str': 'print',
}
log = logging.getLogger(__name__)
def list_(match):
'''
List all the keys under a named status. Returns a dictionary.
match
The type of keys to list. The ``pre``, ``un``, and ``unaccepted``
options will list unaccepted/unsigned keys. ``acc`` or ``accepted`` will
list accepted/signed keys. ``rej`` or ``rejected`` will list rejected keys.
Finally, ``all`` will list all keys.
.. code-block:: python
>>> wheel.cmd('key.list', ['accepted'])
{'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.list_status(match)
def list_all():
'''
List all the keys. Returns a dictionary containing lists of the minions in
each salt-key category, including ``minions``, ``minions_rejected``,
``minions_denied``, etc. Returns a dictionary.
.. code-block:: python
>>> wheel.cmd('key.list_all')
{'local': ['master.pem', 'master.pub'], 'minions_rejected': [],
'minions_denied': [], 'minions_pre': [],
'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.all_keys()
def name_match(match):
'''
List all the keys based on a glob match
'''
skey = get_key(__opts__)
return skey.name_match(match)
def accept(match, include_rejected=False, include_denied=False):
'''
Accept keys based on a glob match. Returns a dictionary.
match
The glob match of keys to accept.
include_rejected
To include rejected 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('key.accept', ['minion1'])
{'minions': ['minion1']}
'''
skey = get_key(__opts__)
return skey.accept(match, include_rejected=include_rejected, include_denied=include_denied)
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 delete(match):
'''
Delete keys based on a glob match. Returns a dictionary.
match
The glob match of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete', 'match': 'minion1'})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match)
def delete_dict(match):
'''
Delete keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match_dict=match)
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 reject_dict(match, include_accepted=False, include_denied=False):
'''
Reject keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to reject.
include_accepted
To include accepted 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
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.reject_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.reject(match_dict=match,
include_accepted=include_accepted,
include_denied=include_denied)
def key_str(match):
r'''
Return information about the key. Returns a dictionary.
match
The key to return information about.
.. code-block:: python
>>> wheel.cmd('key.key_str', ['minion1'])
{'minions': {'minion1': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0B
...
TWugEQpPt\niQIDAQAB\n-----END PUBLIC KEY-----'}}
'''
skey = get_key(__opts__)
return skey.key_str(match)
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_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)
|
saltstack/salt
|
salt/wheel/key.py
|
gen_accept
|
python
|
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
|
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']}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/key.py#L374-L421
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def gen(id_=None, keysize=2048):\n r'''\n Generate a key pair. No keys are stored on the master. A key pair is\n returned as a dict containing pub and priv keys. Returns a dictionary\n containing the the ``pub`` and ``priv`` keys with their generated values.\n\n id\\_\n Set a name to generate a key pair for use with salt. If not specified,\n a random name will be specified.\n\n keysize\n The size of the key pair to generate. The size must be ``2048``, which\n is the default, or greater. If set to a value less than ``2048``, the\n key size will be rounded up to ``2048``.\n\n .. code-block:: python\n\n >>> wheel.cmd('key.gen')\n {'pub': '-----BEGIN PUBLIC KEY-----\\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBC\n ...\n BBPfamX9gGPQTpN9e8HwcZjXQnmg8OrcUl10WHw09SDWLOlnW+ueTWugEQpPt\\niQIDAQAB\\n\n -----END PUBLIC KEY-----',\n 'priv': '-----BEGIN RSA PRIVATE KEY-----\\nMIIEpAIBAAKCAQEA42Kf+w9XeZWgguzv\n ...\n QH3/W74X1+WTBlx4R2KGLYBiH+bCCFEQ/Zvcu4Xp4bIOPtRKozEQ==\\n\n -----END RSA PRIVATE KEY-----'}\n\n '''\n if id_ is None:\n id_ = hashlib.sha512(os.urandom(32)).hexdigest()\n else:\n id_ = clean.filename(id_)\n ret = {'priv': '',\n 'pub': ''}\n priv = salt.crypt.gen_keys(__opts__['pki_dir'], id_, keysize)\n pub = '{0}.pub'.format(priv[:priv.rindex('.')])\n with salt.utils.files.fopen(priv) as fp_:\n ret['priv'] = salt.utils.stringutils.to_unicode(fp_.read())\n with salt.utils.files.fopen(pub) as fp_:\n ret['pub'] = salt.utils.stringutils.to_unicode(fp_.read())\n\n # The priv key is given the Read-Only attribute. The causes `os.remove` to\n # fail in Windows.\n if salt.utils.platform.is_windows():\n os.chmod(priv, 128)\n\n os.remove(priv)\n os.remove(pub)\n return ret\n",
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def hostname(value):\n '''\n Clean value for RFC1123.\n\n :param value:\n :return:\n '''\n return re.sub(r'[^a-zA-Z0-9.-]', '', InputSanitizer.trim(value)).strip('.')\n"
] |
# -*- coding: utf-8 -*-
'''
Wheel system wrapper for the Salt key system to be used in interactions with
the Salt Master programmatically.
The key module for the wheel system is meant to provide an internal interface
for other Salt systems to interact with the Salt Master. The following usage
examples assume that a WheelClient is available:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
Note that importing and using the ``WheelClient`` must be performed on the same
machine as the Salt Master and as the same user that runs the Salt Master,
unless :conf_master:`external_auth` is configured and the user is authorized
to execute wheel functions.
The function documentation starts with the ``wheel`` reference from the code
sample above and use the :py:class:`WheelClient` functions to show how they can
be called from a Python interpreter.
The wheel key functions can also be called via a ``salt`` command at the CLI
using the :mod:`saltutil execution module <salt.modules.saltutil>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import hashlib
import logging
# Import salt libs
from salt.key import get_key
import salt.crypt
import salt.utils.crypt
import salt.utils.files
import salt.utils.platform
from salt.utils.sanitizers import clean
__func_alias__ = {
'list_': 'list',
'key_str': 'print',
}
log = logging.getLogger(__name__)
def list_(match):
'''
List all the keys under a named status. Returns a dictionary.
match
The type of keys to list. The ``pre``, ``un``, and ``unaccepted``
options will list unaccepted/unsigned keys. ``acc`` or ``accepted`` will
list accepted/signed keys. ``rej`` or ``rejected`` will list rejected keys.
Finally, ``all`` will list all keys.
.. code-block:: python
>>> wheel.cmd('key.list', ['accepted'])
{'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.list_status(match)
def list_all():
'''
List all the keys. Returns a dictionary containing lists of the minions in
each salt-key category, including ``minions``, ``minions_rejected``,
``minions_denied``, etc. Returns a dictionary.
.. code-block:: python
>>> wheel.cmd('key.list_all')
{'local': ['master.pem', 'master.pub'], 'minions_rejected': [],
'minions_denied': [], 'minions_pre': [],
'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.all_keys()
def name_match(match):
'''
List all the keys based on a glob match
'''
skey = get_key(__opts__)
return skey.name_match(match)
def accept(match, include_rejected=False, include_denied=False):
'''
Accept keys based on a glob match. Returns a dictionary.
match
The glob match of keys to accept.
include_rejected
To include rejected 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('key.accept', ['minion1'])
{'minions': ['minion1']}
'''
skey = get_key(__opts__)
return skey.accept(match, include_rejected=include_rejected, include_denied=include_denied)
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 delete(match):
'''
Delete keys based on a glob match. Returns a dictionary.
match
The glob match of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete', 'match': 'minion1'})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match)
def delete_dict(match):
'''
Delete keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match_dict=match)
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 reject_dict(match, include_accepted=False, include_denied=False):
'''
Reject keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to reject.
include_accepted
To include accepted 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
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.reject_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.reject(match_dict=match,
include_accepted=include_accepted,
include_denied=include_denied)
def key_str(match):
r'''
Return information about the key. Returns a dictionary.
match
The key to return information about.
.. code-block:: python
>>> wheel.cmd('key.key_str', ['minion1'])
{'minions': {'minion1': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0B
...
TWugEQpPt\niQIDAQAB\n-----END PUBLIC KEY-----'}}
'''
skey = get_key(__opts__)
return skey.key_str(match)
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_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)
|
saltstack/salt
|
salt/wheel/key.py
|
gen_keys
|
python
|
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)
|
Generate minion RSA public keypair
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/key.py#L424-L429
|
[
"def get_key(opts):\n return Key(opts)\n",
"def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):\n '''\n Generate minion RSA public keypair\n '''\n keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,\n keysize, user)\n salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)\n return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))\n"
] |
# -*- coding: utf-8 -*-
'''
Wheel system wrapper for the Salt key system to be used in interactions with
the Salt Master programmatically.
The key module for the wheel system is meant to provide an internal interface
for other Salt systems to interact with the Salt Master. The following usage
examples assume that a WheelClient is available:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
Note that importing and using the ``WheelClient`` must be performed on the same
machine as the Salt Master and as the same user that runs the Salt Master,
unless :conf_master:`external_auth` is configured and the user is authorized
to execute wheel functions.
The function documentation starts with the ``wheel`` reference from the code
sample above and use the :py:class:`WheelClient` functions to show how they can
be called from a Python interpreter.
The wheel key functions can also be called via a ``salt`` command at the CLI
using the :mod:`saltutil execution module <salt.modules.saltutil>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import hashlib
import logging
# Import salt libs
from salt.key import get_key
import salt.crypt
import salt.utils.crypt
import salt.utils.files
import salt.utils.platform
from salt.utils.sanitizers import clean
__func_alias__ = {
'list_': 'list',
'key_str': 'print',
}
log = logging.getLogger(__name__)
def list_(match):
'''
List all the keys under a named status. Returns a dictionary.
match
The type of keys to list. The ``pre``, ``un``, and ``unaccepted``
options will list unaccepted/unsigned keys. ``acc`` or ``accepted`` will
list accepted/signed keys. ``rej`` or ``rejected`` will list rejected keys.
Finally, ``all`` will list all keys.
.. code-block:: python
>>> wheel.cmd('key.list', ['accepted'])
{'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.list_status(match)
def list_all():
'''
List all the keys. Returns a dictionary containing lists of the minions in
each salt-key category, including ``minions``, ``minions_rejected``,
``minions_denied``, etc. Returns a dictionary.
.. code-block:: python
>>> wheel.cmd('key.list_all')
{'local': ['master.pem', 'master.pub'], 'minions_rejected': [],
'minions_denied': [], 'minions_pre': [],
'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.all_keys()
def name_match(match):
'''
List all the keys based on a glob match
'''
skey = get_key(__opts__)
return skey.name_match(match)
def accept(match, include_rejected=False, include_denied=False):
'''
Accept keys based on a glob match. Returns a dictionary.
match
The glob match of keys to accept.
include_rejected
To include rejected 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('key.accept', ['minion1'])
{'minions': ['minion1']}
'''
skey = get_key(__opts__)
return skey.accept(match, include_rejected=include_rejected, include_denied=include_denied)
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 delete(match):
'''
Delete keys based on a glob match. Returns a dictionary.
match
The glob match of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete', 'match': 'minion1'})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match)
def delete_dict(match):
'''
Delete keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match_dict=match)
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 reject_dict(match, include_accepted=False, include_denied=False):
'''
Reject keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to reject.
include_accepted
To include accepted 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
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.reject_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.reject(match_dict=match,
include_accepted=include_accepted,
include_denied=include_denied)
def key_str(match):
r'''
Return information about the key. Returns a dictionary.
match
The key to return information about.
.. code-block:: python
>>> wheel.cmd('key.key_str', ['minion1'])
{'minions': {'minion1': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0B
...
TWugEQpPt\niQIDAQAB\n-----END PUBLIC KEY-----'}}
'''
skey = get_key(__opts__)
return skey.key_str(match)
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_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)
|
saltstack/salt
|
salt/wheel/key.py
|
gen_signature
|
python
|
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)
|
Generate master public-key-signature
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/key.py#L432-L437
|
[
"def get_key(opts):\n return Key(opts)\n",
"def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):\n '''\n Generate master public-key-signature\n '''\n # check given pub-key\n if pub:\n if not os.path.isfile(pub):\n return 'Public-key {0} does not exist'.format(pub)\n # default to master.pub\n else:\n mpub = self.opts['pki_dir'] + '/' + 'master.pub'\n if os.path.isfile(mpub):\n pub = mpub\n\n # check given priv-key\n if priv:\n if not os.path.isfile(priv):\n return 'Private-key {0} does not exist'.format(priv)\n # default to master_sign.pem\n else:\n mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'\n if os.path.isfile(mpriv):\n priv = mpriv\n\n if not priv:\n if auto_create:\n log.debug(\n 'Generating new signing key-pair .%s.* in %s',\n self.opts['master_sign_key_name'], self.opts['pki_dir']\n )\n salt.crypt.gen_keys(self.opts['pki_dir'],\n self.opts['master_sign_key_name'],\n keysize or self.opts['keysize'],\n self.opts.get('user'),\n self.passphrase)\n\n priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'\n else:\n return 'No usable private-key found'\n\n if not pub:\n return 'No usable public-key found'\n\n log.debug('Using public-key %s', pub)\n log.debug('Using private-key %s', priv)\n\n if signature_path:\n if not os.path.isdir(signature_path):\n log.debug('target directory %s does not exist', signature_path)\n else:\n signature_path = self.opts['pki_dir']\n\n sign_path = signature_path + '/' + self.opts['master_pubkey_signature']\n\n skey = get_key(self.opts)\n return skey.gen_signature(priv, pub, sign_path)\n"
] |
# -*- coding: utf-8 -*-
'''
Wheel system wrapper for the Salt key system to be used in interactions with
the Salt Master programmatically.
The key module for the wheel system is meant to provide an internal interface
for other Salt systems to interact with the Salt Master. The following usage
examples assume that a WheelClient is available:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
Note that importing and using the ``WheelClient`` must be performed on the same
machine as the Salt Master and as the same user that runs the Salt Master,
unless :conf_master:`external_auth` is configured and the user is authorized
to execute wheel functions.
The function documentation starts with the ``wheel`` reference from the code
sample above and use the :py:class:`WheelClient` functions to show how they can
be called from a Python interpreter.
The wheel key functions can also be called via a ``salt`` command at the CLI
using the :mod:`saltutil execution module <salt.modules.saltutil>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import hashlib
import logging
# Import salt libs
from salt.key import get_key
import salt.crypt
import salt.utils.crypt
import salt.utils.files
import salt.utils.platform
from salt.utils.sanitizers import clean
__func_alias__ = {
'list_': 'list',
'key_str': 'print',
}
log = logging.getLogger(__name__)
def list_(match):
'''
List all the keys under a named status. Returns a dictionary.
match
The type of keys to list. The ``pre``, ``un``, and ``unaccepted``
options will list unaccepted/unsigned keys. ``acc`` or ``accepted`` will
list accepted/signed keys. ``rej`` or ``rejected`` will list rejected keys.
Finally, ``all`` will list all keys.
.. code-block:: python
>>> wheel.cmd('key.list', ['accepted'])
{'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.list_status(match)
def list_all():
'''
List all the keys. Returns a dictionary containing lists of the minions in
each salt-key category, including ``minions``, ``minions_rejected``,
``minions_denied``, etc. Returns a dictionary.
.. code-block:: python
>>> wheel.cmd('key.list_all')
{'local': ['master.pem', 'master.pub'], 'minions_rejected': [],
'minions_denied': [], 'minions_pre': [],
'minions': ['minion1', 'minion2', 'minion3']}
'''
skey = get_key(__opts__)
return skey.all_keys()
def name_match(match):
'''
List all the keys based on a glob match
'''
skey = get_key(__opts__)
return skey.name_match(match)
def accept(match, include_rejected=False, include_denied=False):
'''
Accept keys based on a glob match. Returns a dictionary.
match
The glob match of keys to accept.
include_rejected
To include rejected 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('key.accept', ['minion1'])
{'minions': ['minion1']}
'''
skey = get_key(__opts__)
return skey.accept(match, include_rejected=include_rejected, include_denied=include_denied)
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 delete(match):
'''
Delete keys based on a glob match. Returns a dictionary.
match
The glob match of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete', 'match': 'minion1'})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match)
def delete_dict(match):
'''
Delete keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to delete.
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.delete_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.delete_key(match_dict=match)
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 reject_dict(match, include_accepted=False, include_denied=False):
'''
Reject keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to reject.
include_accepted
To include accepted 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
.. code-block:: python
>>> wheel.cmd_async({'fun': 'key.reject_dict',
'match': {
'minions': [
'jerry',
'stuart',
'bob',
],
})
{'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
'''
skey = get_key(__opts__)
return skey.reject(match_dict=match,
include_accepted=include_accepted,
include_denied=include_denied)
def key_str(match):
r'''
Return information about the key. Returns a dictionary.
match
The key to return information about.
.. code-block:: python
>>> wheel.cmd('key.key_str', ['minion1'])
{'minions': {'minion1': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0B
...
TWugEQpPt\niQIDAQAB\n-----END PUBLIC KEY-----'}}
'''
skey = get_key(__opts__)
return skey.key_str(match)
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)
|
saltstack/salt
|
salt/modules/moosefs.py
|
dirinfo
|
python
|
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
|
Return information on a directory located on the Moose
CLI Example:
.. code-block:: bash
salt '*' moosefs.dirinfo /path/to/dir/ [-[n][h|H]]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/moosefs.py#L20-L43
| null |
# -*- coding: utf-8 -*-
'''
Module for gathering and managing information about MooseFS
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.path
def __virtual__():
'''
Only load if the mfs commands are installed
'''
if salt.utils.path.which('mfsgetgoal'):
return 'moosefs'
return (False, 'The moosefs execution module cannot be loaded: the mfsgetgoal binary is not in the path.')
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
|
saltstack/salt
|
salt/modules/moosefs.py
|
fileinfo
|
python
|
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
|
Return information on a file located on the Moose
CLI Example:
.. code-block:: bash
salt '*' moosefs.fileinfo /path/to/dir/
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/moosefs.py#L46-L89
| null |
# -*- coding: utf-8 -*-
'''
Module for gathering and managing information about MooseFS
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.path
def __virtual__():
'''
Only load if the mfs commands are installed
'''
if salt.utils.path.which('mfsgetgoal'):
return 'moosefs'
return (False, 'The moosefs execution module cannot be loaded: the mfsgetgoal binary is not in the path.')
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 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
|
saltstack/salt
|
salt/modules/moosefs.py
|
mounts
|
python
|
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
|
Return a list of current MooseFS mounts
CLI Example:
.. code-block:: bash
salt '*' moosefs.mounts
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/moosefs.py#L92-L124
| null |
# -*- coding: utf-8 -*-
'''
Module for gathering and managing information about MooseFS
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.path
def __virtual__():
'''
Only load if the mfs commands are installed
'''
if salt.utils.path.which('mfsgetgoal'):
return 'moosefs'
return (False, 'The moosefs execution module cannot be loaded: the mfsgetgoal binary is not in the path.')
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 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
|
saltstack/salt
|
salt/modules/moosefs.py
|
getgoal
|
python
|
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
|
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]]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/moosefs.py#L127-L164
| null |
# -*- coding: utf-8 -*-
'''
Module for gathering and managing information about MooseFS
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.path
def __virtual__():
'''
Only load if the mfs commands are installed
'''
if salt.utils.path.which('mfsgetgoal'):
return 'moosefs'
return (False, 'The moosefs execution module cannot be loaded: the mfsgetgoal binary is not in the path.')
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
|
saltstack/salt
|
salt/utils/win_lgpo_auditpol.py
|
_auditpol_cmd
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_auditpol.py#L108-L128
|
[
"def run_all(cmd,\n cwd=None,\n stdin=None,\n runas=None,\n group=None,\n shell=DEFAULT_SHELL,\n python_shell=None,\n env=None,\n clean_env=False,\n template=None,\n rstrip=True,\n umask=None,\n output_encoding=None,\n output_loglevel='debug',\n log_callback=None,\n hide_output=False,\n timeout=None,\n reset_system_locale=True,\n ignore_retcode=False,\n saltenv='base',\n use_vt=False,\n redirect_stderr=False,\n password=None,\n encoded_cmd=False,\n prepend_path=None,\n success_retcodes=None,\n success_stdout=None,\n success_stderr=None,\n **kwargs):\n '''\n Execute the passed command and return a dict of return data\n\n :param str cmd: The command to run. ex: ``ls -lart /home``\n\n :param str cwd: The directory from which to execute the command. Defaults\n to the home directory of the user specified by ``runas`` (or the user\n under which Salt is running if ``runas`` is not specified).\n\n :param str stdin: A string of standard input can be specified for the\n command to be run using the ``stdin`` parameter. This can be useful in\n cases where sensitive information must be read from standard input.\n\n :param str runas: Specify an alternate user to run the command. The default\n behavior is to run as the user under which Salt is running. If running\n on a Windows minion you must also use the ``password`` argument, and\n the target user account must be in the Administrators group.\n\n .. warning::\n\n For versions 2018.3.3 and above on macosx while using runas,\n to pass special characters to the command you need to escape\n the characters on the shell.\n\n Example:\n\n .. code-block:: bash\n\n cmd.run_all 'echo '\\\\''h=\\\\\"baz\\\\\"'\\\\\\''' runas=macuser\n\n :param str password: Windows only. Required when specifying ``runas``. This\n parameter will be ignored on non-Windows platforms.\n\n .. versionadded:: 2016.3.0\n\n :param str group: Group to run command as. Not currently supported\n on Windows.\n\n :param str shell: Specify an alternate shell. Defaults to the system's\n default shell.\n\n :param bool python_shell: If False, let python handle the positional\n arguments. Set to True to use shell features, such as pipes or\n redirection.\n\n :param dict env: Environment variables to be set prior to execution.\n\n .. note::\n When passing environment variables on the CLI, they should be\n passed as the string representation of a dictionary.\n\n .. code-block:: bash\n\n salt myminion cmd.run_all 'some command' env='{\"FOO\": \"bar\"}'\n\n :param bool clean_env: Attempt to clean out all other shell environment\n variables and set only those provided in the 'env' argument to this\n function.\n\n :param str prepend_path: $PATH segment to prepend (trailing ':' not\n necessary) to $PATH\n\n .. versionadded:: 2018.3.0\n\n :param str template: If this setting is applied then the named templating\n engine will be used to render the downloaded file. Currently jinja,\n mako, and wempy are supported.\n\n :param bool rstrip: Strip all whitespace off the end of output before it is\n returned.\n\n :param str umask: The umask (in octal) to use when running the command.\n\n :param str output_encoding: Control the encoding used to decode the\n command's output.\n\n .. note::\n This should not need to be used in most cases. By default, Salt\n will try to use the encoding detected from the system locale, and\n will fall back to UTF-8 if this fails. This should only need to be\n used in cases where the output of the command is encoded in\n something other than the system locale or UTF-8.\n\n To see the encoding Salt has detected from the system locale, check\n the `locale` line in the output of :py:func:`test.versions_report\n <salt.modules.test.versions_report>`.\n\n .. versionadded:: 2018.3.0\n\n :param str output_loglevel: Control the loglevel at which the output from\n the command is logged to the minion log.\n\n .. note::\n The command being run will still be logged at the ``debug``\n loglevel regardless, unless ``quiet`` is used for this value.\n\n :param bool ignore_retcode: If the exit code of the command is nonzero,\n this is treated as an error condition, and the output from the command\n will be logged to the minion log. However, there are some cases where\n programs use the return code for signaling and a nonzero exit code\n doesn't necessarily mean failure. Pass this argument as ``True`` to\n skip logging the output if the command has a nonzero exit code.\n\n :param bool hide_output: If ``True``, suppress stdout and stderr in the\n return data.\n\n .. note::\n This is separate from ``output_loglevel``, which only handles how\n Salt logs to the minion log.\n\n .. versionadded:: 2018.3.0\n\n :param int timeout: A timeout in seconds for the executed process to\n return.\n\n :param bool use_vt: Use VT utils (saltstack) to stream the command output\n more interactively to the console and the logs. This is experimental.\n\n :param bool encoded_cmd: Specify if the supplied command is encoded.\n Only applies to shell 'powershell'.\n\n .. versionadded:: 2018.3.0\n\n :param bool redirect_stderr: If set to ``True``, then stderr will be\n redirected to stdout. This is helpful for cases where obtaining both\n the retcode and output is desired, but it is not desired to have the\n output separated into both stdout and stderr.\n\n .. versionadded:: 2015.8.2\n\n :param str password: Windows only. Required when specifying ``runas``. This\n parameter will be ignored on non-Windows platforms.\n\n .. versionadded:: 2016.3.0\n\n :param bool bg: If ``True``, run command in background and do not await or\n deliver its results\n\n .. versionadded:: 2016.3.6\n\n :param list success_retcodes: This parameter will be allow a list of\n non-zero return codes that should be considered a success. If the\n return code returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: 2019.2.0\n\n :param list success_stdout: This parameter will be allow a list of\n strings that when found in standard out should be considered a success.\n If stdout returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: Neon\n\n :param list success_stderr: This parameter will be allow a list of\n strings that when found in standard error should be considered a success.\n If stderr returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: Neon\n\n :param bool stdin_raw_newlines: False\n If ``True``, Salt will not automatically convert the characters ``\\\\n``\n present in the ``stdin`` value to newlines.\n\n .. versionadded:: 2019.2.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cmd.run_all \"ls -l | awk '/foo/{print \\\\$2}'\"\n\n The template arg can be set to 'jinja' or another supported template\n engine to render the command arguments before execution.\n For example:\n\n .. code-block:: bash\n\n salt '*' cmd.run_all template=jinja \"ls -l /tmp/{{grains.id}} | awk '/foo/{print \\\\$2}'\"\n\n A string of standard input can be specified for the command to be run using\n the ``stdin`` parameter. This can be useful in cases where sensitive\n information must be read from standard input.\n\n .. code-block:: bash\n\n salt '*' cmd.run_all \"grep f\" stdin='one\\\\ntwo\\\\nthree\\\\nfour\\\\nfive\\\\n'\n '''\n python_shell = _python_shell_default(python_shell,\n kwargs.get('__pub_jid', ''))\n stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE\n ret = _run(cmd,\n runas=runas,\n group=group,\n cwd=cwd,\n stdin=stdin,\n stderr=stderr,\n shell=shell,\n python_shell=python_shell,\n env=env,\n clean_env=clean_env,\n prepend_path=prepend_path,\n template=template,\n rstrip=rstrip,\n umask=umask,\n output_encoding=output_encoding,\n output_loglevel=output_loglevel,\n log_callback=log_callback,\n timeout=timeout,\n reset_system_locale=reset_system_locale,\n ignore_retcode=ignore_retcode,\n saltenv=saltenv,\n use_vt=use_vt,\n password=password,\n encoded_cmd=encoded_cmd,\n success_retcodes=success_retcodes,\n success_stdout=success_stdout,\n success_stderr=success_stderr,\n **kwargs)\n\n if hide_output:\n ret['stdout'] = ret['stderr'] = ''\n return ret\n"
] |
# -*- coding: utf-8 -*-
r'''
A salt util for modifying the audit policies on the machine. This util is used
by the ``win_auditpol`` and ``win_lgpo`` modules.
Though this utility does not set group policy for auditing, it displays how all
auditing configuration is applied on the machine, either set directly or via
local or domain group policy.
.. versionadded:: 2018.3.4
.. versionadded:: 2019.2.1
This util allows you to view and modify the audit settings as they are applied
on the machine. The audit settings are broken down into nine categories:
- Account Logon
- Account Management
- Detailed Tracking
- DS Access
- Logon/Logoff
- Object Access
- Policy Change
- Privilege Use
- System
The ``get_settings`` function will return the subcategories for all nine of
the above categories in one dictionary along with their auditing status.
To modify a setting you only need to specify the subcategory name and the value
you wish to set. Valid settings are:
- No Auditing
- Success
- Failure
- Success and Failure
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")
# Get current state of the "Credential Validation" setting
salt.utils.win_lgpo_auditpol.get_setting(name='Credential Validation')
# 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')
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import re
import tempfile
# Import Salt libs
import salt.modules.cmdmod
import salt.utils.files
import salt.utils.platform
from salt.exceptions import CommandExecutionError
# Import 3rd Party libs
from salt.ext.six.moves import zip
log = logging.getLogger(__name__)
__virtualname__ = 'auditpol'
categories = ['Account Logon',
'Account Management',
'Detailed Tracking',
'DS Access',
'Logon/Logoff',
'Object Access',
'Policy Change',
'Privilege Use',
'System']
settings = {'No Auditing': '/success:disable /failure:disable',
'Success': '/success:enable /failure:disable',
'Failure': '/success:disable /failure:enable',
'Success and Failure': '/success:enable /failure:enable'}
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if on a Windows system
'''
if not salt.utils.platform.is_windows():
return False, 'This utility only available on Windows'
return __virtualname__
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 _get_valid_names():
if 'auditpol.valid_names' not in __context__:
settings = get_settings(category='All')
__context__['auditpol.valid_names'] = [k.lower() for k in settings]
return __context__['auditpol.valid_names']
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()
|
saltstack/salt
|
salt/utils/win_lgpo_auditpol.py
|
get_settings
|
python
|
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
|
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")
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_auditpol.py#L131-L189
|
[
"def _auditpol_cmd(cmd):\n '''\n Helper function for running the auditpol command\n\n Args:\n cmd (str): the auditpol command to run\n\n Returns:\n list: A list containing each line of the return (splitlines)\n\n Raises:\n CommandExecutionError: If the command encounters an error\n '''\n ret = salt.modules.cmdmod.run_all(cmd='auditpol {0}'.format(cmd),\n python_shell=True)\n if ret['retcode'] == 0:\n return ret['stdout'].splitlines()\n\n msg = 'Error executing auditpol command: {0}\\n'.format(cmd)\n msg += '\\n'.join(ret['stdout'])\n raise CommandExecutionError(msg)\n"
] |
# -*- coding: utf-8 -*-
r'''
A salt util for modifying the audit policies on the machine. This util is used
by the ``win_auditpol`` and ``win_lgpo`` modules.
Though this utility does not set group policy for auditing, it displays how all
auditing configuration is applied on the machine, either set directly or via
local or domain group policy.
.. versionadded:: 2018.3.4
.. versionadded:: 2019.2.1
This util allows you to view and modify the audit settings as they are applied
on the machine. The audit settings are broken down into nine categories:
- Account Logon
- Account Management
- Detailed Tracking
- DS Access
- Logon/Logoff
- Object Access
- Policy Change
- Privilege Use
- System
The ``get_settings`` function will return the subcategories for all nine of
the above categories in one dictionary along with their auditing status.
To modify a setting you only need to specify the subcategory name and the value
you wish to set. Valid settings are:
- No Auditing
- Success
- Failure
- Success and Failure
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")
# Get current state of the "Credential Validation" setting
salt.utils.win_lgpo_auditpol.get_setting(name='Credential Validation')
# 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')
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import re
import tempfile
# Import Salt libs
import salt.modules.cmdmod
import salt.utils.files
import salt.utils.platform
from salt.exceptions import CommandExecutionError
# Import 3rd Party libs
from salt.ext.six.moves import zip
log = logging.getLogger(__name__)
__virtualname__ = 'auditpol'
categories = ['Account Logon',
'Account Management',
'Detailed Tracking',
'DS Access',
'Logon/Logoff',
'Object Access',
'Policy Change',
'Privilege Use',
'System']
settings = {'No Auditing': '/success:disable /failure:disable',
'Success': '/success:enable /failure:disable',
'Failure': '/success:disable /failure:enable',
'Success and Failure': '/success:enable /failure:enable'}
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if on a Windows system
'''
if not salt.utils.platform.is_windows():
return False, 'This utility only available on Windows'
return __virtualname__
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_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 _get_valid_names():
if 'auditpol.valid_names' not in __context__:
settings = get_settings(category='All')
__context__['auditpol.valid_names'] = [k.lower() for k in settings]
return __context__['auditpol.valid_names']
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()
|
saltstack/salt
|
salt/utils/win_lgpo_auditpol.py
|
get_setting
|
python
|
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))
|
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')
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_auditpol.py#L192-L219
|
[
"def get_settings(category='All'):\n '''\n Get the current configuration for all audit settings specified in the\n category\n\n Args:\n category (str):\n One of the nine categories to return. Can also be ``All`` to return\n the settings for all categories. Valid options are:\n\n - Account Logon\n - Account Management\n - Detailed Tracking\n - DS Access\n - Logon/Logoff\n - Object Access\n - Policy Change\n - Privilege Use\n - System\n - All\n\n Default value is ``All``\n\n Returns:\n dict: A dictionary containing all subcategories for the specified\n category along with their current configuration\n\n Raises:\n KeyError: On invalid category\n CommandExecutionError: If an error is encountered retrieving the settings\n\n Usage:\n\n .. code-block:: python\n\n import salt.utils.win_lgpo_auditpol\n\n # Get current state of all audit settings\n salt.utils.win_lgpo_auditpol.get_settings()\n\n # Get the current state of all audit settings in the \"Account Logon\"\n # category\n salt.utils.win_lgpo_auditpol.get_settings(category=\"Account Logon\")\n '''\n # Parameter validation\n if category.lower() in ['all', '*']:\n category = '*'\n elif category.lower() not in [x.lower() for x in categories]:\n raise KeyError('Invalid category: \"{0}\"'.format(category))\n\n cmd = '/get /category:\"{0}\"'.format(category)\n results = _auditpol_cmd(cmd)\n\n ret = {}\n # Skip the first 2 lines\n for line in results[3:]:\n if ' ' in line.strip():\n ret.update(dict(list(zip(*[iter(re.split(r\"\\s{2,}\", line.strip()))]*2))))\n return ret\n"
] |
# -*- coding: utf-8 -*-
r'''
A salt util for modifying the audit policies on the machine. This util is used
by the ``win_auditpol`` and ``win_lgpo`` modules.
Though this utility does not set group policy for auditing, it displays how all
auditing configuration is applied on the machine, either set directly or via
local or domain group policy.
.. versionadded:: 2018.3.4
.. versionadded:: 2019.2.1
This util allows you to view and modify the audit settings as they are applied
on the machine. The audit settings are broken down into nine categories:
- Account Logon
- Account Management
- Detailed Tracking
- DS Access
- Logon/Logoff
- Object Access
- Policy Change
- Privilege Use
- System
The ``get_settings`` function will return the subcategories for all nine of
the above categories in one dictionary along with their auditing status.
To modify a setting you only need to specify the subcategory name and the value
you wish to set. Valid settings are:
- No Auditing
- Success
- Failure
- Success and Failure
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")
# Get current state of the "Credential Validation" setting
salt.utils.win_lgpo_auditpol.get_setting(name='Credential Validation')
# 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')
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import re
import tempfile
# Import Salt libs
import salt.modules.cmdmod
import salt.utils.files
import salt.utils.platform
from salt.exceptions import CommandExecutionError
# Import 3rd Party libs
from salt.ext.six.moves import zip
log = logging.getLogger(__name__)
__virtualname__ = 'auditpol'
categories = ['Account Logon',
'Account Management',
'Detailed Tracking',
'DS Access',
'Logon/Logoff',
'Object Access',
'Policy Change',
'Privilege Use',
'System']
settings = {'No Auditing': '/success:disable /failure:disable',
'Success': '/success:enable /failure:disable',
'Failure': '/success:disable /failure:enable',
'Success and Failure': '/success:enable /failure:enable'}
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if on a Windows system
'''
if not salt.utils.platform.is_windows():
return False, 'This utility only available on Windows'
return __virtualname__
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_valid_names():
if 'auditpol.valid_names' not in __context__:
settings = get_settings(category='All')
__context__['auditpol.valid_names'] = [k.lower() for k in settings]
return __context__['auditpol.valid_names']
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()
|
saltstack/salt
|
salt/utils/win_lgpo_auditpol.py
|
set_setting
|
python
|
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
|
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')
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_auditpol.py#L229-L280
|
[
"def _get_valid_names():\n if 'auditpol.valid_names' not in __context__:\n settings = get_settings(category='All')\n __context__['auditpol.valid_names'] = [k.lower() for k in settings]\n return __context__['auditpol.valid_names']\n",
"def _auditpol_cmd(cmd):\n '''\n Helper function for running the auditpol command\n\n Args:\n cmd (str): the auditpol command to run\n\n Returns:\n list: A list containing each line of the return (splitlines)\n\n Raises:\n CommandExecutionError: If the command encounters an error\n '''\n ret = salt.modules.cmdmod.run_all(cmd='auditpol {0}'.format(cmd),\n python_shell=True)\n if ret['retcode'] == 0:\n return ret['stdout'].splitlines()\n\n msg = 'Error executing auditpol command: {0}\\n'.format(cmd)\n msg += '\\n'.join(ret['stdout'])\n raise CommandExecutionError(msg)\n"
] |
# -*- coding: utf-8 -*-
r'''
A salt util for modifying the audit policies on the machine. This util is used
by the ``win_auditpol`` and ``win_lgpo`` modules.
Though this utility does not set group policy for auditing, it displays how all
auditing configuration is applied on the machine, either set directly or via
local or domain group policy.
.. versionadded:: 2018.3.4
.. versionadded:: 2019.2.1
This util allows you to view and modify the audit settings as they are applied
on the machine. The audit settings are broken down into nine categories:
- Account Logon
- Account Management
- Detailed Tracking
- DS Access
- Logon/Logoff
- Object Access
- Policy Change
- Privilege Use
- System
The ``get_settings`` function will return the subcategories for all nine of
the above categories in one dictionary along with their auditing status.
To modify a setting you only need to specify the subcategory name and the value
you wish to set. Valid settings are:
- No Auditing
- Success
- Failure
- Success and Failure
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")
# Get current state of the "Credential Validation" setting
salt.utils.win_lgpo_auditpol.get_setting(name='Credential Validation')
# 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')
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import re
import tempfile
# Import Salt libs
import salt.modules.cmdmod
import salt.utils.files
import salt.utils.platform
from salt.exceptions import CommandExecutionError
# Import 3rd Party libs
from salt.ext.six.moves import zip
log = logging.getLogger(__name__)
__virtualname__ = 'auditpol'
categories = ['Account Logon',
'Account Management',
'Detailed Tracking',
'DS Access',
'Logon/Logoff',
'Object Access',
'Policy Change',
'Privilege Use',
'System']
settings = {'No Auditing': '/success:disable /failure:disable',
'Success': '/success:enable /failure:disable',
'Failure': '/success:disable /failure:enable',
'Success and Failure': '/success:enable /failure:enable'}
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if on a Windows system
'''
if not salt.utils.platform.is_windows():
return False, 'This utility only available on Windows'
return __virtualname__
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 _get_valid_names():
if 'auditpol.valid_names' not in __context__:
settings = get_settings(category='All')
__context__['auditpol.valid_names'] = [k.lower() for k in settings]
return __context__['auditpol.valid_names']
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()
|
saltstack/salt
|
salt/utils/win_lgpo_auditpol.py
|
get_auditpol_dump
|
python
|
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()
|
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()
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_auditpol.py#L283-L308
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def _auditpol_cmd(cmd):\n '''\n Helper function for running the auditpol command\n\n Args:\n cmd (str): the auditpol command to run\n\n Returns:\n list: A list containing each line of the return (splitlines)\n\n Raises:\n CommandExecutionError: If the command encounters an error\n '''\n ret = salt.modules.cmdmod.run_all(cmd='auditpol {0}'.format(cmd),\n python_shell=True)\n if ret['retcode'] == 0:\n return ret['stdout'].splitlines()\n\n msg = 'Error executing auditpol command: {0}\\n'.format(cmd)\n msg += '\\n'.join(ret['stdout'])\n raise CommandExecutionError(msg)\n"
] |
# -*- coding: utf-8 -*-
r'''
A salt util for modifying the audit policies on the machine. This util is used
by the ``win_auditpol`` and ``win_lgpo`` modules.
Though this utility does not set group policy for auditing, it displays how all
auditing configuration is applied on the machine, either set directly or via
local or domain group policy.
.. versionadded:: 2018.3.4
.. versionadded:: 2019.2.1
This util allows you to view and modify the audit settings as they are applied
on the machine. The audit settings are broken down into nine categories:
- Account Logon
- Account Management
- Detailed Tracking
- DS Access
- Logon/Logoff
- Object Access
- Policy Change
- Privilege Use
- System
The ``get_settings`` function will return the subcategories for all nine of
the above categories in one dictionary along with their auditing status.
To modify a setting you only need to specify the subcategory name and the value
you wish to set. Valid settings are:
- No Auditing
- Success
- Failure
- Success and Failure
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")
# Get current state of the "Credential Validation" setting
salt.utils.win_lgpo_auditpol.get_setting(name='Credential Validation')
# 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')
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import re
import tempfile
# Import Salt libs
import salt.modules.cmdmod
import salt.utils.files
import salt.utils.platform
from salt.exceptions import CommandExecutionError
# Import 3rd Party libs
from salt.ext.six.moves import zip
log = logging.getLogger(__name__)
__virtualname__ = 'auditpol'
categories = ['Account Logon',
'Account Management',
'Detailed Tracking',
'DS Access',
'Logon/Logoff',
'Object Access',
'Policy Change',
'Privilege Use',
'System']
settings = {'No Auditing': '/success:disable /failure:disable',
'Success': '/success:enable /failure:disable',
'Failure': '/success:disable /failure:enable',
'Success and Failure': '/success:enable /failure:enable'}
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if on a Windows system
'''
if not salt.utils.platform.is_windows():
return False, 'This utility only available on Windows'
return __virtualname__
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 _get_valid_names():
if 'auditpol.valid_names' not in __context__:
settings = get_settings(category='All')
__context__['auditpol.valid_names'] = [k.lower() for k in settings]
return __context__['auditpol.valid_names']
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
|
saltstack/salt
|
salt/states/rbenv.py
|
_ruby_installed
|
python
|
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
|
Check to see if given ruby is installed.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rbenv.py#L72-L84
| null |
# -*- coding: utf-8 -*-
'''
Managing Ruby installations with rbenv
======================================
This module is used to install and manage ruby installations with rbenv and the
ruby-build plugin. Different versions of ruby can be installed, and uninstalled.
Rbenv will be installed automatically the first time it is needed and can be
updated later. This module will *not* automatically install packages which rbenv
will need to compile the versions of ruby. If your version of ruby fails to
install, refer to the ruby-build documentation to verify you are not missing any
dependencies: https://github.com/sstephenson/ruby-build/wiki
If rbenv is run as the root user then it will be installed to /usr/local/rbenv,
otherwise it will be installed to the users ~/.rbenv directory. To make
rbenv available in the shell you may need to add the rbenv/shims and rbenv/bin
directories to the users PATH. If you are installing as root and want other
users to be able to access rbenv then you will need to add RBENV_ROOT to
their environment.
The following state configuration demonstrates how to install Ruby 1.9.x
and 2.x using rbenv on Ubuntu/Debian:
.. code-block:: yaml
rbenv-deps:
pkg.installed:
- names:
- bash
- git
- openssl
- libssl-dev
- make
- curl
- autoconf
- bison
- build-essential
- libffi-dev
- libyaml-dev
- libreadline6-dev
- zlib1g-dev
- libncurses5-dev
ruby-1.9.3-p429:
rbenv.absent:
- require:
- pkg: rbenv-deps
ruby-2.0.0-p598:
rbenv.installed:
- default: True
- require:
- pkg: rbenv-deps
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import copy
def _check_rbenv(ret, user=None):
'''
Check to see if rbenv is installed.
'''
if not __salt__['rbenv.is_installed'](user):
ret['result'] = False
ret['comment'] = 'Rbenv is not installed.'
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)
|
saltstack/salt
|
salt/states/rbenv.py
|
_check_and_install_ruby
|
python
|
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
|
Verify that ruby is installed, install if unavailable
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rbenv.py#L87-L106
| null |
# -*- coding: utf-8 -*-
'''
Managing Ruby installations with rbenv
======================================
This module is used to install and manage ruby installations with rbenv and the
ruby-build plugin. Different versions of ruby can be installed, and uninstalled.
Rbenv will be installed automatically the first time it is needed and can be
updated later. This module will *not* automatically install packages which rbenv
will need to compile the versions of ruby. If your version of ruby fails to
install, refer to the ruby-build documentation to verify you are not missing any
dependencies: https://github.com/sstephenson/ruby-build/wiki
If rbenv is run as the root user then it will be installed to /usr/local/rbenv,
otherwise it will be installed to the users ~/.rbenv directory. To make
rbenv available in the shell you may need to add the rbenv/shims and rbenv/bin
directories to the users PATH. If you are installing as root and want other
users to be able to access rbenv then you will need to add RBENV_ROOT to
their environment.
The following state configuration demonstrates how to install Ruby 1.9.x
and 2.x using rbenv on Ubuntu/Debian:
.. code-block:: yaml
rbenv-deps:
pkg.installed:
- names:
- bash
- git
- openssl
- libssl-dev
- make
- curl
- autoconf
- bison
- build-essential
- libffi-dev
- libyaml-dev
- libreadline6-dev
- zlib1g-dev
- libncurses5-dev
ruby-1.9.3-p429:
rbenv.absent:
- require:
- pkg: rbenv-deps
ruby-2.0.0-p598:
rbenv.installed:
- default: True
- require:
- pkg: rbenv-deps
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import copy
def _check_rbenv(ret, user=None):
'''
Check to see if rbenv is installed.
'''
if not __salt__['rbenv.is_installed'](user):
ret['result'] = False
ret['comment'] = 'Rbenv is not installed.'
return ret
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 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)
|
saltstack/salt
|
salt/states/rbenv.py
|
installed
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rbenv.py#L109-L147
|
[
"def _ruby_installed(ret, ruby, user=None):\n '''\n Check to see if given ruby is installed.\n '''\n default = __salt__['rbenv.default'](runas=user)\n for version in __salt__['rbenv.versions'](user):\n if version == ruby:\n ret['result'] = True\n ret['comment'] = 'Requested ruby exists'\n ret['default'] = default == ruby\n break\n\n return ret\n",
"def _check_and_install_ruby(ret, ruby, default=False, user=None):\n '''\n Verify that ruby is installed, install if unavailable\n '''\n ret = _ruby_installed(ret, ruby, user=user)\n if not ret['result']:\n if __salt__['rbenv.install_ruby'](ruby, runas=user):\n ret['result'] = True\n ret['changes'][ruby] = 'Installed'\n ret['comment'] = 'Successfully installed ruby'\n ret['default'] = default\n else:\n ret['result'] = False\n ret['comment'] = 'Failed to install ruby'\n return ret\n\n if default:\n __salt__['rbenv.default'](ruby, runas=user)\n\n return ret\n",
"def _check_and_install_rbenv(ret, user=None):\n '''\n Verify that rbenv is installed, install if unavailable\n '''\n ret = _check_rbenv(ret, user)\n if ret['result'] is False:\n if __salt__['rbenv.install'](user):\n ret['result'] = True\n ret['comment'] = 'Rbenv installed'\n else:\n ret['result'] = False\n ret['comment'] = 'Rbenv failed to install'\n else:\n ret['result'] = True\n ret['comment'] = 'Rbenv is already installed'\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Managing Ruby installations with rbenv
======================================
This module is used to install and manage ruby installations with rbenv and the
ruby-build plugin. Different versions of ruby can be installed, and uninstalled.
Rbenv will be installed automatically the first time it is needed and can be
updated later. This module will *not* automatically install packages which rbenv
will need to compile the versions of ruby. If your version of ruby fails to
install, refer to the ruby-build documentation to verify you are not missing any
dependencies: https://github.com/sstephenson/ruby-build/wiki
If rbenv is run as the root user then it will be installed to /usr/local/rbenv,
otherwise it will be installed to the users ~/.rbenv directory. To make
rbenv available in the shell you may need to add the rbenv/shims and rbenv/bin
directories to the users PATH. If you are installing as root and want other
users to be able to access rbenv then you will need to add RBENV_ROOT to
their environment.
The following state configuration demonstrates how to install Ruby 1.9.x
and 2.x using rbenv on Ubuntu/Debian:
.. code-block:: yaml
rbenv-deps:
pkg.installed:
- names:
- bash
- git
- openssl
- libssl-dev
- make
- curl
- autoconf
- bison
- build-essential
- libffi-dev
- libyaml-dev
- libreadline6-dev
- zlib1g-dev
- libncurses5-dev
ruby-1.9.3-p429:
rbenv.absent:
- require:
- pkg: rbenv-deps
ruby-2.0.0-p598:
rbenv.installed:
- default: True
- require:
- pkg: rbenv-deps
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import copy
def _check_rbenv(ret, user=None):
'''
Check to see if rbenv is installed.
'''
if not __salt__['rbenv.is_installed'](user):
ret['result'] = False
ret['comment'] = 'Rbenv is not installed.'
return ret
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 _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)
|
saltstack/salt
|
salt/states/rbenv.py
|
_check_and_uninstall_ruby
|
python
|
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
|
Verify that ruby is uninstalled
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rbenv.py#L150-L172
| null |
# -*- coding: utf-8 -*-
'''
Managing Ruby installations with rbenv
======================================
This module is used to install and manage ruby installations with rbenv and the
ruby-build plugin. Different versions of ruby can be installed, and uninstalled.
Rbenv will be installed automatically the first time it is needed and can be
updated later. This module will *not* automatically install packages which rbenv
will need to compile the versions of ruby. If your version of ruby fails to
install, refer to the ruby-build documentation to verify you are not missing any
dependencies: https://github.com/sstephenson/ruby-build/wiki
If rbenv is run as the root user then it will be installed to /usr/local/rbenv,
otherwise it will be installed to the users ~/.rbenv directory. To make
rbenv available in the shell you may need to add the rbenv/shims and rbenv/bin
directories to the users PATH. If you are installing as root and want other
users to be able to access rbenv then you will need to add RBENV_ROOT to
their environment.
The following state configuration demonstrates how to install Ruby 1.9.x
and 2.x using rbenv on Ubuntu/Debian:
.. code-block:: yaml
rbenv-deps:
pkg.installed:
- names:
- bash
- git
- openssl
- libssl-dev
- make
- curl
- autoconf
- bison
- build-essential
- libffi-dev
- libyaml-dev
- libreadline6-dev
- zlib1g-dev
- libncurses5-dev
ruby-1.9.3-p429:
rbenv.absent:
- require:
- pkg: rbenv-deps
ruby-2.0.0-p598:
rbenv.installed:
- default: True
- require:
- pkg: rbenv-deps
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import copy
def _check_rbenv(ret, user=None):
'''
Check to see if rbenv is installed.
'''
if not __salt__['rbenv.is_installed'](user):
ret['result'] = False
ret['comment'] = 'Rbenv is not installed.'
return ret
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 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)
|
saltstack/salt
|
salt/states/rbenv.py
|
absent
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rbenv.py#L175-L211
|
[
"def _check_rbenv(ret, user=None):\n '''\n Check to see if rbenv is installed.\n '''\n if not __salt__['rbenv.is_installed'](user):\n ret['result'] = False\n ret['comment'] = 'Rbenv is not installed.'\n return ret\n",
"def _ruby_installed(ret, ruby, user=None):\n '''\n Check to see if given ruby is installed.\n '''\n default = __salt__['rbenv.default'](runas=user)\n for version in __salt__['rbenv.versions'](user):\n if version == ruby:\n ret['result'] = True\n ret['comment'] = 'Requested ruby exists'\n ret['default'] = default == ruby\n break\n\n return ret\n",
"def _check_and_uninstall_ruby(ret, ruby, user=None):\n '''\n Verify that ruby is uninstalled\n '''\n ret = _ruby_installed(ret, ruby, user=user)\n if ret['result']:\n if ret['default']:\n __salt__['rbenv.default']('system', runas=user)\n\n if __salt__['rbenv.uninstall_ruby'](ruby, runas=user):\n ret['result'] = True\n ret['changes'][ruby] = 'Uninstalled'\n ret['comment'] = 'Successfully removed ruby'\n return ret\n else:\n ret['result'] = False\n ret['comment'] = 'Failed to uninstall ruby'\n return ret\n else:\n ret['result'] = True\n ret['comment'] = 'Ruby {0} is already absent'.format(ruby)\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Managing Ruby installations with rbenv
======================================
This module is used to install and manage ruby installations with rbenv and the
ruby-build plugin. Different versions of ruby can be installed, and uninstalled.
Rbenv will be installed automatically the first time it is needed and can be
updated later. This module will *not* automatically install packages which rbenv
will need to compile the versions of ruby. If your version of ruby fails to
install, refer to the ruby-build documentation to verify you are not missing any
dependencies: https://github.com/sstephenson/ruby-build/wiki
If rbenv is run as the root user then it will be installed to /usr/local/rbenv,
otherwise it will be installed to the users ~/.rbenv directory. To make
rbenv available in the shell you may need to add the rbenv/shims and rbenv/bin
directories to the users PATH. If you are installing as root and want other
users to be able to access rbenv then you will need to add RBENV_ROOT to
their environment.
The following state configuration demonstrates how to install Ruby 1.9.x
and 2.x using rbenv on Ubuntu/Debian:
.. code-block:: yaml
rbenv-deps:
pkg.installed:
- names:
- bash
- git
- openssl
- libssl-dev
- make
- curl
- autoconf
- bison
- build-essential
- libffi-dev
- libyaml-dev
- libreadline6-dev
- zlib1g-dev
- libncurses5-dev
ruby-1.9.3-p429:
rbenv.absent:
- require:
- pkg: rbenv-deps
ruby-2.0.0-p598:
rbenv.installed:
- default: True
- require:
- pkg: rbenv-deps
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import copy
def _check_rbenv(ret, user=None):
'''
Check to see if rbenv is installed.
'''
if not __salt__['rbenv.is_installed'](user):
ret['result'] = False
ret['comment'] = 'Rbenv is not installed.'
return ret
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 _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)
|
saltstack/salt
|
salt/states/rbenv.py
|
_check_and_install_rbenv
|
python
|
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
|
Verify that rbenv is installed, install if unavailable
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rbenv.py#L214-L230
|
[
"def _check_rbenv(ret, user=None):\n '''\n Check to see if rbenv is installed.\n '''\n if not __salt__['rbenv.is_installed'](user):\n ret['result'] = False\n ret['comment'] = 'Rbenv is not installed.'\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Managing Ruby installations with rbenv
======================================
This module is used to install and manage ruby installations with rbenv and the
ruby-build plugin. Different versions of ruby can be installed, and uninstalled.
Rbenv will be installed automatically the first time it is needed and can be
updated later. This module will *not* automatically install packages which rbenv
will need to compile the versions of ruby. If your version of ruby fails to
install, refer to the ruby-build documentation to verify you are not missing any
dependencies: https://github.com/sstephenson/ruby-build/wiki
If rbenv is run as the root user then it will be installed to /usr/local/rbenv,
otherwise it will be installed to the users ~/.rbenv directory. To make
rbenv available in the shell you may need to add the rbenv/shims and rbenv/bin
directories to the users PATH. If you are installing as root and want other
users to be able to access rbenv then you will need to add RBENV_ROOT to
their environment.
The following state configuration demonstrates how to install Ruby 1.9.x
and 2.x using rbenv on Ubuntu/Debian:
.. code-block:: yaml
rbenv-deps:
pkg.installed:
- names:
- bash
- git
- openssl
- libssl-dev
- make
- curl
- autoconf
- bison
- build-essential
- libffi-dev
- libyaml-dev
- libreadline6-dev
- zlib1g-dev
- libncurses5-dev
ruby-1.9.3-p429:
rbenv.absent:
- require:
- pkg: rbenv-deps
ruby-2.0.0-p598:
rbenv.installed:
- default: True
- require:
- pkg: rbenv-deps
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import copy
def _check_rbenv(ret, user=None):
'''
Check to see if rbenv is installed.
'''
if not __salt__['rbenv.is_installed'](user):
ret['result'] = False
ret['comment'] = 'Rbenv is not installed.'
return ret
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 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)
|
saltstack/salt
|
salt/states/rbenv.py
|
install_rbenv
|
python
|
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)
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rbenv.py#L233-L258
|
[
"def _check_rbenv(ret, user=None):\n '''\n Check to see if rbenv is installed.\n '''\n if not __salt__['rbenv.is_installed'](user):\n ret['result'] = False\n ret['comment'] = 'Rbenv is not installed.'\n return ret\n",
"def _check_and_install_rbenv(ret, user=None):\n '''\n Verify that rbenv is installed, install if unavailable\n '''\n ret = _check_rbenv(ret, user)\n if ret['result'] is False:\n if __salt__['rbenv.install'](user):\n ret['result'] = True\n ret['comment'] = 'Rbenv installed'\n else:\n ret['result'] = False\n ret['comment'] = 'Rbenv failed to install'\n else:\n ret['result'] = True\n ret['comment'] = 'Rbenv is already installed'\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Managing Ruby installations with rbenv
======================================
This module is used to install and manage ruby installations with rbenv and the
ruby-build plugin. Different versions of ruby can be installed, and uninstalled.
Rbenv will be installed automatically the first time it is needed and can be
updated later. This module will *not* automatically install packages which rbenv
will need to compile the versions of ruby. If your version of ruby fails to
install, refer to the ruby-build documentation to verify you are not missing any
dependencies: https://github.com/sstephenson/ruby-build/wiki
If rbenv is run as the root user then it will be installed to /usr/local/rbenv,
otherwise it will be installed to the users ~/.rbenv directory. To make
rbenv available in the shell you may need to add the rbenv/shims and rbenv/bin
directories to the users PATH. If you are installing as root and want other
users to be able to access rbenv then you will need to add RBENV_ROOT to
their environment.
The following state configuration demonstrates how to install Ruby 1.9.x
and 2.x using rbenv on Ubuntu/Debian:
.. code-block:: yaml
rbenv-deps:
pkg.installed:
- names:
- bash
- git
- openssl
- libssl-dev
- make
- curl
- autoconf
- bison
- build-essential
- libffi-dev
- libyaml-dev
- libreadline6-dev
- zlib1g-dev
- libncurses5-dev
ruby-1.9.3-p429:
rbenv.absent:
- require:
- pkg: rbenv-deps
ruby-2.0.0-p598:
rbenv.installed:
- default: True
- require:
- pkg: rbenv-deps
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import copy
def _check_rbenv(ret, user=None):
'''
Check to see if rbenv is installed.
'''
if not __salt__['rbenv.is_installed'](user):
ret['result'] = False
ret['comment'] = 'Rbenv is not installed.'
return ret
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
|
saltstack/salt
|
salt/modules/nftables.py
|
build_rule
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nftables.py#L86-L274
|
[
"def _nftables_cmd():\n '''\n Return correct command\n '''\n return 'nft'\n"
] |
# -*- coding: utf-8 -*-
'''
Support for nftables
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import (
CommandExecutionError
)
# Set up logging
log = logging.getLogger(__name__)
_NFTABLES_FAMILIES = {
'ipv4': 'ip',
'ip4': 'ip',
'ip': 'ip',
'ipv6': 'ip6',
'ip6': 'ip6',
'inet': 'inet',
'arp': 'arp',
'bridge': 'bridge',
'netdev': 'netdev'
}
def __virtual__():
'''
Only load the module if nftables is installed
'''
if salt.utils.path.which('nft'):
return 'nftables'
return (False, 'The nftables execution module failed to load: nftables is not installed.')
def _nftables_cmd():
'''
Return correct command
'''
return 'nft'
def _conf(family='ip'):
'''
Use the same file for rules for now.
'''
if __grains__['os_family'] == 'RedHat':
return '/etc/nftables'
elif __grains__['os_family'] == 'Arch':
return '/etc/nftables'
elif __grains__['os_family'] == 'Debian':
return '/etc/nftables'
elif __grains__['os_family'] == 'Gentoo':
return '/etc/nftables'
else:
return False
def version():
'''
Return version from nftables --version
CLI Example:
.. code-block:: bash
salt '*' nftables.version
'''
cmd = '{0} --version' . format(_nftables_cmd())
out = __salt__['cmd.run'](cmd).split()
return out[1]
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_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' nftables.check_chain filter input
IPv6:
salt '*' nftables.check_chain filter input family=ipv6
'''
ret = {'comment': '',
'result': False}
if not chain:
ret['comment'] = 'Chain needs to be specified'
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))
if out == -1:
ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\
format(chain, table, family)
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\
format(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_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.new_table filter
IPv6:
salt '*' nftables.new_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} created'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be created'.\
format(table, family)
return ret
def delete_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_table filter
IPv6:
salt '*' nftables.delete_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} deleted'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be deleted'.\
format(table, family)
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 delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete the chain from the specified table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_chain filter input
salt '*' nftables.delete_chain filter foo
IPv6:
salt '*' nftables.delete_chain filter input family=ipv6
salt '*' nftables.delete_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 not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete chain {1} {2} {3}'.\
format(_nftables_cmd(), nft_family, table, chain)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Chain {0} in table {1} in family {2} deleted'.\
format(chain, table, family)
ret['result'] = True
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} could not be deleted'.\
format(chain, table, family)
return ret
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table & 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.append filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.append filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to append rule {0} to chain {1} in table {2}.'.format(rule, chain, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table & chain, at the specified position.
If position is not specified, rule will be inserted in first position.
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 Examples:
.. code-block:: bash
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept'
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to insert rule {0} to table {1}.'.format(rule, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
if position:
cmd = '{0} insert rule {1} {2} {3} position {4} {5}'.\
format(_nftables_cmd(), nft_family, table, chain, position, rule)
else:
cmd = '{0} insert rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table & chain, specifying either the rule
in its entirety, or the rule's position in the 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 Examples:
.. code-block:: bash
salt '*' nftables.delete filter input position=3
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.delete filter input position=3 family=ipv6
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to delete rule {0} in table {1}.'.format(rule, table),
'result': False}
if position and rule:
ret['comment'] = 'Only specify a position or a rule, not both'
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']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} does not exist'.\
format(rule, chain, table, family)
return ret
# nftables rules can only be deleted using the handle
# if we don't have it, find it.
if not position:
position = get_rule_handle(table, chain, rule, family)
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete rule {1} {2} {3} handle {4}'.\
format(_nftables_cmd(), nft_family, table, chain, position)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Deleted rule "{0}" in chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to delete rule "{0}" in chain {1} table {2} in family {3}'.\
format(rule, 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
|
saltstack/salt
|
salt/modules/nftables.py
|
get_saved_rules
|
python
|
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
|
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' nftables.get_saved_rules
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nftables.py#L277-L301
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def _conf(family='ip'):\n '''\n Use the same file for rules for now.\n '''\n if __grains__['os_family'] == 'RedHat':\n return '/etc/nftables'\n elif __grains__['os_family'] == 'Arch':\n return '/etc/nftables'\n elif __grains__['os_family'] == 'Debian':\n return '/etc/nftables'\n elif __grains__['os_family'] == 'Gentoo':\n return '/etc/nftables'\n else:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for nftables
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import (
CommandExecutionError
)
# Set up logging
log = logging.getLogger(__name__)
_NFTABLES_FAMILIES = {
'ipv4': 'ip',
'ip4': 'ip',
'ip': 'ip',
'ipv6': 'ip6',
'ip6': 'ip6',
'inet': 'inet',
'arp': 'arp',
'bridge': 'bridge',
'netdev': 'netdev'
}
def __virtual__():
'''
Only load the module if nftables is installed
'''
if salt.utils.path.which('nft'):
return 'nftables'
return (False, 'The nftables execution module failed to load: nftables is not installed.')
def _nftables_cmd():
'''
Return correct command
'''
return 'nft'
def _conf(family='ip'):
'''
Use the same file for rules for now.
'''
if __grains__['os_family'] == 'RedHat':
return '/etc/nftables'
elif __grains__['os_family'] == 'Arch':
return '/etc/nftables'
elif __grains__['os_family'] == 'Debian':
return '/etc/nftables'
elif __grains__['os_family'] == 'Gentoo':
return '/etc/nftables'
else:
return False
def version():
'''
Return version from nftables --version
CLI Example:
.. code-block:: bash
salt '*' nftables.version
'''
cmd = '{0} --version' . format(_nftables_cmd())
out = __salt__['cmd.run'](cmd).split()
return out[1]
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_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_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' nftables.check_chain filter input
IPv6:
salt '*' nftables.check_chain filter input family=ipv6
'''
ret = {'comment': '',
'result': False}
if not chain:
ret['comment'] = 'Chain needs to be specified'
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))
if out == -1:
ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\
format(chain, table, family)
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\
format(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_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.new_table filter
IPv6:
salt '*' nftables.new_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} created'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be created'.\
format(table, family)
return ret
def delete_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_table filter
IPv6:
salt '*' nftables.delete_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} deleted'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be deleted'.\
format(table, family)
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 delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete the chain from the specified table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_chain filter input
salt '*' nftables.delete_chain filter foo
IPv6:
salt '*' nftables.delete_chain filter input family=ipv6
salt '*' nftables.delete_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 not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete chain {1} {2} {3}'.\
format(_nftables_cmd(), nft_family, table, chain)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Chain {0} in table {1} in family {2} deleted'.\
format(chain, table, family)
ret['result'] = True
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} could not be deleted'.\
format(chain, table, family)
return ret
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table & 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.append filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.append filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to append rule {0} to chain {1} in table {2}.'.format(rule, chain, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table & chain, at the specified position.
If position is not specified, rule will be inserted in first position.
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 Examples:
.. code-block:: bash
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept'
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to insert rule {0} to table {1}.'.format(rule, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
if position:
cmd = '{0} insert rule {1} {2} {3} position {4} {5}'.\
format(_nftables_cmd(), nft_family, table, chain, position, rule)
else:
cmd = '{0} insert rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table & chain, specifying either the rule
in its entirety, or the rule's position in the 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 Examples:
.. code-block:: bash
salt '*' nftables.delete filter input position=3
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.delete filter input position=3 family=ipv6
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to delete rule {0} in table {1}.'.format(rule, table),
'result': False}
if position and rule:
ret['comment'] = 'Only specify a position or a rule, not both'
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']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} does not exist'.\
format(rule, chain, table, family)
return ret
# nftables rules can only be deleted using the handle
# if we don't have it, find it.
if not position:
position = get_rule_handle(table, chain, rule, family)
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete rule {1} {2} {3} handle {4}'.\
format(_nftables_cmd(), nft_family, table, chain, position)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Deleted rule "{0}" in chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to delete rule "{0}" in chain {1} table {2} in family {3}'.\
format(rule, 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
|
saltstack/salt
|
salt/modules/nftables.py
|
get_rules
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nftables.py#L304-L334
|
[
"def _nftables_cmd():\n '''\n Return correct command\n '''\n return 'nft'\n"
] |
# -*- coding: utf-8 -*-
'''
Support for nftables
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import (
CommandExecutionError
)
# Set up logging
log = logging.getLogger(__name__)
_NFTABLES_FAMILIES = {
'ipv4': 'ip',
'ip4': 'ip',
'ip': 'ip',
'ipv6': 'ip6',
'ip6': 'ip6',
'inet': 'inet',
'arp': 'arp',
'bridge': 'bridge',
'netdev': 'netdev'
}
def __virtual__():
'''
Only load the module if nftables is installed
'''
if salt.utils.path.which('nft'):
return 'nftables'
return (False, 'The nftables execution module failed to load: nftables is not installed.')
def _nftables_cmd():
'''
Return correct command
'''
return 'nft'
def _conf(family='ip'):
'''
Use the same file for rules for now.
'''
if __grains__['os_family'] == 'RedHat':
return '/etc/nftables'
elif __grains__['os_family'] == 'Arch':
return '/etc/nftables'
elif __grains__['os_family'] == 'Debian':
return '/etc/nftables'
elif __grains__['os_family'] == 'Gentoo':
return '/etc/nftables'
else:
return False
def version():
'''
Return version from nftables --version
CLI Example:
.. code-block:: bash
salt '*' nftables.version
'''
cmd = '{0} --version' . format(_nftables_cmd())
out = __salt__['cmd.run'](cmd).split()
return out[1]
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 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_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' nftables.check_chain filter input
IPv6:
salt '*' nftables.check_chain filter input family=ipv6
'''
ret = {'comment': '',
'result': False}
if not chain:
ret['comment'] = 'Chain needs to be specified'
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))
if out == -1:
ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\
format(chain, table, family)
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\
format(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_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.new_table filter
IPv6:
salt '*' nftables.new_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} created'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be created'.\
format(table, family)
return ret
def delete_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_table filter
IPv6:
salt '*' nftables.delete_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} deleted'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be deleted'.\
format(table, family)
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 delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete the chain from the specified table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_chain filter input
salt '*' nftables.delete_chain filter foo
IPv6:
salt '*' nftables.delete_chain filter input family=ipv6
salt '*' nftables.delete_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 not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete chain {1} {2} {3}'.\
format(_nftables_cmd(), nft_family, table, chain)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Chain {0} in table {1} in family {2} deleted'.\
format(chain, table, family)
ret['result'] = True
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} could not be deleted'.\
format(chain, table, family)
return ret
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table & 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.append filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.append filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to append rule {0} to chain {1} in table {2}.'.format(rule, chain, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table & chain, at the specified position.
If position is not specified, rule will be inserted in first position.
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 Examples:
.. code-block:: bash
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept'
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to insert rule {0} to table {1}.'.format(rule, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
if position:
cmd = '{0} insert rule {1} {2} {3} position {4} {5}'.\
format(_nftables_cmd(), nft_family, table, chain, position, rule)
else:
cmd = '{0} insert rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table & chain, specifying either the rule
in its entirety, or the rule's position in the 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 Examples:
.. code-block:: bash
salt '*' nftables.delete filter input position=3
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.delete filter input position=3 family=ipv6
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to delete rule {0} in table {1}.'.format(rule, table),
'result': False}
if position and rule:
ret['comment'] = 'Only specify a position or a rule, not both'
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']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} does not exist'.\
format(rule, chain, table, family)
return ret
# nftables rules can only be deleted using the handle
# if we don't have it, find it.
if not position:
position = get_rule_handle(table, chain, rule, family)
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete rule {1} {2} {3} handle {4}'.\
format(_nftables_cmd(), nft_family, table, chain, position)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Deleted rule "{0}" in chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to delete rule "{0}" in chain {1} table {2} in family {3}'.\
format(rule, 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
|
saltstack/salt
|
salt/modules/nftables.py
|
save
|
python
|
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
|
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' nftables.save /etc/nftables
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nftables.py#L337-L367
|
[
"def encode(data, encoding=None, errors='strict', keep=False,\n preserve_dict_class=False, preserve_tuples=False):\n '''\n Generic function which will encode whichever type is passed, if necessary\n\n If `strict` is True, and `keep` is False, and we fail to encode, a\n UnicodeEncodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where encoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs.\n '''\n if isinstance(data, Mapping):\n return encode_dict(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, list):\n return encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, tuple):\n return encode_tuple(data, encoding, errors, keep, preserve_dict_class) \\\n if preserve_tuples \\\n else encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n else:\n try:\n return salt.utils.stringutils.to_bytes(data, encoding, errors)\n except TypeError:\n # to_bytes raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply\n # means we are going to leave the value as-is.\n pass\n except UnicodeEncodeError:\n if not keep:\n raise\n return data\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def _conf(family='ip'):\n '''\n Use the same file for rules for now.\n '''\n if __grains__['os_family'] == 'RedHat':\n return '/etc/nftables'\n elif __grains__['os_family'] == 'Arch':\n return '/etc/nftables'\n elif __grains__['os_family'] == 'Debian':\n return '/etc/nftables'\n elif __grains__['os_family'] == 'Gentoo':\n return '/etc/nftables'\n else:\n return False\n",
"def get_rules(family='ipv4'):\n '''\n Return a data structure of the current, in-memory rules\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nftables.get_rules\n\n salt '*' nftables.get_rules family=ipv6\n\n '''\n nft_family = _NFTABLES_FAMILIES[family]\n rules = []\n cmd = '{0} --numeric --numeric --numeric ' \\\n 'list tables {1}'. format(_nftables_cmd(),\n nft_family)\n out = __salt__['cmd.run'](cmd, python_shell=False)\n if not out:\n return rules\n\n tables = re.split('\\n+', out)\n for table in tables:\n table_name = table.split(' ')[1]\n cmd = '{0} --numeric --numeric --numeric ' \\\n 'list table {1} {2}'.format(_nftables_cmd(),\n nft_family, table_name)\n out = __salt__['cmd.run'](cmd, python_shell=False)\n rules.append(out)\n return rules\n"
] |
# -*- coding: utf-8 -*-
'''
Support for nftables
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import (
CommandExecutionError
)
# Set up logging
log = logging.getLogger(__name__)
_NFTABLES_FAMILIES = {
'ipv4': 'ip',
'ip4': 'ip',
'ip': 'ip',
'ipv6': 'ip6',
'ip6': 'ip6',
'inet': 'inet',
'arp': 'arp',
'bridge': 'bridge',
'netdev': 'netdev'
}
def __virtual__():
'''
Only load the module if nftables is installed
'''
if salt.utils.path.which('nft'):
return 'nftables'
return (False, 'The nftables execution module failed to load: nftables is not installed.')
def _nftables_cmd():
'''
Return correct command
'''
return 'nft'
def _conf(family='ip'):
'''
Use the same file for rules for now.
'''
if __grains__['os_family'] == 'RedHat':
return '/etc/nftables'
elif __grains__['os_family'] == 'Arch':
return '/etc/nftables'
elif __grains__['os_family'] == 'Debian':
return '/etc/nftables'
elif __grains__['os_family'] == 'Gentoo':
return '/etc/nftables'
else:
return False
def version():
'''
Return version from nftables --version
CLI Example:
.. code-block:: bash
salt '*' nftables.version
'''
cmd = '{0} --version' . format(_nftables_cmd())
out = __salt__['cmd.run'](cmd).split()
return out[1]
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 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_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' nftables.check_chain filter input
IPv6:
salt '*' nftables.check_chain filter input family=ipv6
'''
ret = {'comment': '',
'result': False}
if not chain:
ret['comment'] = 'Chain needs to be specified'
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))
if out == -1:
ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\
format(chain, table, family)
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\
format(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_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.new_table filter
IPv6:
salt '*' nftables.new_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} created'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be created'.\
format(table, family)
return ret
def delete_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_table filter
IPv6:
salt '*' nftables.delete_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} deleted'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be deleted'.\
format(table, family)
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 delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete the chain from the specified table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_chain filter input
salt '*' nftables.delete_chain filter foo
IPv6:
salt '*' nftables.delete_chain filter input family=ipv6
salt '*' nftables.delete_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 not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete chain {1} {2} {3}'.\
format(_nftables_cmd(), nft_family, table, chain)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Chain {0} in table {1} in family {2} deleted'.\
format(chain, table, family)
ret['result'] = True
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} could not be deleted'.\
format(chain, table, family)
return ret
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table & 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.append filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.append filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to append rule {0} to chain {1} in table {2}.'.format(rule, chain, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table & chain, at the specified position.
If position is not specified, rule will be inserted in first position.
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 Examples:
.. code-block:: bash
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept'
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to insert rule {0} to table {1}.'.format(rule, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
if position:
cmd = '{0} insert rule {1} {2} {3} position {4} {5}'.\
format(_nftables_cmd(), nft_family, table, chain, position, rule)
else:
cmd = '{0} insert rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table & chain, specifying either the rule
in its entirety, or the rule's position in the 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 Examples:
.. code-block:: bash
salt '*' nftables.delete filter input position=3
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.delete filter input position=3 family=ipv6
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to delete rule {0} in table {1}.'.format(rule, table),
'result': False}
if position and rule:
ret['comment'] = 'Only specify a position or a rule, not both'
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']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} does not exist'.\
format(rule, chain, table, family)
return ret
# nftables rules can only be deleted using the handle
# if we don't have it, find it.
if not position:
position = get_rule_handle(table, chain, rule, family)
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete rule {1} {2} {3} handle {4}'.\
format(_nftables_cmd(), nft_family, table, chain, position)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Deleted rule "{0}" in chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to delete rule "{0}" in chain {1} table {2} in family {3}'.\
format(rule, 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
|
saltstack/salt
|
salt/modules/nftables.py
|
get_rule_handle
|
python
|
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)}
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nftables.py#L370-L426
|
[
"def check(table='filter', chain=None, rule=None, family='ipv4'):\n '''\n Check for the existence of a rule in the table and chain\n\n This function accepts a rule in a standard nftables command format,\n starting with the chain. Trying to force users to adapt to a new\n method of creating rules would be irritating at best, and we\n already have a parser that can handle it.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nftables.check filter input \\\\\n rule='tcp dport 22 log accept'\n\n IPv6:\n salt '*' nftables.check filter input \\\\\n rule='tcp dport 22 log accept' \\\\\n family=ipv6\n '''\n ret = {'comment': '',\n 'result': False}\n\n if not chain:\n ret['comment'] = 'Chain needs to be specified'\n return ret\n\n if not rule:\n ret['comment'] = 'Rule needs to be specified'\n return ret\n\n res = check_table(table, family=family)\n if not res['result']:\n return res\n\n res = check_chain(table, chain, family=family)\n if not res['result']:\n return res\n\n nft_family = _NFTABLES_FAMILIES[family]\n cmd = '{0} --handle --numeric --numeric --numeric list chain {1} {2} {3}'.\\\n format(_nftables_cmd(), nft_family, table, chain)\n search_rule = '{0} #'.format(rule)\n out = __salt__['cmd.run'](cmd, python_shell=False).find(search_rule)\n\n if out == -1:\n ret['comment'] = 'Rule {0} in chain {1} in table {2} in family {3} does not exist'.\\\n format(rule, chain, table, family)\n else:\n ret['comment'] = 'Rule {0} in chain {1} in table {2} in family {3} exists'.\\\n format(rule, chain, table, family)\n ret['result'] = True\n return ret\n",
"def check_chain(table='filter', chain=None, family='ipv4'):\n '''\n .. versionadded:: 2014.7.0\n\n Check for the existence of a chain in the table\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nftables.check_chain filter input\n\n IPv6:\n salt '*' nftables.check_chain filter input family=ipv6\n '''\n\n ret = {'comment': '',\n 'result': False}\n\n if not chain:\n ret['comment'] = 'Chain needs to be specified'\n return ret\n\n nft_family = _NFTABLES_FAMILIES[family]\n cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)\n out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))\n\n if out == -1:\n ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\\\n format(chain, table, family)\n else:\n ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\\\n format(chain, table, family)\n ret['result'] = True\n return ret\n",
"def _nftables_cmd():\n '''\n Return correct command\n '''\n return 'nft'\n",
"def check_table(table=None, family='ipv4'):\n '''\n Check for the existence of a table\n\n CLI Example::\n\n salt '*' nftables.check_table nat\n '''\n ret = {'comment': '',\n 'result': False}\n\n if not table:\n ret['comment'] = 'Table needs to be specified'\n return ret\n\n nft_family = _NFTABLES_FAMILIES[family]\n cmd = '{0} list tables {1}' . format(_nftables_cmd(), nft_family)\n out = __salt__['cmd.run'](cmd, python_shell=False).find('table {0} {1}'.format(nft_family, table))\n\n if out == -1:\n ret['comment'] = 'Table {0} in family {1} does not exist'.\\\n format(table, family)\n else:\n ret['comment'] = 'Table {0} in family {1} exists'.\\\n format(table, family)\n ret['result'] = True\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for nftables
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import (
CommandExecutionError
)
# Set up logging
log = logging.getLogger(__name__)
_NFTABLES_FAMILIES = {
'ipv4': 'ip',
'ip4': 'ip',
'ip': 'ip',
'ipv6': 'ip6',
'ip6': 'ip6',
'inet': 'inet',
'arp': 'arp',
'bridge': 'bridge',
'netdev': 'netdev'
}
def __virtual__():
'''
Only load the module if nftables is installed
'''
if salt.utils.path.which('nft'):
return 'nftables'
return (False, 'The nftables execution module failed to load: nftables is not installed.')
def _nftables_cmd():
'''
Return correct command
'''
return 'nft'
def _conf(family='ip'):
'''
Use the same file for rules for now.
'''
if __grains__['os_family'] == 'RedHat':
return '/etc/nftables'
elif __grains__['os_family'] == 'Arch':
return '/etc/nftables'
elif __grains__['os_family'] == 'Debian':
return '/etc/nftables'
elif __grains__['os_family'] == 'Gentoo':
return '/etc/nftables'
else:
return False
def version():
'''
Return version from nftables --version
CLI Example:
.. code-block:: bash
salt '*' nftables.version
'''
cmd = '{0} --version' . format(_nftables_cmd())
out = __salt__['cmd.run'](cmd).split()
return out[1]
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 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_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' nftables.check_chain filter input
IPv6:
salt '*' nftables.check_chain filter input family=ipv6
'''
ret = {'comment': '',
'result': False}
if not chain:
ret['comment'] = 'Chain needs to be specified'
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))
if out == -1:
ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\
format(chain, table, family)
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\
format(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_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.new_table filter
IPv6:
salt '*' nftables.new_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} created'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be created'.\
format(table, family)
return ret
def delete_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_table filter
IPv6:
salt '*' nftables.delete_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} deleted'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be deleted'.\
format(table, family)
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 delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete the chain from the specified table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_chain filter input
salt '*' nftables.delete_chain filter foo
IPv6:
salt '*' nftables.delete_chain filter input family=ipv6
salt '*' nftables.delete_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 not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete chain {1} {2} {3}'.\
format(_nftables_cmd(), nft_family, table, chain)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Chain {0} in table {1} in family {2} deleted'.\
format(chain, table, family)
ret['result'] = True
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} could not be deleted'.\
format(chain, table, family)
return ret
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table & 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.append filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.append filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to append rule {0} to chain {1} in table {2}.'.format(rule, chain, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table & chain, at the specified position.
If position is not specified, rule will be inserted in first position.
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 Examples:
.. code-block:: bash
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept'
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to insert rule {0} to table {1}.'.format(rule, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
if position:
cmd = '{0} insert rule {1} {2} {3} position {4} {5}'.\
format(_nftables_cmd(), nft_family, table, chain, position, rule)
else:
cmd = '{0} insert rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table & chain, specifying either the rule
in its entirety, or the rule's position in the 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 Examples:
.. code-block:: bash
salt '*' nftables.delete filter input position=3
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.delete filter input position=3 family=ipv6
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to delete rule {0} in table {1}.'.format(rule, table),
'result': False}
if position and rule:
ret['comment'] = 'Only specify a position or a rule, not both'
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']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} does not exist'.\
format(rule, chain, table, family)
return ret
# nftables rules can only be deleted using the handle
# if we don't have it, find it.
if not position:
position = get_rule_handle(table, chain, rule, family)
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete rule {1} {2} {3} handle {4}'.\
format(_nftables_cmd(), nft_family, table, chain, position)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Deleted rule "{0}" in chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to delete rule "{0}" in chain {1} table {2} in family {3}'.\
format(rule, 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
|
saltstack/salt
|
salt/modules/nftables.py
|
check
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nftables.py#L429-L482
|
[
"def check_chain(table='filter', chain=None, family='ipv4'):\n '''\n .. versionadded:: 2014.7.0\n\n Check for the existence of a chain in the table\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nftables.check_chain filter input\n\n IPv6:\n salt '*' nftables.check_chain filter input family=ipv6\n '''\n\n ret = {'comment': '',\n 'result': False}\n\n if not chain:\n ret['comment'] = 'Chain needs to be specified'\n return ret\n\n nft_family = _NFTABLES_FAMILIES[family]\n cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)\n out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))\n\n if out == -1:\n ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\\\n format(chain, table, family)\n else:\n ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\\\n format(chain, table, family)\n ret['result'] = True\n return ret\n",
"def _nftables_cmd():\n '''\n Return correct command\n '''\n return 'nft'\n",
"def check_table(table=None, family='ipv4'):\n '''\n Check for the existence of a table\n\n CLI Example::\n\n salt '*' nftables.check_table nat\n '''\n ret = {'comment': '',\n 'result': False}\n\n if not table:\n ret['comment'] = 'Table needs to be specified'\n return ret\n\n nft_family = _NFTABLES_FAMILIES[family]\n cmd = '{0} list tables {1}' . format(_nftables_cmd(), nft_family)\n out = __salt__['cmd.run'](cmd, python_shell=False).find('table {0} {1}'.format(nft_family, table))\n\n if out == -1:\n ret['comment'] = 'Table {0} in family {1} does not exist'.\\\n format(table, family)\n else:\n ret['comment'] = 'Table {0} in family {1} exists'.\\\n format(table, family)\n ret['result'] = True\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for nftables
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import (
CommandExecutionError
)
# Set up logging
log = logging.getLogger(__name__)
_NFTABLES_FAMILIES = {
'ipv4': 'ip',
'ip4': 'ip',
'ip': 'ip',
'ipv6': 'ip6',
'ip6': 'ip6',
'inet': 'inet',
'arp': 'arp',
'bridge': 'bridge',
'netdev': 'netdev'
}
def __virtual__():
'''
Only load the module if nftables is installed
'''
if salt.utils.path.which('nft'):
return 'nftables'
return (False, 'The nftables execution module failed to load: nftables is not installed.')
def _nftables_cmd():
'''
Return correct command
'''
return 'nft'
def _conf(family='ip'):
'''
Use the same file for rules for now.
'''
if __grains__['os_family'] == 'RedHat':
return '/etc/nftables'
elif __grains__['os_family'] == 'Arch':
return '/etc/nftables'
elif __grains__['os_family'] == 'Debian':
return '/etc/nftables'
elif __grains__['os_family'] == 'Gentoo':
return '/etc/nftables'
else:
return False
def version():
'''
Return version from nftables --version
CLI Example:
.. code-block:: bash
salt '*' nftables.version
'''
cmd = '{0} --version' . format(_nftables_cmd())
out = __salt__['cmd.run'](cmd).split()
return out[1]
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_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' nftables.check_chain filter input
IPv6:
salt '*' nftables.check_chain filter input family=ipv6
'''
ret = {'comment': '',
'result': False}
if not chain:
ret['comment'] = 'Chain needs to be specified'
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))
if out == -1:
ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\
format(chain, table, family)
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\
format(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_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.new_table filter
IPv6:
salt '*' nftables.new_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} created'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be created'.\
format(table, family)
return ret
def delete_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_table filter
IPv6:
salt '*' nftables.delete_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} deleted'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be deleted'.\
format(table, family)
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 delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete the chain from the specified table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_chain filter input
salt '*' nftables.delete_chain filter foo
IPv6:
salt '*' nftables.delete_chain filter input family=ipv6
salt '*' nftables.delete_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 not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete chain {1} {2} {3}'.\
format(_nftables_cmd(), nft_family, table, chain)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Chain {0} in table {1} in family {2} deleted'.\
format(chain, table, family)
ret['result'] = True
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} could not be deleted'.\
format(chain, table, family)
return ret
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table & 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.append filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.append filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to append rule {0} to chain {1} in table {2}.'.format(rule, chain, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table & chain, at the specified position.
If position is not specified, rule will be inserted in first position.
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 Examples:
.. code-block:: bash
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept'
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to insert rule {0} to table {1}.'.format(rule, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
if position:
cmd = '{0} insert rule {1} {2} {3} position {4} {5}'.\
format(_nftables_cmd(), nft_family, table, chain, position, rule)
else:
cmd = '{0} insert rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table & chain, specifying either the rule
in its entirety, or the rule's position in the 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 Examples:
.. code-block:: bash
salt '*' nftables.delete filter input position=3
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.delete filter input position=3 family=ipv6
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to delete rule {0} in table {1}.'.format(rule, table),
'result': False}
if position and rule:
ret['comment'] = 'Only specify a position or a rule, not both'
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']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} does not exist'.\
format(rule, chain, table, family)
return ret
# nftables rules can only be deleted using the handle
# if we don't have it, find it.
if not position:
position = get_rule_handle(table, chain, rule, family)
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete rule {1} {2} {3} handle {4}'.\
format(_nftables_cmd(), nft_family, table, chain, position)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Deleted rule "{0}" in chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to delete rule "{0}" in chain {1} table {2} in family {3}'.\
format(rule, 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
|
saltstack/salt
|
salt/modules/nftables.py
|
check_table
|
python
|
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
|
Check for the existence of a table
CLI Example::
salt '*' nftables.check_table nat
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nftables.py#L522-L548
|
[
"def _nftables_cmd():\n '''\n Return correct command\n '''\n return 'nft'\n"
] |
# -*- coding: utf-8 -*-
'''
Support for nftables
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import (
CommandExecutionError
)
# Set up logging
log = logging.getLogger(__name__)
_NFTABLES_FAMILIES = {
'ipv4': 'ip',
'ip4': 'ip',
'ip': 'ip',
'ipv6': 'ip6',
'ip6': 'ip6',
'inet': 'inet',
'arp': 'arp',
'bridge': 'bridge',
'netdev': 'netdev'
}
def __virtual__():
'''
Only load the module if nftables is installed
'''
if salt.utils.path.which('nft'):
return 'nftables'
return (False, 'The nftables execution module failed to load: nftables is not installed.')
def _nftables_cmd():
'''
Return correct command
'''
return 'nft'
def _conf(family='ip'):
'''
Use the same file for rules for now.
'''
if __grains__['os_family'] == 'RedHat':
return '/etc/nftables'
elif __grains__['os_family'] == 'Arch':
return '/etc/nftables'
elif __grains__['os_family'] == 'Debian':
return '/etc/nftables'
elif __grains__['os_family'] == 'Gentoo':
return '/etc/nftables'
else:
return False
def version():
'''
Return version from nftables --version
CLI Example:
.. code-block:: bash
salt '*' nftables.version
'''
cmd = '{0} --version' . format(_nftables_cmd())
out = __salt__['cmd.run'](cmd).split()
return out[1]
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_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' nftables.check_chain filter input
IPv6:
salt '*' nftables.check_chain filter input family=ipv6
'''
ret = {'comment': '',
'result': False}
if not chain:
ret['comment'] = 'Chain needs to be specified'
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))
if out == -1:
ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\
format(chain, table, family)
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\
format(chain, table, family)
ret['result'] = True
return ret
def new_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.new_table filter
IPv6:
salt '*' nftables.new_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} created'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be created'.\
format(table, family)
return ret
def delete_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_table filter
IPv6:
salt '*' nftables.delete_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} deleted'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be deleted'.\
format(table, family)
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 delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete the chain from the specified table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_chain filter input
salt '*' nftables.delete_chain filter foo
IPv6:
salt '*' nftables.delete_chain filter input family=ipv6
salt '*' nftables.delete_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 not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete chain {1} {2} {3}'.\
format(_nftables_cmd(), nft_family, table, chain)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Chain {0} in table {1} in family {2} deleted'.\
format(chain, table, family)
ret['result'] = True
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} could not be deleted'.\
format(chain, table, family)
return ret
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table & 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.append filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.append filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to append rule {0} to chain {1} in table {2}.'.format(rule, chain, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table & chain, at the specified position.
If position is not specified, rule will be inserted in first position.
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 Examples:
.. code-block:: bash
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept'
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to insert rule {0} to table {1}.'.format(rule, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
if position:
cmd = '{0} insert rule {1} {2} {3} position {4} {5}'.\
format(_nftables_cmd(), nft_family, table, chain, position, rule)
else:
cmd = '{0} insert rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table & chain, specifying either the rule
in its entirety, or the rule's position in the 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 Examples:
.. code-block:: bash
salt '*' nftables.delete filter input position=3
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.delete filter input position=3 family=ipv6
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to delete rule {0} in table {1}.'.format(rule, table),
'result': False}
if position and rule:
ret['comment'] = 'Only specify a position or a rule, not both'
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']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} does not exist'.\
format(rule, chain, table, family)
return ret
# nftables rules can only be deleted using the handle
# if we don't have it, find it.
if not position:
position = get_rule_handle(table, chain, rule, family)
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete rule {1} {2} {3} handle {4}'.\
format(_nftables_cmd(), nft_family, table, chain, position)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Deleted rule "{0}" in chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to delete rule "{0}" in chain {1} table {2} in family {3}'.\
format(rule, 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
|
saltstack/salt
|
salt/modules/nftables.py
|
new_chain
|
python
|
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
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nftables.py#L631-L694
|
[
"def check_chain(table='filter', chain=None, family='ipv4'):\n '''\n .. versionadded:: 2014.7.0\n\n Check for the existence of a chain in the table\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nftables.check_chain filter input\n\n IPv6:\n salt '*' nftables.check_chain filter input family=ipv6\n '''\n\n ret = {'comment': '',\n 'result': False}\n\n if not chain:\n ret['comment'] = 'Chain needs to be specified'\n return ret\n\n nft_family = _NFTABLES_FAMILIES[family]\n cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)\n out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))\n\n if out == -1:\n ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\\\n format(chain, table, family)\n else:\n ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\\\n format(chain, table, family)\n ret['result'] = True\n return ret\n",
"def _nftables_cmd():\n '''\n Return correct command\n '''\n return 'nft'\n",
"def check_table(table=None, family='ipv4'):\n '''\n Check for the existence of a table\n\n CLI Example::\n\n salt '*' nftables.check_table nat\n '''\n ret = {'comment': '',\n 'result': False}\n\n if not table:\n ret['comment'] = 'Table needs to be specified'\n return ret\n\n nft_family = _NFTABLES_FAMILIES[family]\n cmd = '{0} list tables {1}' . format(_nftables_cmd(), nft_family)\n out = __salt__['cmd.run'](cmd, python_shell=False).find('table {0} {1}'.format(nft_family, table))\n\n if out == -1:\n ret['comment'] = 'Table {0} in family {1} does not exist'.\\\n format(table, family)\n else:\n ret['comment'] = 'Table {0} in family {1} exists'.\\\n format(table, family)\n ret['result'] = True\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for nftables
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import (
CommandExecutionError
)
# Set up logging
log = logging.getLogger(__name__)
_NFTABLES_FAMILIES = {
'ipv4': 'ip',
'ip4': 'ip',
'ip': 'ip',
'ipv6': 'ip6',
'ip6': 'ip6',
'inet': 'inet',
'arp': 'arp',
'bridge': 'bridge',
'netdev': 'netdev'
}
def __virtual__():
'''
Only load the module if nftables is installed
'''
if salt.utils.path.which('nft'):
return 'nftables'
return (False, 'The nftables execution module failed to load: nftables is not installed.')
def _nftables_cmd():
'''
Return correct command
'''
return 'nft'
def _conf(family='ip'):
'''
Use the same file for rules for now.
'''
if __grains__['os_family'] == 'RedHat':
return '/etc/nftables'
elif __grains__['os_family'] == 'Arch':
return '/etc/nftables'
elif __grains__['os_family'] == 'Debian':
return '/etc/nftables'
elif __grains__['os_family'] == 'Gentoo':
return '/etc/nftables'
else:
return False
def version():
'''
Return version from nftables --version
CLI Example:
.. code-block:: bash
salt '*' nftables.version
'''
cmd = '{0} --version' . format(_nftables_cmd())
out = __salt__['cmd.run'](cmd).split()
return out[1]
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_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' nftables.check_chain filter input
IPv6:
salt '*' nftables.check_chain filter input family=ipv6
'''
ret = {'comment': '',
'result': False}
if not chain:
ret['comment'] = 'Chain needs to be specified'
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))
if out == -1:
ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\
format(chain, table, family)
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\
format(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_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.new_table filter
IPv6:
salt '*' nftables.new_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} created'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be created'.\
format(table, family)
return ret
def delete_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_table filter
IPv6:
salt '*' nftables.delete_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} deleted'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be deleted'.\
format(table, family)
return ret
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete the chain from the specified table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_chain filter input
salt '*' nftables.delete_chain filter foo
IPv6:
salt '*' nftables.delete_chain filter input family=ipv6
salt '*' nftables.delete_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 not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete chain {1} {2} {3}'.\
format(_nftables_cmd(), nft_family, table, chain)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Chain {0} in table {1} in family {2} deleted'.\
format(chain, table, family)
ret['result'] = True
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} could not be deleted'.\
format(chain, table, family)
return ret
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table & 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.append filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.append filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to append rule {0} to chain {1} in table {2}.'.format(rule, chain, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table & chain, at the specified position.
If position is not specified, rule will be inserted in first position.
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 Examples:
.. code-block:: bash
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept'
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to insert rule {0} to table {1}.'.format(rule, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
if position:
cmd = '{0} insert rule {1} {2} {3} position {4} {5}'.\
format(_nftables_cmd(), nft_family, table, chain, position, rule)
else:
cmd = '{0} insert rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table & chain, specifying either the rule
in its entirety, or the rule's position in the 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 Examples:
.. code-block:: bash
salt '*' nftables.delete filter input position=3
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.delete filter input position=3 family=ipv6
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to delete rule {0} in table {1}.'.format(rule, table),
'result': False}
if position and rule:
ret['comment'] = 'Only specify a position or a rule, not both'
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']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} does not exist'.\
format(rule, chain, table, family)
return ret
# nftables rules can only be deleted using the handle
# if we don't have it, find it.
if not position:
position = get_rule_handle(table, chain, rule, family)
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete rule {1} {2} {3} handle {4}'.\
format(_nftables_cmd(), nft_family, table, chain, position)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Deleted rule "{0}" in chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to delete rule "{0}" in chain {1} table {2} in family {3}'.\
format(rule, 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
|
saltstack/salt
|
salt/modules/nftables.py
|
flush
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nftables.py#L948-L993
|
[
"def check_chain(table='filter', chain=None, family='ipv4'):\n '''\n .. versionadded:: 2014.7.0\n\n Check for the existence of a chain in the table\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nftables.check_chain filter input\n\n IPv6:\n salt '*' nftables.check_chain filter input family=ipv6\n '''\n\n ret = {'comment': '',\n 'result': False}\n\n if not chain:\n ret['comment'] = 'Chain needs to be specified'\n return ret\n\n nft_family = _NFTABLES_FAMILIES[family]\n cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)\n out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))\n\n if out == -1:\n ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\\\n format(chain, table, family)\n else:\n ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\\\n format(chain, table, family)\n ret['result'] = True\n return ret\n",
"def _nftables_cmd():\n '''\n Return correct command\n '''\n return 'nft'\n",
"def check_table(table=None, family='ipv4'):\n '''\n Check for the existence of a table\n\n CLI Example::\n\n salt '*' nftables.check_table nat\n '''\n ret = {'comment': '',\n 'result': False}\n\n if not table:\n ret['comment'] = 'Table needs to be specified'\n return ret\n\n nft_family = _NFTABLES_FAMILIES[family]\n cmd = '{0} list tables {1}' . format(_nftables_cmd(), nft_family)\n out = __salt__['cmd.run'](cmd, python_shell=False).find('table {0} {1}'.format(nft_family, table))\n\n if out == -1:\n ret['comment'] = 'Table {0} in family {1} does not exist'.\\\n format(table, family)\n else:\n ret['comment'] = 'Table {0} in family {1} exists'.\\\n format(table, family)\n ret['result'] = True\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for nftables
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import (
CommandExecutionError
)
# Set up logging
log = logging.getLogger(__name__)
_NFTABLES_FAMILIES = {
'ipv4': 'ip',
'ip4': 'ip',
'ip': 'ip',
'ipv6': 'ip6',
'ip6': 'ip6',
'inet': 'inet',
'arp': 'arp',
'bridge': 'bridge',
'netdev': 'netdev'
}
def __virtual__():
'''
Only load the module if nftables is installed
'''
if salt.utils.path.which('nft'):
return 'nftables'
return (False, 'The nftables execution module failed to load: nftables is not installed.')
def _nftables_cmd():
'''
Return correct command
'''
return 'nft'
def _conf(family='ip'):
'''
Use the same file for rules for now.
'''
if __grains__['os_family'] == 'RedHat':
return '/etc/nftables'
elif __grains__['os_family'] == 'Arch':
return '/etc/nftables'
elif __grains__['os_family'] == 'Debian':
return '/etc/nftables'
elif __grains__['os_family'] == 'Gentoo':
return '/etc/nftables'
else:
return False
def version():
'''
Return version from nftables --version
CLI Example:
.. code-block:: bash
salt '*' nftables.version
'''
cmd = '{0} --version' . format(_nftables_cmd())
out = __salt__['cmd.run'](cmd).split()
return out[1]
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_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' nftables.check_chain filter input
IPv6:
salt '*' nftables.check_chain filter input family=ipv6
'''
ret = {'comment': '',
'result': False}
if not chain:
ret['comment'] = 'Chain needs to be specified'
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} list table {1} {2}' . format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False).find('chain {0} {{'.format(chain))
if out == -1:
ret['comment'] = 'Chain {0} in table {1} in family {2} does not exist'.\
format(chain, table, family)
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} exists'.\
format(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_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.new_table filter
IPv6:
salt '*' nftables.new_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} created'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be created'.\
format(table, family)
return ret
def delete_table(table, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new custom table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_table filter
IPv6:
salt '*' nftables.delete_table filter family=ipv6
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
res = check_table(table, family=family)
if not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete table {1} {2}'.format(_nftables_cmd(), nft_family, table)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Table {0} in family {1} deleted'.\
format(table, family)
ret['result'] = True
else:
ret['comment'] = 'Table {0} in family {1} could not be deleted'.\
format(table, family)
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 delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete the chain from the specified table.
CLI Example:
.. code-block:: bash
salt '*' nftables.delete_chain filter input
salt '*' nftables.delete_chain filter foo
IPv6:
salt '*' nftables.delete_chain filter input family=ipv6
salt '*' nftables.delete_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 not res['result']:
return res
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete chain {1} {2} {3}'.\
format(_nftables_cmd(), nft_family, table, chain)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
ret['comment'] = 'Chain {0} in table {1} in family {2} deleted'.\
format(chain, table, family)
ret['result'] = True
else:
ret['comment'] = 'Chain {0} in table {1} in family {2} could not be deleted'.\
format(chain, table, family)
return ret
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table & 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.append filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.append filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to append rule {0} to chain {1} in table {2}.'.format(rule, chain, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} add rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table & chain, at the specified position.
If position is not specified, rule will be inserted in first position.
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 Examples:
.. code-block:: bash
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept'
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.insert filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
salt '*' nftables.insert filter input position=3 \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to insert rule {0} to table {1}.'.format(rule, table),
'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 res['result']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} already exists'.\
format(rule, chain, table, family)
return ret
nft_family = _NFTABLES_FAMILIES[family]
if position:
cmd = '{0} insert rule {1} {2} {3} position {4} {5}'.\
format(_nftables_cmd(), nft_family, table, chain, position, rule)
else:
cmd = '{0} insert rule {1} {2} {3} {4}'.\
format(_nftables_cmd(), nft_family, table, chain, rule)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Added rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to add rule "{0}" chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
return ret
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table & chain, specifying either the rule
in its entirety, or the rule's position in the 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 Examples:
.. code-block:: bash
salt '*' nftables.delete filter input position=3
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept'
IPv6:
salt '*' nftables.delete filter input position=3 family=ipv6
salt '*' nftables.delete filter input \\
rule='tcp dport 22 log accept' \\
family=ipv6
'''
ret = {'comment': 'Failed to delete rule {0} in table {1}.'.format(rule, table),
'result': False}
if position and rule:
ret['comment'] = 'Only specify a position or a rule, not both'
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']:
ret['comment'] = 'Rule {0} chain {1} in table {2} in family {3} does not exist'.\
format(rule, chain, table, family)
return ret
# nftables rules can only be deleted using the handle
# if we don't have it, find it.
if not position:
position = get_rule_handle(table, chain, rule, family)
nft_family = _NFTABLES_FAMILIES[family]
cmd = '{0} delete rule {1} {2} {3} handle {4}'.\
format(_nftables_cmd(), nft_family, table, chain, position)
out = __salt__['cmd.run'](cmd, python_shell=False)
if len(out) == 0:
ret['result'] = True
ret['comment'] = 'Deleted rule "{0}" in chain {1} in table {2} in family {3}.'.\
format(rule, chain, table, family)
else:
ret['comment'] = 'Failed to delete rule "{0}" in chain {1} table {2} in family {3}'.\
format(rule, chain, table, family)
return ret
|
saltstack/salt
|
salt/renderers/stateconf.py
|
rewrite_single_shorthand_state_decl
|
python
|
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: []}
|
Rewrite all state declarations that look like this::
state_id_decl:
state.func
into::
state_id_decl:
state.func: []
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/stateconf.py#L251-L265
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
A flexible renderer that takes a templating engine and a data format
:maintainer: Jack Kuan <kjkuan@gmail.com>
:maturity: new
:platform: all
'''
# See http://docs.saltstack.org/en/latest/ref/renderers/all/salt.renderers.stateconf.html
# for a guide to using this module.
#
# FIXME: I really need to review and simplify this renderer, it's getting out of hand!
#
# TODO:
# - sls meta/info state: E.g.,
#
# sls_info:
# stateconf.set:
# - author: Jack Kuan
# - description: what the salt file does...
# - version: 0.1.0
#
# - version constraint for 'include'. E.g.,
#
# include:
# - apache: >= 0.1.0
#
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
import getopt
import copy
# Import salt libs
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import SaltRenderError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error
__all__ = ['render']
log = logging.getLogger(__name__)
__opts__ = {
'stateconf_end_marker': r'#\s*-+\s*end of state config\s*-+',
# e.g., something like "# --- end of state config --" works by default.
'stateconf_start_state': '.start',
# name of the state id for the generated start state.
'stateconf_goal_state': '.goal',
# name of the state id for the generated goal state.
'stateconf_state_func': 'stateconf.set'
# names the state and the state function to be recognized as a special
# state from which to gather sls file context variables. It should be
# specified in the 'state.func' notation, and both the state module and
# the function must actually exist and the function should be a dummy,
# no-op state function that simply returns a
# dict(name=name, result=True, changes={}, comment='')
}
STATE_FUNC = STATE_NAME = ''
def __init__(opts):
global STATE_NAME, STATE_FUNC
STATE_FUNC = __opts__['stateconf_state_func']
STATE_NAME = STATE_FUNC.split('.')[0]
MOD_BASENAME = os.path.basename(__file__)
INVALID_USAGE_ERROR = SaltRenderError(
'Invalid use of {0} renderer!\n'
'''Usage: #!{0} [-GoSp] [<data_renderer> [options] . <template_renderer> [options]]
where an example <data_renderer> would be yaml and a <template_renderer> might
be jinja. Each renderer can be passed its renderer specific options.
Options(for this renderer):
-G Do not generate the goal state that requires all other states in the sls.
-o Indirectly order the states by adding requires such that they will be
executed in the order they are defined in the sls. Implies using yaml -o.
-s Generate the start state that gets inserted as the first state in
the sls. This only makes sense if your high state data dict is ordered.
-p Assume high state input. This option allows you to pipe high state data
through this renderer. With this option, the use of stateconf.set state
in the sls will have no effect, but other features of the renderer still
apply.
'''.format(MOD_BASENAME)
)
def render(input, saltenv='base', sls='', argline='', **kws):
gen_start_state = False
no_goal_state = False
implicit_require = False
def process_sls_data(data, context=None, extract=False):
sls_dir = os.path.dirname(sls.replace('.', os.path.sep)) if '.' in sls else sls
ctx = dict(sls_dir=sls_dir if sls_dir else '.')
if context:
ctx.update(context)
tmplout = render_template(
StringIO(data), saltenv, sls, context=ctx,
argline=rt_argline.strip(), **kws
)
high = render_data(tmplout, saltenv, sls, argline=rd_argline.strip())
return process_high_data(high, extract)
def process_high_data(high, extract):
# make a copy so that the original, un-preprocessed highstate data
# structure can be used later for error checking if anything goes
# wrong during the preprocessing.
data = copy.deepcopy(high)
try:
rewrite_single_shorthand_state_decl(data)
rewrite_sls_includes_excludes(data, sls, saltenv)
if not extract and implicit_require:
sid = has_names_decls(data)
if sid:
raise SaltRenderError(
'\'names\' declaration(found in state id: {0}) is '
'not supported with implicitly ordered states! You '
'should generate the states in a template for-loop '
'instead.'.format(sid)
)
add_implicit_requires(data)
if gen_start_state:
add_start_state(data, sls)
if not extract and not no_goal_state:
add_goal_state(data)
rename_state_ids(data, sls)
# We must extract no matter what so extending a stateconf sls file
# works!
extract_state_confs(data)
except SaltRenderError:
raise
except Exception as err:
log.exception(
'Error found while pre-processing the salt file %s:\n%s',
sls, err
)
from salt.state import State
state = State(__opts__)
errors = state.verify_high(high)
if errors:
raise SaltRenderError('\n'.join(errors))
raise SaltRenderError('sls preprocessing/rendering failed!')
return data
# ----------------------
renderers = kws['renderers']
opts, args = getopt.getopt(argline.split(), 'Gosp')
argline = ' '.join(args) if args else 'yaml . jinja'
if ('-G', '') in opts:
no_goal_state = True
if ('-o', '') in opts:
implicit_require = True
if ('-s', '') in opts:
gen_start_state = True
if ('-p', '') in opts:
data = process_high_data(input, extract=False)
else:
# Split on the first dot surrounded by spaces but not preceded by a
# backslash. A backslash preceded dot will be replaced with just dot.
args = [
arg.strip().replace('\\.', '.')
for arg in re.split(r'\s+(?<!\\)\.\s+', argline, 1)
]
try:
name, rd_argline = (args[0] + ' ').split(' ', 1)
render_data = renderers[name] # e.g., the yaml renderer
if implicit_require:
if name == 'yaml':
rd_argline = '-o ' + rd_argline
else:
raise SaltRenderError(
'Implicit ordering is only supported if the yaml renderer '
'is used!'
)
name, rt_argline = (args[1] + ' ').split(' ', 1)
render_template = renderers[name] # e.g., the mako renderer
except KeyError as err:
raise SaltRenderError('Renderer: {0} is not available!'.format(err))
except IndexError:
raise INVALID_USAGE_ERROR
if isinstance(input, six.string_types):
with salt.utils.files.fopen(input, 'r') as ifile:
sls_templ = salt.utils.stringutils.to_unicode(ifile.read())
else: # assume file-like
sls_templ = salt.utils.stringutils.to_unicode(input.read())
# first pass to extract the state configuration
match = re.search(__opts__['stateconf_end_marker'], sls_templ)
if match:
process_sls_data(sls_templ[:match.start()], extract=True)
# if some config has been extracted then remove the sls-name prefix
# of the keys in the extracted stateconf.set context to make them easier
# to use in the salt file.
if STATE_CONF:
tmplctx = STATE_CONF.copy()
if tmplctx:
prefix = sls + '::'
for k in six.iterkeys(tmplctx): # iterate over a copy of keys
if k.startswith(prefix):
tmplctx[k[len(prefix):]] = tmplctx[k]
del tmplctx[k]
else:
tmplctx = {}
# do a second pass that provides the extracted conf as template context
data = process_sls_data(sls_templ, tmplctx)
if log.isEnabledFor(logging.DEBUG):
import pprint # FIXME: pprint OrderedDict
log.debug('Rendered sls: %s', pprint.pformat(data))
return data
def has_names_decls(data):
for sid, _, _, args in statelist(data):
if sid == 'extend':
continue
for _ in nvlist(args, ['names']):
return sid
def rewrite_sls_includes_excludes(data, sls, saltenv):
# if the path of the included/excluded sls starts with a leading dot(.)
# then it's taken to be relative to the including/excluding sls.
for sid in data:
if sid == 'include':
includes = data[sid]
for i, each in enumerate(includes):
if isinstance(each, dict):
slsenv, incl = each.popitem()
else:
slsenv = saltenv
incl = each
if incl.startswith('.'):
includes[i] = {slsenv: _relative_to_abs_sls(incl, sls)}
elif sid == 'exclude':
for sdata in data[sid]:
if 'sls' in sdata and sdata['sls'].startswith('.'):
sdata['sls'] = _relative_to_abs_sls(sdata['sls'], sls)
def _local_to_abs_sid(sid, sls): # id must starts with '.'
if '::' in sid:
return _relative_to_abs_sls(sid, sls)
else:
abs_sls = _relative_to_abs_sls(sid, sls + '.')
return '::'.join(abs_sls.rsplit('.', 1))
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 statelist(states_dict, sid_excludes=frozenset(['include', 'exclude'])):
for sid, states in six.iteritems(states_dict):
if sid.startswith('__'):
continue
if sid in sid_excludes:
continue
for sname, args in six.iteritems(states):
if sname.startswith('__'):
continue
yield sid, states, sname, args
REQUISITES = ('require', 'require_in', 'watch', 'watch_in', 'use', 'use_in', 'listen', 'listen_in', 'onchanges',
'onchanges_in', 'onfail', 'onfail_in')
def rename_state_ids(data, sls, is_extend=False):
# if the .sls file is salt://my/salt/file.sls
# then rename all state ids defined in it that start with a dot(.) with
# "my.salt.file::" + the_state_id_without_the_first_dot.
# update "local" references to the renamed states.
if 'extend' in data and not is_extend:
rename_state_ids(data['extend'], sls, True)
for sid, _, _, args in statelist(data):
for req, sname, sid in nvlist2(args, REQUISITES):
if sid.startswith('.'):
req[sname] = _local_to_abs_sid(sid, sls)
for sid in list(data):
if sid.startswith('.'):
newsid = _local_to_abs_sid(sid, sls)
if newsid in data:
raise SaltRenderError(
'Can\'t rename state id({0}) into {1} because the later '
'already exists!'.format(sid, newsid)
)
# add a '- name: sid' to those states without '- name'.
for sname, args in six.iteritems(data[sid]):
if state_name(sname) == STATE_NAME:
continue
for arg in args:
if isinstance(arg, dict) and next(iter(arg)) == 'name':
break
else:
# then no '- name: ...' is defined in the state args
# add the sid without the leading dot as the name.
args.insert(0, dict(name=sid[1:]))
data[newsid] = data[sid]
del data[sid]
REQUIRE = ('require', 'watch', 'listen', 'onchanges', 'onfail')
REQUIRE_IN = ('require_in', 'watch_in', 'listen_in', 'onchanges_in', 'onfail_in')
EXTENDED_REQUIRE = {}
EXTENDED_REQUIRE_IN = {}
from itertools import chain
# To avoid cycles among states when each state requires the one before it:
# explicit require/watch/listen/onchanges/onfail can only contain states before it
# explicit require_in/watch_in/listen_in/onchanges_in/onfail_in can only contain states after it
def add_implicit_requires(data):
def T(sid, state): # pylint: disable=C0103
return '{0}:{1}'.format(sid, state_name(state))
states_before = set()
states_after = set()
for sid in data:
for state in data[sid]:
states_after.add(T(sid, state))
prev_state = (None, None) # (state_name, sid)
for sid, states, sname, args in statelist(data):
if sid == 'extend':
for esid, _, _, eargs in statelist(states):
for _, rstate, rsid in nvlist2(eargs, REQUIRE):
EXTENDED_REQUIRE.setdefault(
T(esid, rstate), []).append((None, rstate, rsid))
for _, rstate, rsid in nvlist2(eargs, REQUIRE_IN):
EXTENDED_REQUIRE_IN.setdefault(
T(esid, rstate), []).append((None, rstate, rsid))
continue
tag = T(sid, sname)
states_after.remove(tag)
reqs = nvlist2(args, REQUIRE)
if tag in EXTENDED_REQUIRE:
reqs = chain(reqs, EXTENDED_REQUIRE[tag])
for _, rstate, rsid in reqs:
if T(rsid, rstate) in states_after:
raise SaltRenderError(
'State({0}) can\'t require/watch/listen/onchanges/onfail a state({1}) defined '
'after it!'.format(tag, T(rsid, rstate))
)
reqs = nvlist2(args, REQUIRE_IN)
if tag in EXTENDED_REQUIRE_IN:
reqs = chain(reqs, EXTENDED_REQUIRE_IN[tag])
for _, rstate, rsid in reqs:
if T(rsid, rstate) in states_before:
raise SaltRenderError(
'State({0}) can\'t require_in/watch_in/listen_in/onchanges_in/onfail_in a state({1}) '
'defined before it!'.format(tag, T(rsid, rstate))
)
# add a (- state: sid) item, at the beginning of the require of this
# state if there's a state before this one.
if prev_state[0] is not None:
try:
next(nvlist(args, ['require']))[2].insert(0, dict([prev_state]))
except StopIteration: # i.e., there's no require
args.append(dict(require=[dict([prev_state])]))
states_before.add(tag)
prev_state = (state_name(sname), sid)
def add_start_state(data, sls):
start_sid = __opts__['stateconf_start_state']
if start_sid in data:
raise SaltRenderError(
'Can\'t generate start state({0})! The same state id already '
'exists!'.format(start_sid)
)
if not data:
return
# the start state is either the first state whose id declaration has
# no __sls__, or it's the first state whose id declaration has a
# __sls__ == sls.
non_sids = ('include', 'exclude', 'extend')
for sid, states in six.iteritems(data):
if sid in non_sids or sid.startswith('__'):
continue
if '__sls__' not in states or states['__sls__'] == sls:
break
else:
raise SaltRenderError('Can\'t determine the first state in the sls file!')
reqin = {state_name(next(six.iterkeys(data[sid]))): sid}
data[start_sid] = {STATE_FUNC: [{'require_in': [reqin]}]}
def add_goal_state(data):
goal_sid = __opts__['stateconf_goal_state']
if goal_sid in data:
raise SaltRenderError(
'Can\'t generate goal state({0})! The same state id already '
'exists!'.format(goal_sid)
)
else:
reqlist = []
for sid, states, state, _ in \
statelist(data, ('include', 'exclude', 'extend')):
if '__sls__' in states:
# Then id declaration must have been included from a
# rendered sls. Currently, this is only possible with
# pydsl's high state output.
continue
reqlist.append({state_name(state): sid})
data[goal_sid] = {STATE_FUNC: [dict(require=reqlist)]}
def state_name(sname):
'''
Return the name of the state regardless if sname is
just the state name or a state.func name.
'''
return sname.split('.', 1)[0]
# Quick and dirty way to get attribute access for dictionary keys.
# So, we can do: ${apache.port} instead of ${apache['port']} when possible.
class Bunch(dict):
def __getattr__(self, name):
return self[name]
# With sls:
#
# state_id:
# stateconf.set:
# - name1: value1
#
# STATE_CONF is:
# { state_id => {name1: value1} }
#
STATE_CONF = {} # stateconf.set
STATE_CONF_EXT = {} # stateconf.set under extend: ...
def extract_state_confs(data, is_extend=False):
for state_id, state_dict in six.iteritems(data):
if state_id == 'extend' and not is_extend:
extract_state_confs(state_dict, True)
continue
if STATE_NAME in state_dict:
key = STATE_NAME
elif STATE_FUNC in state_dict:
key = STATE_FUNC
else:
continue
to_dict = STATE_CONF_EXT if is_extend else STATE_CONF
conf = to_dict.setdefault(state_id, Bunch())
for sdk in state_dict[key]:
if not isinstance(sdk, dict):
continue
key, val = next(six.iteritems(sdk))
conf[key] = val
if not is_extend and state_id in STATE_CONF_EXT:
extend = STATE_CONF_EXT[state_id]
for requisite in 'require', 'watch', 'listen', 'onchanges', 'onfail':
if requisite in extend:
extend[requisite] += to_dict[state_id].get(requisite, [])
to_dict[state_id].update(STATE_CONF_EXT[state_id])
|
saltstack/salt
|
salt/renderers/stateconf.py
|
_relative_to_abs_sls
|
python
|
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])
|
Convert ``relative`` sls reference into absolute, relative to ``sls``.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/stateconf.py#L296-L307
| null |
# -*- coding: utf-8 -*-
'''
A flexible renderer that takes a templating engine and a data format
:maintainer: Jack Kuan <kjkuan@gmail.com>
:maturity: new
:platform: all
'''
# See http://docs.saltstack.org/en/latest/ref/renderers/all/salt.renderers.stateconf.html
# for a guide to using this module.
#
# FIXME: I really need to review and simplify this renderer, it's getting out of hand!
#
# TODO:
# - sls meta/info state: E.g.,
#
# sls_info:
# stateconf.set:
# - author: Jack Kuan
# - description: what the salt file does...
# - version: 0.1.0
#
# - version constraint for 'include'. E.g.,
#
# include:
# - apache: >= 0.1.0
#
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
import getopt
import copy
# Import salt libs
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import SaltRenderError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error
__all__ = ['render']
log = logging.getLogger(__name__)
__opts__ = {
'stateconf_end_marker': r'#\s*-+\s*end of state config\s*-+',
# e.g., something like "# --- end of state config --" works by default.
'stateconf_start_state': '.start',
# name of the state id for the generated start state.
'stateconf_goal_state': '.goal',
# name of the state id for the generated goal state.
'stateconf_state_func': 'stateconf.set'
# names the state and the state function to be recognized as a special
# state from which to gather sls file context variables. It should be
# specified in the 'state.func' notation, and both the state module and
# the function must actually exist and the function should be a dummy,
# no-op state function that simply returns a
# dict(name=name, result=True, changes={}, comment='')
}
STATE_FUNC = STATE_NAME = ''
def __init__(opts):
global STATE_NAME, STATE_FUNC
STATE_FUNC = __opts__['stateconf_state_func']
STATE_NAME = STATE_FUNC.split('.')[0]
MOD_BASENAME = os.path.basename(__file__)
INVALID_USAGE_ERROR = SaltRenderError(
'Invalid use of {0} renderer!\n'
'''Usage: #!{0} [-GoSp] [<data_renderer> [options] . <template_renderer> [options]]
where an example <data_renderer> would be yaml and a <template_renderer> might
be jinja. Each renderer can be passed its renderer specific options.
Options(for this renderer):
-G Do not generate the goal state that requires all other states in the sls.
-o Indirectly order the states by adding requires such that they will be
executed in the order they are defined in the sls. Implies using yaml -o.
-s Generate the start state that gets inserted as the first state in
the sls. This only makes sense if your high state data dict is ordered.
-p Assume high state input. This option allows you to pipe high state data
through this renderer. With this option, the use of stateconf.set state
in the sls will have no effect, but other features of the renderer still
apply.
'''.format(MOD_BASENAME)
)
def render(input, saltenv='base', sls='', argline='', **kws):
gen_start_state = False
no_goal_state = False
implicit_require = False
def process_sls_data(data, context=None, extract=False):
sls_dir = os.path.dirname(sls.replace('.', os.path.sep)) if '.' in sls else sls
ctx = dict(sls_dir=sls_dir if sls_dir else '.')
if context:
ctx.update(context)
tmplout = render_template(
StringIO(data), saltenv, sls, context=ctx,
argline=rt_argline.strip(), **kws
)
high = render_data(tmplout, saltenv, sls, argline=rd_argline.strip())
return process_high_data(high, extract)
def process_high_data(high, extract):
# make a copy so that the original, un-preprocessed highstate data
# structure can be used later for error checking if anything goes
# wrong during the preprocessing.
data = copy.deepcopy(high)
try:
rewrite_single_shorthand_state_decl(data)
rewrite_sls_includes_excludes(data, sls, saltenv)
if not extract and implicit_require:
sid = has_names_decls(data)
if sid:
raise SaltRenderError(
'\'names\' declaration(found in state id: {0}) is '
'not supported with implicitly ordered states! You '
'should generate the states in a template for-loop '
'instead.'.format(sid)
)
add_implicit_requires(data)
if gen_start_state:
add_start_state(data, sls)
if not extract and not no_goal_state:
add_goal_state(data)
rename_state_ids(data, sls)
# We must extract no matter what so extending a stateconf sls file
# works!
extract_state_confs(data)
except SaltRenderError:
raise
except Exception as err:
log.exception(
'Error found while pre-processing the salt file %s:\n%s',
sls, err
)
from salt.state import State
state = State(__opts__)
errors = state.verify_high(high)
if errors:
raise SaltRenderError('\n'.join(errors))
raise SaltRenderError('sls preprocessing/rendering failed!')
return data
# ----------------------
renderers = kws['renderers']
opts, args = getopt.getopt(argline.split(), 'Gosp')
argline = ' '.join(args) if args else 'yaml . jinja'
if ('-G', '') in opts:
no_goal_state = True
if ('-o', '') in opts:
implicit_require = True
if ('-s', '') in opts:
gen_start_state = True
if ('-p', '') in opts:
data = process_high_data(input, extract=False)
else:
# Split on the first dot surrounded by spaces but not preceded by a
# backslash. A backslash preceded dot will be replaced with just dot.
args = [
arg.strip().replace('\\.', '.')
for arg in re.split(r'\s+(?<!\\)\.\s+', argline, 1)
]
try:
name, rd_argline = (args[0] + ' ').split(' ', 1)
render_data = renderers[name] # e.g., the yaml renderer
if implicit_require:
if name == 'yaml':
rd_argline = '-o ' + rd_argline
else:
raise SaltRenderError(
'Implicit ordering is only supported if the yaml renderer '
'is used!'
)
name, rt_argline = (args[1] + ' ').split(' ', 1)
render_template = renderers[name] # e.g., the mako renderer
except KeyError as err:
raise SaltRenderError('Renderer: {0} is not available!'.format(err))
except IndexError:
raise INVALID_USAGE_ERROR
if isinstance(input, six.string_types):
with salt.utils.files.fopen(input, 'r') as ifile:
sls_templ = salt.utils.stringutils.to_unicode(ifile.read())
else: # assume file-like
sls_templ = salt.utils.stringutils.to_unicode(input.read())
# first pass to extract the state configuration
match = re.search(__opts__['stateconf_end_marker'], sls_templ)
if match:
process_sls_data(sls_templ[:match.start()], extract=True)
# if some config has been extracted then remove the sls-name prefix
# of the keys in the extracted stateconf.set context to make them easier
# to use in the salt file.
if STATE_CONF:
tmplctx = STATE_CONF.copy()
if tmplctx:
prefix = sls + '::'
for k in six.iterkeys(tmplctx): # iterate over a copy of keys
if k.startswith(prefix):
tmplctx[k[len(prefix):]] = tmplctx[k]
del tmplctx[k]
else:
tmplctx = {}
# do a second pass that provides the extracted conf as template context
data = process_sls_data(sls_templ, tmplctx)
if log.isEnabledFor(logging.DEBUG):
import pprint # FIXME: pprint OrderedDict
log.debug('Rendered sls: %s', pprint.pformat(data))
return data
def has_names_decls(data):
for sid, _, _, args in statelist(data):
if sid == 'extend':
continue
for _ in nvlist(args, ['names']):
return sid
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 rewrite_sls_includes_excludes(data, sls, saltenv):
# if the path of the included/excluded sls starts with a leading dot(.)
# then it's taken to be relative to the including/excluding sls.
for sid in data:
if sid == 'include':
includes = data[sid]
for i, each in enumerate(includes):
if isinstance(each, dict):
slsenv, incl = each.popitem()
else:
slsenv = saltenv
incl = each
if incl.startswith('.'):
includes[i] = {slsenv: _relative_to_abs_sls(incl, sls)}
elif sid == 'exclude':
for sdata in data[sid]:
if 'sls' in sdata and sdata['sls'].startswith('.'):
sdata['sls'] = _relative_to_abs_sls(sdata['sls'], sls)
def _local_to_abs_sid(sid, sls): # id must starts with '.'
if '::' in sid:
return _relative_to_abs_sls(sid, sls)
else:
abs_sls = _relative_to_abs_sls(sid, sls + '.')
return '::'.join(abs_sls.rsplit('.', 1))
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 statelist(states_dict, sid_excludes=frozenset(['include', 'exclude'])):
for sid, states in six.iteritems(states_dict):
if sid.startswith('__'):
continue
if sid in sid_excludes:
continue
for sname, args in six.iteritems(states):
if sname.startswith('__'):
continue
yield sid, states, sname, args
REQUISITES = ('require', 'require_in', 'watch', 'watch_in', 'use', 'use_in', 'listen', 'listen_in', 'onchanges',
'onchanges_in', 'onfail', 'onfail_in')
def rename_state_ids(data, sls, is_extend=False):
# if the .sls file is salt://my/salt/file.sls
# then rename all state ids defined in it that start with a dot(.) with
# "my.salt.file::" + the_state_id_without_the_first_dot.
# update "local" references to the renamed states.
if 'extend' in data and not is_extend:
rename_state_ids(data['extend'], sls, True)
for sid, _, _, args in statelist(data):
for req, sname, sid in nvlist2(args, REQUISITES):
if sid.startswith('.'):
req[sname] = _local_to_abs_sid(sid, sls)
for sid in list(data):
if sid.startswith('.'):
newsid = _local_to_abs_sid(sid, sls)
if newsid in data:
raise SaltRenderError(
'Can\'t rename state id({0}) into {1} because the later '
'already exists!'.format(sid, newsid)
)
# add a '- name: sid' to those states without '- name'.
for sname, args in six.iteritems(data[sid]):
if state_name(sname) == STATE_NAME:
continue
for arg in args:
if isinstance(arg, dict) and next(iter(arg)) == 'name':
break
else:
# then no '- name: ...' is defined in the state args
# add the sid without the leading dot as the name.
args.insert(0, dict(name=sid[1:]))
data[newsid] = data[sid]
del data[sid]
REQUIRE = ('require', 'watch', 'listen', 'onchanges', 'onfail')
REQUIRE_IN = ('require_in', 'watch_in', 'listen_in', 'onchanges_in', 'onfail_in')
EXTENDED_REQUIRE = {}
EXTENDED_REQUIRE_IN = {}
from itertools import chain
# To avoid cycles among states when each state requires the one before it:
# explicit require/watch/listen/onchanges/onfail can only contain states before it
# explicit require_in/watch_in/listen_in/onchanges_in/onfail_in can only contain states after it
def add_implicit_requires(data):
def T(sid, state): # pylint: disable=C0103
return '{0}:{1}'.format(sid, state_name(state))
states_before = set()
states_after = set()
for sid in data:
for state in data[sid]:
states_after.add(T(sid, state))
prev_state = (None, None) # (state_name, sid)
for sid, states, sname, args in statelist(data):
if sid == 'extend':
for esid, _, _, eargs in statelist(states):
for _, rstate, rsid in nvlist2(eargs, REQUIRE):
EXTENDED_REQUIRE.setdefault(
T(esid, rstate), []).append((None, rstate, rsid))
for _, rstate, rsid in nvlist2(eargs, REQUIRE_IN):
EXTENDED_REQUIRE_IN.setdefault(
T(esid, rstate), []).append((None, rstate, rsid))
continue
tag = T(sid, sname)
states_after.remove(tag)
reqs = nvlist2(args, REQUIRE)
if tag in EXTENDED_REQUIRE:
reqs = chain(reqs, EXTENDED_REQUIRE[tag])
for _, rstate, rsid in reqs:
if T(rsid, rstate) in states_after:
raise SaltRenderError(
'State({0}) can\'t require/watch/listen/onchanges/onfail a state({1}) defined '
'after it!'.format(tag, T(rsid, rstate))
)
reqs = nvlist2(args, REQUIRE_IN)
if tag in EXTENDED_REQUIRE_IN:
reqs = chain(reqs, EXTENDED_REQUIRE_IN[tag])
for _, rstate, rsid in reqs:
if T(rsid, rstate) in states_before:
raise SaltRenderError(
'State({0}) can\'t require_in/watch_in/listen_in/onchanges_in/onfail_in a state({1}) '
'defined before it!'.format(tag, T(rsid, rstate))
)
# add a (- state: sid) item, at the beginning of the require of this
# state if there's a state before this one.
if prev_state[0] is not None:
try:
next(nvlist(args, ['require']))[2].insert(0, dict([prev_state]))
except StopIteration: # i.e., there's no require
args.append(dict(require=[dict([prev_state])]))
states_before.add(tag)
prev_state = (state_name(sname), sid)
def add_start_state(data, sls):
start_sid = __opts__['stateconf_start_state']
if start_sid in data:
raise SaltRenderError(
'Can\'t generate start state({0})! The same state id already '
'exists!'.format(start_sid)
)
if not data:
return
# the start state is either the first state whose id declaration has
# no __sls__, or it's the first state whose id declaration has a
# __sls__ == sls.
non_sids = ('include', 'exclude', 'extend')
for sid, states in six.iteritems(data):
if sid in non_sids or sid.startswith('__'):
continue
if '__sls__' not in states or states['__sls__'] == sls:
break
else:
raise SaltRenderError('Can\'t determine the first state in the sls file!')
reqin = {state_name(next(six.iterkeys(data[sid]))): sid}
data[start_sid] = {STATE_FUNC: [{'require_in': [reqin]}]}
def add_goal_state(data):
goal_sid = __opts__['stateconf_goal_state']
if goal_sid in data:
raise SaltRenderError(
'Can\'t generate goal state({0})! The same state id already '
'exists!'.format(goal_sid)
)
else:
reqlist = []
for sid, states, state, _ in \
statelist(data, ('include', 'exclude', 'extend')):
if '__sls__' in states:
# Then id declaration must have been included from a
# rendered sls. Currently, this is only possible with
# pydsl's high state output.
continue
reqlist.append({state_name(state): sid})
data[goal_sid] = {STATE_FUNC: [dict(require=reqlist)]}
def state_name(sname):
'''
Return the name of the state regardless if sname is
just the state name or a state.func name.
'''
return sname.split('.', 1)[0]
# Quick and dirty way to get attribute access for dictionary keys.
# So, we can do: ${apache.port} instead of ${apache['port']} when possible.
class Bunch(dict):
def __getattr__(self, name):
return self[name]
# With sls:
#
# state_id:
# stateconf.set:
# - name1: value1
#
# STATE_CONF is:
# { state_id => {name1: value1} }
#
STATE_CONF = {} # stateconf.set
STATE_CONF_EXT = {} # stateconf.set under extend: ...
def extract_state_confs(data, is_extend=False):
for state_id, state_dict in six.iteritems(data):
if state_id == 'extend' and not is_extend:
extract_state_confs(state_dict, True)
continue
if STATE_NAME in state_dict:
key = STATE_NAME
elif STATE_FUNC in state_dict:
key = STATE_FUNC
else:
continue
to_dict = STATE_CONF_EXT if is_extend else STATE_CONF
conf = to_dict.setdefault(state_id, Bunch())
for sdk in state_dict[key]:
if not isinstance(sdk, dict):
continue
key, val = next(six.iteritems(sdk))
conf[key] = val
if not is_extend and state_id in STATE_CONF_EXT:
extend = STATE_CONF_EXT[state_id]
for requisite in 'require', 'watch', 'listen', 'onchanges', 'onfail':
if requisite in extend:
extend[requisite] += to_dict[state_id].get(requisite, [])
to_dict[state_id].update(STATE_CONF_EXT[state_id])
|
saltstack/salt
|
salt/renderers/stateconf.py
|
nvlist
|
python
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/stateconf.py#L310-L331
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
A flexible renderer that takes a templating engine and a data format
:maintainer: Jack Kuan <kjkuan@gmail.com>
:maturity: new
:platform: all
'''
# See http://docs.saltstack.org/en/latest/ref/renderers/all/salt.renderers.stateconf.html
# for a guide to using this module.
#
# FIXME: I really need to review and simplify this renderer, it's getting out of hand!
#
# TODO:
# - sls meta/info state: E.g.,
#
# sls_info:
# stateconf.set:
# - author: Jack Kuan
# - description: what the salt file does...
# - version: 0.1.0
#
# - version constraint for 'include'. E.g.,
#
# include:
# - apache: >= 0.1.0
#
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
import getopt
import copy
# Import salt libs
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import SaltRenderError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error
__all__ = ['render']
log = logging.getLogger(__name__)
__opts__ = {
'stateconf_end_marker': r'#\s*-+\s*end of state config\s*-+',
# e.g., something like "# --- end of state config --" works by default.
'stateconf_start_state': '.start',
# name of the state id for the generated start state.
'stateconf_goal_state': '.goal',
# name of the state id for the generated goal state.
'stateconf_state_func': 'stateconf.set'
# names the state and the state function to be recognized as a special
# state from which to gather sls file context variables. It should be
# specified in the 'state.func' notation, and both the state module and
# the function must actually exist and the function should be a dummy,
# no-op state function that simply returns a
# dict(name=name, result=True, changes={}, comment='')
}
STATE_FUNC = STATE_NAME = ''
def __init__(opts):
global STATE_NAME, STATE_FUNC
STATE_FUNC = __opts__['stateconf_state_func']
STATE_NAME = STATE_FUNC.split('.')[0]
MOD_BASENAME = os.path.basename(__file__)
INVALID_USAGE_ERROR = SaltRenderError(
'Invalid use of {0} renderer!\n'
'''Usage: #!{0} [-GoSp] [<data_renderer> [options] . <template_renderer> [options]]
where an example <data_renderer> would be yaml and a <template_renderer> might
be jinja. Each renderer can be passed its renderer specific options.
Options(for this renderer):
-G Do not generate the goal state that requires all other states in the sls.
-o Indirectly order the states by adding requires such that they will be
executed in the order they are defined in the sls. Implies using yaml -o.
-s Generate the start state that gets inserted as the first state in
the sls. This only makes sense if your high state data dict is ordered.
-p Assume high state input. This option allows you to pipe high state data
through this renderer. With this option, the use of stateconf.set state
in the sls will have no effect, but other features of the renderer still
apply.
'''.format(MOD_BASENAME)
)
def render(input, saltenv='base', sls='', argline='', **kws):
gen_start_state = False
no_goal_state = False
implicit_require = False
def process_sls_data(data, context=None, extract=False):
sls_dir = os.path.dirname(sls.replace('.', os.path.sep)) if '.' in sls else sls
ctx = dict(sls_dir=sls_dir if sls_dir else '.')
if context:
ctx.update(context)
tmplout = render_template(
StringIO(data), saltenv, sls, context=ctx,
argline=rt_argline.strip(), **kws
)
high = render_data(tmplout, saltenv, sls, argline=rd_argline.strip())
return process_high_data(high, extract)
def process_high_data(high, extract):
# make a copy so that the original, un-preprocessed highstate data
# structure can be used later for error checking if anything goes
# wrong during the preprocessing.
data = copy.deepcopy(high)
try:
rewrite_single_shorthand_state_decl(data)
rewrite_sls_includes_excludes(data, sls, saltenv)
if not extract and implicit_require:
sid = has_names_decls(data)
if sid:
raise SaltRenderError(
'\'names\' declaration(found in state id: {0}) is '
'not supported with implicitly ordered states! You '
'should generate the states in a template for-loop '
'instead.'.format(sid)
)
add_implicit_requires(data)
if gen_start_state:
add_start_state(data, sls)
if not extract and not no_goal_state:
add_goal_state(data)
rename_state_ids(data, sls)
# We must extract no matter what so extending a stateconf sls file
# works!
extract_state_confs(data)
except SaltRenderError:
raise
except Exception as err:
log.exception(
'Error found while pre-processing the salt file %s:\n%s',
sls, err
)
from salt.state import State
state = State(__opts__)
errors = state.verify_high(high)
if errors:
raise SaltRenderError('\n'.join(errors))
raise SaltRenderError('sls preprocessing/rendering failed!')
return data
# ----------------------
renderers = kws['renderers']
opts, args = getopt.getopt(argline.split(), 'Gosp')
argline = ' '.join(args) if args else 'yaml . jinja'
if ('-G', '') in opts:
no_goal_state = True
if ('-o', '') in opts:
implicit_require = True
if ('-s', '') in opts:
gen_start_state = True
if ('-p', '') in opts:
data = process_high_data(input, extract=False)
else:
# Split on the first dot surrounded by spaces but not preceded by a
# backslash. A backslash preceded dot will be replaced with just dot.
args = [
arg.strip().replace('\\.', '.')
for arg in re.split(r'\s+(?<!\\)\.\s+', argline, 1)
]
try:
name, rd_argline = (args[0] + ' ').split(' ', 1)
render_data = renderers[name] # e.g., the yaml renderer
if implicit_require:
if name == 'yaml':
rd_argline = '-o ' + rd_argline
else:
raise SaltRenderError(
'Implicit ordering is only supported if the yaml renderer '
'is used!'
)
name, rt_argline = (args[1] + ' ').split(' ', 1)
render_template = renderers[name] # e.g., the mako renderer
except KeyError as err:
raise SaltRenderError('Renderer: {0} is not available!'.format(err))
except IndexError:
raise INVALID_USAGE_ERROR
if isinstance(input, six.string_types):
with salt.utils.files.fopen(input, 'r') as ifile:
sls_templ = salt.utils.stringutils.to_unicode(ifile.read())
else: # assume file-like
sls_templ = salt.utils.stringutils.to_unicode(input.read())
# first pass to extract the state configuration
match = re.search(__opts__['stateconf_end_marker'], sls_templ)
if match:
process_sls_data(sls_templ[:match.start()], extract=True)
# if some config has been extracted then remove the sls-name prefix
# of the keys in the extracted stateconf.set context to make them easier
# to use in the salt file.
if STATE_CONF:
tmplctx = STATE_CONF.copy()
if tmplctx:
prefix = sls + '::'
for k in six.iterkeys(tmplctx): # iterate over a copy of keys
if k.startswith(prefix):
tmplctx[k[len(prefix):]] = tmplctx[k]
del tmplctx[k]
else:
tmplctx = {}
# do a second pass that provides the extracted conf as template context
data = process_sls_data(sls_templ, tmplctx)
if log.isEnabledFor(logging.DEBUG):
import pprint # FIXME: pprint OrderedDict
log.debug('Rendered sls: %s', pprint.pformat(data))
return data
def has_names_decls(data):
for sid, _, _, args in statelist(data):
if sid == 'extend':
continue
for _ in nvlist(args, ['names']):
return sid
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 rewrite_sls_includes_excludes(data, sls, saltenv):
# if the path of the included/excluded sls starts with a leading dot(.)
# then it's taken to be relative to the including/excluding sls.
for sid in data:
if sid == 'include':
includes = data[sid]
for i, each in enumerate(includes):
if isinstance(each, dict):
slsenv, incl = each.popitem()
else:
slsenv = saltenv
incl = each
if incl.startswith('.'):
includes[i] = {slsenv: _relative_to_abs_sls(incl, sls)}
elif sid == 'exclude':
for sdata in data[sid]:
if 'sls' in sdata and sdata['sls'].startswith('.'):
sdata['sls'] = _relative_to_abs_sls(sdata['sls'], sls)
def _local_to_abs_sid(sid, sls): # id must starts with '.'
if '::' in sid:
return _relative_to_abs_sls(sid, sls)
else:
abs_sls = _relative_to_abs_sls(sid, sls + '.')
return '::'.join(abs_sls.rsplit('.', 1))
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 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 statelist(states_dict, sid_excludes=frozenset(['include', 'exclude'])):
for sid, states in six.iteritems(states_dict):
if sid.startswith('__'):
continue
if sid in sid_excludes:
continue
for sname, args in six.iteritems(states):
if sname.startswith('__'):
continue
yield sid, states, sname, args
REQUISITES = ('require', 'require_in', 'watch', 'watch_in', 'use', 'use_in', 'listen', 'listen_in', 'onchanges',
'onchanges_in', 'onfail', 'onfail_in')
def rename_state_ids(data, sls, is_extend=False):
# if the .sls file is salt://my/salt/file.sls
# then rename all state ids defined in it that start with a dot(.) with
# "my.salt.file::" + the_state_id_without_the_first_dot.
# update "local" references to the renamed states.
if 'extend' in data and not is_extend:
rename_state_ids(data['extend'], sls, True)
for sid, _, _, args in statelist(data):
for req, sname, sid in nvlist2(args, REQUISITES):
if sid.startswith('.'):
req[sname] = _local_to_abs_sid(sid, sls)
for sid in list(data):
if sid.startswith('.'):
newsid = _local_to_abs_sid(sid, sls)
if newsid in data:
raise SaltRenderError(
'Can\'t rename state id({0}) into {1} because the later '
'already exists!'.format(sid, newsid)
)
# add a '- name: sid' to those states without '- name'.
for sname, args in six.iteritems(data[sid]):
if state_name(sname) == STATE_NAME:
continue
for arg in args:
if isinstance(arg, dict) and next(iter(arg)) == 'name':
break
else:
# then no '- name: ...' is defined in the state args
# add the sid without the leading dot as the name.
args.insert(0, dict(name=sid[1:]))
data[newsid] = data[sid]
del data[sid]
REQUIRE = ('require', 'watch', 'listen', 'onchanges', 'onfail')
REQUIRE_IN = ('require_in', 'watch_in', 'listen_in', 'onchanges_in', 'onfail_in')
EXTENDED_REQUIRE = {}
EXTENDED_REQUIRE_IN = {}
from itertools import chain
# To avoid cycles among states when each state requires the one before it:
# explicit require/watch/listen/onchanges/onfail can only contain states before it
# explicit require_in/watch_in/listen_in/onchanges_in/onfail_in can only contain states after it
def add_implicit_requires(data):
def T(sid, state): # pylint: disable=C0103
return '{0}:{1}'.format(sid, state_name(state))
states_before = set()
states_after = set()
for sid in data:
for state in data[sid]:
states_after.add(T(sid, state))
prev_state = (None, None) # (state_name, sid)
for sid, states, sname, args in statelist(data):
if sid == 'extend':
for esid, _, _, eargs in statelist(states):
for _, rstate, rsid in nvlist2(eargs, REQUIRE):
EXTENDED_REQUIRE.setdefault(
T(esid, rstate), []).append((None, rstate, rsid))
for _, rstate, rsid in nvlist2(eargs, REQUIRE_IN):
EXTENDED_REQUIRE_IN.setdefault(
T(esid, rstate), []).append((None, rstate, rsid))
continue
tag = T(sid, sname)
states_after.remove(tag)
reqs = nvlist2(args, REQUIRE)
if tag in EXTENDED_REQUIRE:
reqs = chain(reqs, EXTENDED_REQUIRE[tag])
for _, rstate, rsid in reqs:
if T(rsid, rstate) in states_after:
raise SaltRenderError(
'State({0}) can\'t require/watch/listen/onchanges/onfail a state({1}) defined '
'after it!'.format(tag, T(rsid, rstate))
)
reqs = nvlist2(args, REQUIRE_IN)
if tag in EXTENDED_REQUIRE_IN:
reqs = chain(reqs, EXTENDED_REQUIRE_IN[tag])
for _, rstate, rsid in reqs:
if T(rsid, rstate) in states_before:
raise SaltRenderError(
'State({0}) can\'t require_in/watch_in/listen_in/onchanges_in/onfail_in a state({1}) '
'defined before it!'.format(tag, T(rsid, rstate))
)
# add a (- state: sid) item, at the beginning of the require of this
# state if there's a state before this one.
if prev_state[0] is not None:
try:
next(nvlist(args, ['require']))[2].insert(0, dict([prev_state]))
except StopIteration: # i.e., there's no require
args.append(dict(require=[dict([prev_state])]))
states_before.add(tag)
prev_state = (state_name(sname), sid)
def add_start_state(data, sls):
start_sid = __opts__['stateconf_start_state']
if start_sid in data:
raise SaltRenderError(
'Can\'t generate start state({0})! The same state id already '
'exists!'.format(start_sid)
)
if not data:
return
# the start state is either the first state whose id declaration has
# no __sls__, or it's the first state whose id declaration has a
# __sls__ == sls.
non_sids = ('include', 'exclude', 'extend')
for sid, states in six.iteritems(data):
if sid in non_sids or sid.startswith('__'):
continue
if '__sls__' not in states or states['__sls__'] == sls:
break
else:
raise SaltRenderError('Can\'t determine the first state in the sls file!')
reqin = {state_name(next(six.iterkeys(data[sid]))): sid}
data[start_sid] = {STATE_FUNC: [{'require_in': [reqin]}]}
def add_goal_state(data):
goal_sid = __opts__['stateconf_goal_state']
if goal_sid in data:
raise SaltRenderError(
'Can\'t generate goal state({0})! The same state id already '
'exists!'.format(goal_sid)
)
else:
reqlist = []
for sid, states, state, _ in \
statelist(data, ('include', 'exclude', 'extend')):
if '__sls__' in states:
# Then id declaration must have been included from a
# rendered sls. Currently, this is only possible with
# pydsl's high state output.
continue
reqlist.append({state_name(state): sid})
data[goal_sid] = {STATE_FUNC: [dict(require=reqlist)]}
def state_name(sname):
'''
Return the name of the state regardless if sname is
just the state name or a state.func name.
'''
return sname.split('.', 1)[0]
# Quick and dirty way to get attribute access for dictionary keys.
# So, we can do: ${apache.port} instead of ${apache['port']} when possible.
class Bunch(dict):
def __getattr__(self, name):
return self[name]
# With sls:
#
# state_id:
# stateconf.set:
# - name1: value1
#
# STATE_CONF is:
# { state_id => {name1: value1} }
#
STATE_CONF = {} # stateconf.set
STATE_CONF_EXT = {} # stateconf.set under extend: ...
def extract_state_confs(data, is_extend=False):
for state_id, state_dict in six.iteritems(data):
if state_id == 'extend' and not is_extend:
extract_state_confs(state_dict, True)
continue
if STATE_NAME in state_dict:
key = STATE_NAME
elif STATE_FUNC in state_dict:
key = STATE_FUNC
else:
continue
to_dict = STATE_CONF_EXT if is_extend else STATE_CONF
conf = to_dict.setdefault(state_id, Bunch())
for sdk in state_dict[key]:
if not isinstance(sdk, dict):
continue
key, val = next(six.iteritems(sdk))
conf[key] = val
if not is_extend and state_id in STATE_CONF_EXT:
extend = STATE_CONF_EXT[state_id]
for requisite in 'require', 'watch', 'listen', 'onchanges', 'onfail':
if requisite in extend:
extend[requisite] += to_dict[state_id].get(requisite, [])
to_dict[state_id].update(STATE_CONF_EXT[state_id])
|
saltstack/salt
|
salt/renderers/stateconf.py
|
nvlist2
|
python
|
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
|
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'}.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/stateconf.py#L334-L351
|
[
"def nvlist(thelist, names=None):\n '''\n Given a list of items::\n\n - whatever\n - name1: value1\n - name2:\n - key: value\n - key: value\n\n return a generator that yields each (item, key, value) tuple, skipping\n items that are not name-value's(dictionaries) or those not in the\n list of matching names. The item in the returned tuple is the single-key\n dictionary.\n '''\n # iterate over the list under the state dict.\n for nvitem in thelist:\n if isinstance(nvitem, dict):\n # then nvitem is a name-value item(a dict) of the list.\n name, value = next(six.iteritems(nvitem))\n if names is None or name in names:\n yield nvitem, name, value\n"
] |
# -*- coding: utf-8 -*-
'''
A flexible renderer that takes a templating engine and a data format
:maintainer: Jack Kuan <kjkuan@gmail.com>
:maturity: new
:platform: all
'''
# See http://docs.saltstack.org/en/latest/ref/renderers/all/salt.renderers.stateconf.html
# for a guide to using this module.
#
# FIXME: I really need to review and simplify this renderer, it's getting out of hand!
#
# TODO:
# - sls meta/info state: E.g.,
#
# sls_info:
# stateconf.set:
# - author: Jack Kuan
# - description: what the salt file does...
# - version: 0.1.0
#
# - version constraint for 'include'. E.g.,
#
# include:
# - apache: >= 0.1.0
#
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
import getopt
import copy
# Import salt libs
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import SaltRenderError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error
__all__ = ['render']
log = logging.getLogger(__name__)
__opts__ = {
'stateconf_end_marker': r'#\s*-+\s*end of state config\s*-+',
# e.g., something like "# --- end of state config --" works by default.
'stateconf_start_state': '.start',
# name of the state id for the generated start state.
'stateconf_goal_state': '.goal',
# name of the state id for the generated goal state.
'stateconf_state_func': 'stateconf.set'
# names the state and the state function to be recognized as a special
# state from which to gather sls file context variables. It should be
# specified in the 'state.func' notation, and both the state module and
# the function must actually exist and the function should be a dummy,
# no-op state function that simply returns a
# dict(name=name, result=True, changes={}, comment='')
}
STATE_FUNC = STATE_NAME = ''
def __init__(opts):
global STATE_NAME, STATE_FUNC
STATE_FUNC = __opts__['stateconf_state_func']
STATE_NAME = STATE_FUNC.split('.')[0]
MOD_BASENAME = os.path.basename(__file__)
INVALID_USAGE_ERROR = SaltRenderError(
'Invalid use of {0} renderer!\n'
'''Usage: #!{0} [-GoSp] [<data_renderer> [options] . <template_renderer> [options]]
where an example <data_renderer> would be yaml and a <template_renderer> might
be jinja. Each renderer can be passed its renderer specific options.
Options(for this renderer):
-G Do not generate the goal state that requires all other states in the sls.
-o Indirectly order the states by adding requires such that they will be
executed in the order they are defined in the sls. Implies using yaml -o.
-s Generate the start state that gets inserted as the first state in
the sls. This only makes sense if your high state data dict is ordered.
-p Assume high state input. This option allows you to pipe high state data
through this renderer. With this option, the use of stateconf.set state
in the sls will have no effect, but other features of the renderer still
apply.
'''.format(MOD_BASENAME)
)
def render(input, saltenv='base', sls='', argline='', **kws):
gen_start_state = False
no_goal_state = False
implicit_require = False
def process_sls_data(data, context=None, extract=False):
sls_dir = os.path.dirname(sls.replace('.', os.path.sep)) if '.' in sls else sls
ctx = dict(sls_dir=sls_dir if sls_dir else '.')
if context:
ctx.update(context)
tmplout = render_template(
StringIO(data), saltenv, sls, context=ctx,
argline=rt_argline.strip(), **kws
)
high = render_data(tmplout, saltenv, sls, argline=rd_argline.strip())
return process_high_data(high, extract)
def process_high_data(high, extract):
# make a copy so that the original, un-preprocessed highstate data
# structure can be used later for error checking if anything goes
# wrong during the preprocessing.
data = copy.deepcopy(high)
try:
rewrite_single_shorthand_state_decl(data)
rewrite_sls_includes_excludes(data, sls, saltenv)
if not extract and implicit_require:
sid = has_names_decls(data)
if sid:
raise SaltRenderError(
'\'names\' declaration(found in state id: {0}) is '
'not supported with implicitly ordered states! You '
'should generate the states in a template for-loop '
'instead.'.format(sid)
)
add_implicit_requires(data)
if gen_start_state:
add_start_state(data, sls)
if not extract and not no_goal_state:
add_goal_state(data)
rename_state_ids(data, sls)
# We must extract no matter what so extending a stateconf sls file
# works!
extract_state_confs(data)
except SaltRenderError:
raise
except Exception as err:
log.exception(
'Error found while pre-processing the salt file %s:\n%s',
sls, err
)
from salt.state import State
state = State(__opts__)
errors = state.verify_high(high)
if errors:
raise SaltRenderError('\n'.join(errors))
raise SaltRenderError('sls preprocessing/rendering failed!')
return data
# ----------------------
renderers = kws['renderers']
opts, args = getopt.getopt(argline.split(), 'Gosp')
argline = ' '.join(args) if args else 'yaml . jinja'
if ('-G', '') in opts:
no_goal_state = True
if ('-o', '') in opts:
implicit_require = True
if ('-s', '') in opts:
gen_start_state = True
if ('-p', '') in opts:
data = process_high_data(input, extract=False)
else:
# Split on the first dot surrounded by spaces but not preceded by a
# backslash. A backslash preceded dot will be replaced with just dot.
args = [
arg.strip().replace('\\.', '.')
for arg in re.split(r'\s+(?<!\\)\.\s+', argline, 1)
]
try:
name, rd_argline = (args[0] + ' ').split(' ', 1)
render_data = renderers[name] # e.g., the yaml renderer
if implicit_require:
if name == 'yaml':
rd_argline = '-o ' + rd_argline
else:
raise SaltRenderError(
'Implicit ordering is only supported if the yaml renderer '
'is used!'
)
name, rt_argline = (args[1] + ' ').split(' ', 1)
render_template = renderers[name] # e.g., the mako renderer
except KeyError as err:
raise SaltRenderError('Renderer: {0} is not available!'.format(err))
except IndexError:
raise INVALID_USAGE_ERROR
if isinstance(input, six.string_types):
with salt.utils.files.fopen(input, 'r') as ifile:
sls_templ = salt.utils.stringutils.to_unicode(ifile.read())
else: # assume file-like
sls_templ = salt.utils.stringutils.to_unicode(input.read())
# first pass to extract the state configuration
match = re.search(__opts__['stateconf_end_marker'], sls_templ)
if match:
process_sls_data(sls_templ[:match.start()], extract=True)
# if some config has been extracted then remove the sls-name prefix
# of the keys in the extracted stateconf.set context to make them easier
# to use in the salt file.
if STATE_CONF:
tmplctx = STATE_CONF.copy()
if tmplctx:
prefix = sls + '::'
for k in six.iterkeys(tmplctx): # iterate over a copy of keys
if k.startswith(prefix):
tmplctx[k[len(prefix):]] = tmplctx[k]
del tmplctx[k]
else:
tmplctx = {}
# do a second pass that provides the extracted conf as template context
data = process_sls_data(sls_templ, tmplctx)
if log.isEnabledFor(logging.DEBUG):
import pprint # FIXME: pprint OrderedDict
log.debug('Rendered sls: %s', pprint.pformat(data))
return data
def has_names_decls(data):
for sid, _, _, args in statelist(data):
if sid == 'extend':
continue
for _ in nvlist(args, ['names']):
return sid
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 rewrite_sls_includes_excludes(data, sls, saltenv):
# if the path of the included/excluded sls starts with a leading dot(.)
# then it's taken to be relative to the including/excluding sls.
for sid in data:
if sid == 'include':
includes = data[sid]
for i, each in enumerate(includes):
if isinstance(each, dict):
slsenv, incl = each.popitem()
else:
slsenv = saltenv
incl = each
if incl.startswith('.'):
includes[i] = {slsenv: _relative_to_abs_sls(incl, sls)}
elif sid == 'exclude':
for sdata in data[sid]:
if 'sls' in sdata and sdata['sls'].startswith('.'):
sdata['sls'] = _relative_to_abs_sls(sdata['sls'], sls)
def _local_to_abs_sid(sid, sls): # id must starts with '.'
if '::' in sid:
return _relative_to_abs_sls(sid, sls)
else:
abs_sls = _relative_to_abs_sls(sid, sls + '.')
return '::'.join(abs_sls.rsplit('.', 1))
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 statelist(states_dict, sid_excludes=frozenset(['include', 'exclude'])):
for sid, states in six.iteritems(states_dict):
if sid.startswith('__'):
continue
if sid in sid_excludes:
continue
for sname, args in six.iteritems(states):
if sname.startswith('__'):
continue
yield sid, states, sname, args
REQUISITES = ('require', 'require_in', 'watch', 'watch_in', 'use', 'use_in', 'listen', 'listen_in', 'onchanges',
'onchanges_in', 'onfail', 'onfail_in')
def rename_state_ids(data, sls, is_extend=False):
# if the .sls file is salt://my/salt/file.sls
# then rename all state ids defined in it that start with a dot(.) with
# "my.salt.file::" + the_state_id_without_the_first_dot.
# update "local" references to the renamed states.
if 'extend' in data and not is_extend:
rename_state_ids(data['extend'], sls, True)
for sid, _, _, args in statelist(data):
for req, sname, sid in nvlist2(args, REQUISITES):
if sid.startswith('.'):
req[sname] = _local_to_abs_sid(sid, sls)
for sid in list(data):
if sid.startswith('.'):
newsid = _local_to_abs_sid(sid, sls)
if newsid in data:
raise SaltRenderError(
'Can\'t rename state id({0}) into {1} because the later '
'already exists!'.format(sid, newsid)
)
# add a '- name: sid' to those states without '- name'.
for sname, args in six.iteritems(data[sid]):
if state_name(sname) == STATE_NAME:
continue
for arg in args:
if isinstance(arg, dict) and next(iter(arg)) == 'name':
break
else:
# then no '- name: ...' is defined in the state args
# add the sid without the leading dot as the name.
args.insert(0, dict(name=sid[1:]))
data[newsid] = data[sid]
del data[sid]
REQUIRE = ('require', 'watch', 'listen', 'onchanges', 'onfail')
REQUIRE_IN = ('require_in', 'watch_in', 'listen_in', 'onchanges_in', 'onfail_in')
EXTENDED_REQUIRE = {}
EXTENDED_REQUIRE_IN = {}
from itertools import chain
# To avoid cycles among states when each state requires the one before it:
# explicit require/watch/listen/onchanges/onfail can only contain states before it
# explicit require_in/watch_in/listen_in/onchanges_in/onfail_in can only contain states after it
def add_implicit_requires(data):
def T(sid, state): # pylint: disable=C0103
return '{0}:{1}'.format(sid, state_name(state))
states_before = set()
states_after = set()
for sid in data:
for state in data[sid]:
states_after.add(T(sid, state))
prev_state = (None, None) # (state_name, sid)
for sid, states, sname, args in statelist(data):
if sid == 'extend':
for esid, _, _, eargs in statelist(states):
for _, rstate, rsid in nvlist2(eargs, REQUIRE):
EXTENDED_REQUIRE.setdefault(
T(esid, rstate), []).append((None, rstate, rsid))
for _, rstate, rsid in nvlist2(eargs, REQUIRE_IN):
EXTENDED_REQUIRE_IN.setdefault(
T(esid, rstate), []).append((None, rstate, rsid))
continue
tag = T(sid, sname)
states_after.remove(tag)
reqs = nvlist2(args, REQUIRE)
if tag in EXTENDED_REQUIRE:
reqs = chain(reqs, EXTENDED_REQUIRE[tag])
for _, rstate, rsid in reqs:
if T(rsid, rstate) in states_after:
raise SaltRenderError(
'State({0}) can\'t require/watch/listen/onchanges/onfail a state({1}) defined '
'after it!'.format(tag, T(rsid, rstate))
)
reqs = nvlist2(args, REQUIRE_IN)
if tag in EXTENDED_REQUIRE_IN:
reqs = chain(reqs, EXTENDED_REQUIRE_IN[tag])
for _, rstate, rsid in reqs:
if T(rsid, rstate) in states_before:
raise SaltRenderError(
'State({0}) can\'t require_in/watch_in/listen_in/onchanges_in/onfail_in a state({1}) '
'defined before it!'.format(tag, T(rsid, rstate))
)
# add a (- state: sid) item, at the beginning of the require of this
# state if there's a state before this one.
if prev_state[0] is not None:
try:
next(nvlist(args, ['require']))[2].insert(0, dict([prev_state]))
except StopIteration: # i.e., there's no require
args.append(dict(require=[dict([prev_state])]))
states_before.add(tag)
prev_state = (state_name(sname), sid)
def add_start_state(data, sls):
start_sid = __opts__['stateconf_start_state']
if start_sid in data:
raise SaltRenderError(
'Can\'t generate start state({0})! The same state id already '
'exists!'.format(start_sid)
)
if not data:
return
# the start state is either the first state whose id declaration has
# no __sls__, or it's the first state whose id declaration has a
# __sls__ == sls.
non_sids = ('include', 'exclude', 'extend')
for sid, states in six.iteritems(data):
if sid in non_sids or sid.startswith('__'):
continue
if '__sls__' not in states or states['__sls__'] == sls:
break
else:
raise SaltRenderError('Can\'t determine the first state in the sls file!')
reqin = {state_name(next(six.iterkeys(data[sid]))): sid}
data[start_sid] = {STATE_FUNC: [{'require_in': [reqin]}]}
def add_goal_state(data):
goal_sid = __opts__['stateconf_goal_state']
if goal_sid in data:
raise SaltRenderError(
'Can\'t generate goal state({0})! The same state id already '
'exists!'.format(goal_sid)
)
else:
reqlist = []
for sid, states, state, _ in \
statelist(data, ('include', 'exclude', 'extend')):
if '__sls__' in states:
# Then id declaration must have been included from a
# rendered sls. Currently, this is only possible with
# pydsl's high state output.
continue
reqlist.append({state_name(state): sid})
data[goal_sid] = {STATE_FUNC: [dict(require=reqlist)]}
def state_name(sname):
'''
Return the name of the state regardless if sname is
just the state name or a state.func name.
'''
return sname.split('.', 1)[0]
# Quick and dirty way to get attribute access for dictionary keys.
# So, we can do: ${apache.port} instead of ${apache['port']} when possible.
class Bunch(dict):
def __getattr__(self, name):
return self[name]
# With sls:
#
# state_id:
# stateconf.set:
# - name1: value1
#
# STATE_CONF is:
# { state_id => {name1: value1} }
#
STATE_CONF = {} # stateconf.set
STATE_CONF_EXT = {} # stateconf.set under extend: ...
def extract_state_confs(data, is_extend=False):
for state_id, state_dict in six.iteritems(data):
if state_id == 'extend' and not is_extend:
extract_state_confs(state_dict, True)
continue
if STATE_NAME in state_dict:
key = STATE_NAME
elif STATE_FUNC in state_dict:
key = STATE_FUNC
else:
continue
to_dict = STATE_CONF_EXT if is_extend else STATE_CONF
conf = to_dict.setdefault(state_id, Bunch())
for sdk in state_dict[key]:
if not isinstance(sdk, dict):
continue
key, val = next(six.iteritems(sdk))
conf[key] = val
if not is_extend and state_id in STATE_CONF_EXT:
extend = STATE_CONF_EXT[state_id]
for requisite in 'require', 'watch', 'listen', 'onchanges', 'onfail':
if requisite in extend:
extend[requisite] += to_dict[state_id].get(requisite, [])
to_dict[state_id].update(STATE_CONF_EXT[state_id])
|
saltstack/salt
|
salt/modules/statuspage.py
|
_get_api_params
|
python
|
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
}
|
Retrieve the API params from the config file.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/statuspage.py#L86-L101
| null |
# -*- coding: utf-8 -*-
'''
StatusPage
==========
Handle requests for the StatusPage_ API_.
.. _StatusPage: https://www.statuspage.io/
.. _API: http://doers.statuspage.io/api/v1/
In the minion configuration file, the following block is required:
.. code-block:: yaml
statuspage:
api_key: <API_KEY>
page_id: <PAGE_ID>
.. versionadded:: 2017.7.0
'''
from __future__ import absolute_import, unicode_literals, print_function
# import python std lib
import logging
# import third party
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# import salt
from salt.ext import six
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'statuspage'
log = logging.getLogger(__file__)
BASE_URL = 'https://api.statuspage.io'
DEFAULT_VERSION = 1
UPDATE_FORBIDDEN_FILEDS = [
'id', # can't rewrite this
'created_at',
'updated_at', # updated_at and created_at are handled by the backend framework of the API
'page_id' # can't move it to a different page
]
INSERT_FORBIDDEN_FILEDS = UPDATE_FORBIDDEN_FILEDS[:] # they are the same for the moment
METHOD_OK_STATUS = {
'POST': 201,
'DELETE': 204
}
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
Return the execution module virtualname.
'''
if HAS_REQUESTS is False:
return False, 'The requests python package is not installed'
return __virtualname__
def _default_ret():
'''
Default dictionary returned.
'''
return {
'result': False,
'comment': '',
'out': None
}
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 _get_headers(params):
'''
Return HTTP headers required.
'''
return {
'Authorization': 'OAuth {oauth}'.format(oauth=params['api_key'])
}
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
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
def create(endpoint='incidents',
api_url=None,
page_id=None,
api_key=None,
api_version=None,
**kwargs):
'''
Insert a new entry under a specific endpoint.
endpoint: incidents
Insert under this 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.create endpoint='components' name='my component' group_id='993vgplshj12'
Example output:
.. code-block:: bash
minion:
----------
comment:
out:
----------
created_at:
2017-01-05T19:35:27.135Z
description:
None
group_id:
993vgplshj12
id:
mjkmtt5lhdgc
name:
my component
page_id:
ksdhgfyiuhaa
position:
7
status:
operational
updated_at:
2017-01-05T19:35:27.135Z
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
headers = _get_headers(params)
create_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
)
change_request = {}
for karg, warg in six.iteritems(kwargs):
if warg is None or karg.startswith('__') or karg in INSERT_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(create_url,
method='POST',
headers=headers,
data=change_request)
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)
|
saltstack/salt
|
salt/modules/statuspage.py
|
_validate_api_params
|
python
|
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)))
|
Validate the API params as specified in the config file.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/statuspage.py#L104-L110
| null |
# -*- coding: utf-8 -*-
'''
StatusPage
==========
Handle requests for the StatusPage_ API_.
.. _StatusPage: https://www.statuspage.io/
.. _API: http://doers.statuspage.io/api/v1/
In the minion configuration file, the following block is required:
.. code-block:: yaml
statuspage:
api_key: <API_KEY>
page_id: <PAGE_ID>
.. versionadded:: 2017.7.0
'''
from __future__ import absolute_import, unicode_literals, print_function
# import python std lib
import logging
# import third party
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# import salt
from salt.ext import six
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'statuspage'
log = logging.getLogger(__file__)
BASE_URL = 'https://api.statuspage.io'
DEFAULT_VERSION = 1
UPDATE_FORBIDDEN_FILEDS = [
'id', # can't rewrite this
'created_at',
'updated_at', # updated_at and created_at are handled by the backend framework of the API
'page_id' # can't move it to a different page
]
INSERT_FORBIDDEN_FILEDS = UPDATE_FORBIDDEN_FILEDS[:] # they are the same for the moment
METHOD_OK_STATUS = {
'POST': 201,
'DELETE': 204
}
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
Return the execution module virtualname.
'''
if HAS_REQUESTS is False:
return False, 'The requests python package is not installed'
return __virtualname__
def _default_ret():
'''
Default dictionary returned.
'''
return {
'result': False,
'comment': '',
'out': None
}
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 _get_headers(params):
'''
Return HTTP headers required.
'''
return {
'Authorization': 'OAuth {oauth}'.format(oauth=params['api_key'])
}
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
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
def create(endpoint='incidents',
api_url=None,
page_id=None,
api_key=None,
api_version=None,
**kwargs):
'''
Insert a new entry under a specific endpoint.
endpoint: incidents
Insert under this 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.create endpoint='components' name='my component' group_id='993vgplshj12'
Example output:
.. code-block:: bash
minion:
----------
comment:
out:
----------
created_at:
2017-01-05T19:35:27.135Z
description:
None
group_id:
993vgplshj12
id:
mjkmtt5lhdgc
name:
my component
page_id:
ksdhgfyiuhaa
position:
7
status:
operational
updated_at:
2017-01-05T19:35:27.135Z
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
headers = _get_headers(params)
create_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
)
change_request = {}
for karg, warg in six.iteritems(kwargs):
if warg is None or karg.startswith('__') or karg in INSERT_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(create_url,
method='POST',
headers=headers,
data=change_request)
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)
|
saltstack/salt
|
salt/modules/statuspage.py
|
_http_request
|
python
|
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
|
Make the HTTP request and return the body as python object.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/statuspage.py#L122-L144
| null |
# -*- coding: utf-8 -*-
'''
StatusPage
==========
Handle requests for the StatusPage_ API_.
.. _StatusPage: https://www.statuspage.io/
.. _API: http://doers.statuspage.io/api/v1/
In the minion configuration file, the following block is required:
.. code-block:: yaml
statuspage:
api_key: <API_KEY>
page_id: <PAGE_ID>
.. versionadded:: 2017.7.0
'''
from __future__ import absolute_import, unicode_literals, print_function
# import python std lib
import logging
# import third party
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# import salt
from salt.ext import six
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'statuspage'
log = logging.getLogger(__file__)
BASE_URL = 'https://api.statuspage.io'
DEFAULT_VERSION = 1
UPDATE_FORBIDDEN_FILEDS = [
'id', # can't rewrite this
'created_at',
'updated_at', # updated_at and created_at are handled by the backend framework of the API
'page_id' # can't move it to a different page
]
INSERT_FORBIDDEN_FILEDS = UPDATE_FORBIDDEN_FILEDS[:] # they are the same for the moment
METHOD_OK_STATUS = {
'POST': 201,
'DELETE': 204
}
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
Return the execution module virtualname.
'''
if HAS_REQUESTS is False:
return False, 'The requests python package is not installed'
return __virtualname__
def _default_ret():
'''
Default dictionary returned.
'''
return {
'result': False,
'comment': '',
'out': None
}
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 _get_headers(params):
'''
Return HTTP headers required.
'''
return {
'Authorization': 'OAuth {oauth}'.format(oauth=params['api_key'])
}
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
def create(endpoint='incidents',
api_url=None,
page_id=None,
api_key=None,
api_version=None,
**kwargs):
'''
Insert a new entry under a specific endpoint.
endpoint: incidents
Insert under this 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.create endpoint='components' name='my component' group_id='993vgplshj12'
Example output:
.. code-block:: bash
minion:
----------
comment:
out:
----------
created_at:
2017-01-05T19:35:27.135Z
description:
None
group_id:
993vgplshj12
id:
mjkmtt5lhdgc
name:
my component
page_id:
ksdhgfyiuhaa
position:
7
status:
operational
updated_at:
2017-01-05T19:35:27.135Z
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
headers = _get_headers(params)
create_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
)
change_request = {}
for karg, warg in six.iteritems(kwargs):
if warg is None or karg.startswith('__') or karg in INSERT_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(create_url,
method='POST',
headers=headers,
data=change_request)
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)
|
saltstack/salt
|
salt/modules/statuspage.py
|
retrieve
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/statuspage.py#L246-L378
|
[
"def _get_api_params(api_url=None,\n page_id=None,\n api_key=None,\n api_version=None):\n '''\n Retrieve the API params from the config file.\n '''\n statuspage_cfg = __salt__['config.get']('statuspage')\n if not statuspage_cfg:\n statuspage_cfg = {}\n return {\n 'api_url': api_url or statuspage_cfg.get('api_url') or BASE_URL, # optional\n 'api_page_id': page_id or statuspage_cfg.get('page_id'), # mandatory\n 'api_key': api_key or statuspage_cfg.get('api_key'), # mandatory\n 'api_version': api_version or statuspage_cfg.get('api_version') or DEFAULT_VERSION\n }\n",
"def _validate_api_params(params):\n '''\n Validate the API params as specified in the config file.\n '''\n # page_id and API key are mandatory and they must be string/unicode\n return (isinstance(params['api_page_id'], (six.string_types, six.text_type)) and\n isinstance(params['api_key'], (six.string_types, six.text_type)))\n"
] |
# -*- coding: utf-8 -*-
'''
StatusPage
==========
Handle requests for the StatusPage_ API_.
.. _StatusPage: https://www.statuspage.io/
.. _API: http://doers.statuspage.io/api/v1/
In the minion configuration file, the following block is required:
.. code-block:: yaml
statuspage:
api_key: <API_KEY>
page_id: <PAGE_ID>
.. versionadded:: 2017.7.0
'''
from __future__ import absolute_import, unicode_literals, print_function
# import python std lib
import logging
# import third party
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# import salt
from salt.ext import six
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'statuspage'
log = logging.getLogger(__file__)
BASE_URL = 'https://api.statuspage.io'
DEFAULT_VERSION = 1
UPDATE_FORBIDDEN_FILEDS = [
'id', # can't rewrite this
'created_at',
'updated_at', # updated_at and created_at are handled by the backend framework of the API
'page_id' # can't move it to a different page
]
INSERT_FORBIDDEN_FILEDS = UPDATE_FORBIDDEN_FILEDS[:] # they are the same for the moment
METHOD_OK_STATUS = {
'POST': 201,
'DELETE': 204
}
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
Return the execution module virtualname.
'''
if HAS_REQUESTS is False:
return False, 'The requests python package is not installed'
return __virtualname__
def _default_ret():
'''
Default dictionary returned.
'''
return {
'result': False,
'comment': '',
'out': None
}
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 _get_headers(params):
'''
Return HTTP headers required.
'''
return {
'Authorization': 'OAuth {oauth}'.format(oauth=params['api_key'])
}
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
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
def create(endpoint='incidents',
api_url=None,
page_id=None,
api_key=None,
api_version=None,
**kwargs):
'''
Insert a new entry under a specific endpoint.
endpoint: incidents
Insert under this 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.create endpoint='components' name='my component' group_id='993vgplshj12'
Example output:
.. code-block:: bash
minion:
----------
comment:
out:
----------
created_at:
2017-01-05T19:35:27.135Z
description:
None
group_id:
993vgplshj12
id:
mjkmtt5lhdgc
name:
my component
page_id:
ksdhgfyiuhaa
position:
7
status:
operational
updated_at:
2017-01-05T19:35:27.135Z
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
headers = _get_headers(params)
create_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
)
change_request = {}
for karg, warg in six.iteritems(kwargs):
if warg is None or karg.startswith('__') or karg in INSERT_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(create_url,
method='POST',
headers=headers,
data=change_request)
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)
|
saltstack/salt
|
salt/modules/statuspage.py
|
update
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/statuspage.py#L381-L483
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _get_headers(params):\n '''\n Return HTTP headers required.\n '''\n return {\n 'Authorization': 'OAuth {oauth}'.format(oauth=params['api_key'])\n }\n",
"def _get_api_params(api_url=None,\n page_id=None,\n api_key=None,\n api_version=None):\n '''\n Retrieve the API params from the config file.\n '''\n statuspage_cfg = __salt__['config.get']('statuspage')\n if not statuspage_cfg:\n statuspage_cfg = {}\n return {\n 'api_url': api_url or statuspage_cfg.get('api_url') or BASE_URL, # optional\n 'api_page_id': page_id or statuspage_cfg.get('page_id'), # mandatory\n 'api_key': api_key or statuspage_cfg.get('api_key'), # mandatory\n 'api_version': api_version or statuspage_cfg.get('api_version') or DEFAULT_VERSION\n }\n",
"def _http_request(url,\n method='GET',\n headers=None,\n data=None):\n '''\n Make the HTTP request and return the body as python object.\n '''\n req = requests.request(method,\n url,\n headers=headers,\n data=data)\n ret = _default_ret()\n ok_status = METHOD_OK_STATUS.get(method, 200)\n if req.status_code != ok_status:\n ret.update({\n 'comment': req.json().get('error', '')\n })\n return ret\n ret.update({\n 'result': True,\n 'out': req.json() if method != 'DELETE' else None # no body when DELETE\n })\n return ret\n",
"def _validate_api_params(params):\n '''\n Validate the API params as specified in the config file.\n '''\n # page_id and API key are mandatory and they must be string/unicode\n return (isinstance(params['api_page_id'], (six.string_types, six.text_type)) and\n isinstance(params['api_key'], (six.string_types, six.text_type)))\n"
] |
# -*- coding: utf-8 -*-
'''
StatusPage
==========
Handle requests for the StatusPage_ API_.
.. _StatusPage: https://www.statuspage.io/
.. _API: http://doers.statuspage.io/api/v1/
In the minion configuration file, the following block is required:
.. code-block:: yaml
statuspage:
api_key: <API_KEY>
page_id: <PAGE_ID>
.. versionadded:: 2017.7.0
'''
from __future__ import absolute_import, unicode_literals, print_function
# import python std lib
import logging
# import third party
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# import salt
from salt.ext import six
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'statuspage'
log = logging.getLogger(__file__)
BASE_URL = 'https://api.statuspage.io'
DEFAULT_VERSION = 1
UPDATE_FORBIDDEN_FILEDS = [
'id', # can't rewrite this
'created_at',
'updated_at', # updated_at and created_at are handled by the backend framework of the API
'page_id' # can't move it to a different page
]
INSERT_FORBIDDEN_FILEDS = UPDATE_FORBIDDEN_FILEDS[:] # they are the same for the moment
METHOD_OK_STATUS = {
'POST': 201,
'DELETE': 204
}
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
Return the execution module virtualname.
'''
if HAS_REQUESTS is False:
return False, 'The requests python package is not installed'
return __virtualname__
def _default_ret():
'''
Default dictionary returned.
'''
return {
'result': False,
'comment': '',
'out': None
}
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 _get_headers(params):
'''
Return HTTP headers required.
'''
return {
'Authorization': 'OAuth {oauth}'.format(oauth=params['api_key'])
}
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
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
def create(endpoint='incidents',
api_url=None,
page_id=None,
api_key=None,
api_version=None,
**kwargs):
'''
Insert a new entry under a specific endpoint.
endpoint: incidents
Insert under this 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.create endpoint='components' name='my component' group_id='993vgplshj12'
Example output:
.. code-block:: bash
minion:
----------
comment:
out:
----------
created_at:
2017-01-05T19:35:27.135Z
description:
None
group_id:
993vgplshj12
id:
mjkmtt5lhdgc
name:
my component
page_id:
ksdhgfyiuhaa
position:
7
status:
operational
updated_at:
2017-01-05T19:35:27.135Z
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
headers = _get_headers(params)
create_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
)
change_request = {}
for karg, warg in six.iteritems(kwargs):
if warg is None or karg.startswith('__') or karg in INSERT_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(create_url,
method='POST',
headers=headers,
data=change_request)
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 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)
|
saltstack/salt
|
salt/modules/statuspage.py
|
delete
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/statuspage.py#L486-L556
|
[
"def _get_headers(params):\n '''\n Return HTTP headers required.\n '''\n return {\n 'Authorization': 'OAuth {oauth}'.format(oauth=params['api_key'])\n }\n",
"def _get_api_params(api_url=None,\n page_id=None,\n api_key=None,\n api_version=None):\n '''\n Retrieve the API params from the config file.\n '''\n statuspage_cfg = __salt__['config.get']('statuspage')\n if not statuspage_cfg:\n statuspage_cfg = {}\n return {\n 'api_url': api_url or statuspage_cfg.get('api_url') or BASE_URL, # optional\n 'api_page_id': page_id or statuspage_cfg.get('page_id'), # mandatory\n 'api_key': api_key or statuspage_cfg.get('api_key'), # mandatory\n 'api_version': api_version or statuspage_cfg.get('api_version') or DEFAULT_VERSION\n }\n",
"def _http_request(url,\n method='GET',\n headers=None,\n data=None):\n '''\n Make the HTTP request and return the body as python object.\n '''\n req = requests.request(method,\n url,\n headers=headers,\n data=data)\n ret = _default_ret()\n ok_status = METHOD_OK_STATUS.get(method, 200)\n if req.status_code != ok_status:\n ret.update({\n 'comment': req.json().get('error', '')\n })\n return ret\n ret.update({\n 'result': True,\n 'out': req.json() if method != 'DELETE' else None # no body when DELETE\n })\n return ret\n",
"def _validate_api_params(params):\n '''\n Validate the API params as specified in the config file.\n '''\n # page_id and API key are mandatory and they must be string/unicode\n return (isinstance(params['api_page_id'], (six.string_types, six.text_type)) and\n isinstance(params['api_key'], (six.string_types, six.text_type)))\n"
] |
# -*- coding: utf-8 -*-
'''
StatusPage
==========
Handle requests for the StatusPage_ API_.
.. _StatusPage: https://www.statuspage.io/
.. _API: http://doers.statuspage.io/api/v1/
In the minion configuration file, the following block is required:
.. code-block:: yaml
statuspage:
api_key: <API_KEY>
page_id: <PAGE_ID>
.. versionadded:: 2017.7.0
'''
from __future__ import absolute_import, unicode_literals, print_function
# import python std lib
import logging
# import third party
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# import salt
from salt.ext import six
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'statuspage'
log = logging.getLogger(__file__)
BASE_URL = 'https://api.statuspage.io'
DEFAULT_VERSION = 1
UPDATE_FORBIDDEN_FILEDS = [
'id', # can't rewrite this
'created_at',
'updated_at', # updated_at and created_at are handled by the backend framework of the API
'page_id' # can't move it to a different page
]
INSERT_FORBIDDEN_FILEDS = UPDATE_FORBIDDEN_FILEDS[:] # they are the same for the moment
METHOD_OK_STATUS = {
'POST': 201,
'DELETE': 204
}
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
Return the execution module virtualname.
'''
if HAS_REQUESTS is False:
return False, 'The requests python package is not installed'
return __virtualname__
def _default_ret():
'''
Default dictionary returned.
'''
return {
'result': False,
'comment': '',
'out': None
}
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 _get_headers(params):
'''
Return HTTP headers required.
'''
return {
'Authorization': 'OAuth {oauth}'.format(oauth=params['api_key'])
}
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
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
def create(endpoint='incidents',
api_url=None,
page_id=None,
api_key=None,
api_version=None,
**kwargs):
'''
Insert a new entry under a specific endpoint.
endpoint: incidents
Insert under this 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.create endpoint='components' name='my component' group_id='993vgplshj12'
Example output:
.. code-block:: bash
minion:
----------
comment:
out:
----------
created_at:
2017-01-05T19:35:27.135Z
description:
None
group_id:
993vgplshj12
id:
mjkmtt5lhdgc
name:
my component
page_id:
ksdhgfyiuhaa
position:
7
status:
operational
updated_at:
2017-01-05T19:35:27.135Z
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
headers = _get_headers(params)
create_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
)
change_request = {}
for karg, warg in six.iteritems(kwargs):
if warg is None or karg.startswith('__') or karg in INSERT_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(create_url,
method='POST',
headers=headers,
data=change_request)
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)
|
saltstack/salt
|
salt/modules/freebsdpkg.py
|
_get_repo_options
|
python
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdpkg.py#L113-L135
| null |
# -*- coding: utf-8 -*-
'''
Remote package support using ``pkg_add(1)``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. warning::
This module has been completely rewritten. Up to and including version
0.17.0, it supported ``pkg_add(1)``, but checked for the existence of a
pkgng local database and, if found, would provide some of pkgng's
functionality. The rewrite of this module has removed all pkgng support,
and moved it to the :mod:`pkgng <salt.modules.pkgng>` execution module. For
versions <= 0.17.0, the documentation here should not be considered
accurate. If your Minion is running one of these versions, then the
documentation for this module can be viewed using the :mod:`sys.doc
<salt.modules.sys.doc>` function:
.. code-block:: bash
salt bsdminion sys.doc pkg
This module acts as the default package provider for FreeBSD 9 and older. If
you need to use pkgng on a FreeBSD 9 system, you will need to override the
``pkg`` provider by setting the :conf_minion:`providers` parameter in your
Minion config file, in order to use pkgng.
.. code-block:: yaml
providers:
pkg: pkgng
More information on pkgng support can be found in the documentation for the
:mod:`pkgng <salt.modules.pkgng>` module.
This module will respect the ``PACKAGEROOT`` and ``PACKAGESITE`` environment
variables, if set, but these values can also be overridden in several ways:
1. :strong:`Salt configuration parameters.` The configuration parameters
``freebsdpkg.PACKAGEROOT`` and ``freebsdpkg.PACKAGESITE`` are recognized.
These config parameters are looked up using :mod:`config.get
<salt.modules.config.get>` and can thus be specified in the Master config
file, Grains, Pillar, or in the Minion config file. Example:
.. code-block:: yaml
freebsdpkg.PACKAGEROOT: ftp://ftp.freebsd.org/
freebsdpkg.PACKAGESITE: ftp://ftp.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
2. :strong:`CLI arguments.` Both the ``packageroot`` (used interchangeably with
``fromrepo`` for API compatibility) and ``packagesite`` CLI arguments are
recognized, and override their config counterparts from section 1 above.
.. code-block:: bash
salt -G 'os:FreeBSD' pkg.install zsh fromrepo=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packageroot=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packagesite=ftp://ftp2.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
.. note::
These arguments can also be passed through in states:
.. code-block:: yaml
zsh:
pkg.installed:
- fromrepo: ftp://ftp2.freebsd.org/
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import logging
import re
# Import salt libs
import salt.utils.data
import salt.utils.functools
import salt.utils.pkg
from salt.exceptions import CommandExecutionError, MinionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Load as 'pkg' on FreeBSD versions less than 10.
Don't load on FreeBSD 9 when the config option
``providers:pkg`` is set to 'pkgng'.
'''
if __grains__['os'] == 'FreeBSD' and float(__grains__['osrelease']) < 10:
providers = {}
if 'providers' in __opts__:
providers = __opts__['providers']
if providers and 'pkg' in providers and providers['pkg'] == 'pkgng':
log.debug('Configuration option \'providers:pkg\' is set to '
'\'pkgng\', won\'t load old provider \'freebsdpkg\'.')
return (False, 'The freebsdpkg execution module cannot be loaded: the configuration option \'providers:pkg\' is set to \'pkgng\'')
return __virtualname__
return (False, 'The freebsdpkg execution module cannot be loaded: either the os is not FreeBSD or the version of FreeBSD is >= 10.')
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
def latest_version(*names, **kwargs):
'''
``pkg_add(1)`` is not capable of querying for remote packages, so this
function will always return results as if there is no package available for
install or upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
return '' if len(names) == 1 else dict((x, '') for x in names)
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
with_origin : False
Return a nested dictionary containing both the origin name and version
for each specified package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
with_origin = kwargs.pop('with_origin', False)
ret = __salt__['pkg_resource.version'](*names, **kwargs)
if not salt.utils.data.is_true(with_origin):
return ret
# Put the return value back into a dict since we're adding a subdict
if len(names) == 1:
ret = {names[0]: ret}
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
def refresh_db(**kwargs):
'''
``pkg_add(1)`` does not use a local database of available packages, so this
function simply returns ``True``. it exists merely for API compatibility.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
return True
def list_pkgs(versions_as_list=False, with_origin=False, **kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
with_origin : False
Return a nested dictionary containing both the origin name and version
for each installed package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
ret = {}
origins = {}
out = __salt__['cmd.run_stdout'](['pkg_info', '-ao'],
output_loglevel='trace',
python_shell=False)
pkgs_re = re.compile(r'Information for ([^:]+):\s*Origin:\n([^\n]+)')
for pkg, origin in pkgs_re.findall(out):
if not pkg:
continue
try:
pkgname, pkgver = pkg.rsplit('-', 1)
except ValueError:
continue
__salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver)
origins[pkgname] = origin
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
__context__['pkg.origin'] = origins
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
**kwargs):
'''
Install package(s) using ``pkg_add(1)``
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo or packageroot
Specify a package repository from which to install. Overrides the
system default, as well as the PACKAGEROOT environment variable.
packagesite
Specify the exact directory from which to install the remote package.
Overrides the PACKAGESITE environment variable, if present.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
sources
A list of packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"}, {"bar": "salt://bar.deb"}]'
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
'''
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
packageroot = kwargs.get('packageroot')
if not fromrepo and packageroot:
fromrepo = packageroot
env = _get_repo_options(fromrepo, kwargs.get('packagesite'))
args = []
if pkg_type == 'repository':
args.append('-r') # use remote repo
args.extend(pkg_params)
old = list_pkgs()
out = __salt__['cmd.run_all'](
['pkg_add'] + args,
env=env,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
_rehash()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def remove(name=None, pkgs=None, **kwargs):
'''
Remove packages using ``pkg_delete(1)``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets, errors = _match([x for x in pkg_params])
for error in errors:
log.error(error)
if not targets:
return {}
out = __salt__['cmd.run_all'](
['pkg_delete'] + targets,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
# Support pkg.delete to remove packages to more closely match pkg_delete
delete = salt.utils.functools.alias_function(remove, 'delete')
# No equivalent to purge packages, use remove instead
purge = salt.utils.functools.alias_function(remove, 'purge')
def _rehash():
'''
Recomputes internal hash table for the PATH variable. Use whenever a new
command is created during the current session.
'''
shell = __salt__['environ.get']('SHELL')
if shell.split('/')[-1] in ('csh', 'tcsh'):
__salt__['cmd.shell']('rehash', output_loglevel='trace')
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
ret = file_dict(*packages)
files = []
for pkg_files in six.itervalues(ret['files']):
files.extend(pkg_files)
ret['files'] = files
return ret
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the
system's package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
files = {}
if packages:
match_pattern = '\'{0}-[0-9]*\''
cmd = ['pkg_info', '-QL'] + [match_pattern.format(p) for p in packages]
else:
cmd = ['pkg_info', '-QLa']
ret = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in ret['stderr'].splitlines():
errors.append(line)
pkg = None
for line in ret['stdout'].splitlines():
if pkg is not None and line.startswith('/'):
files[pkg].append(line)
elif ':/' in line:
pkg, fn = line.split(':', 1)
pkg, ver = pkg.rsplit('-', 1)
files[pkg] = [fn]
else:
continue # unexpected string
return {'errors': errors, 'files': files}
|
saltstack/salt
|
salt/modules/freebsdpkg.py
|
_match
|
python
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdpkg.py#L138-L184
| null |
# -*- coding: utf-8 -*-
'''
Remote package support using ``pkg_add(1)``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. warning::
This module has been completely rewritten. Up to and including version
0.17.0, it supported ``pkg_add(1)``, but checked for the existence of a
pkgng local database and, if found, would provide some of pkgng's
functionality. The rewrite of this module has removed all pkgng support,
and moved it to the :mod:`pkgng <salt.modules.pkgng>` execution module. For
versions <= 0.17.0, the documentation here should not be considered
accurate. If your Minion is running one of these versions, then the
documentation for this module can be viewed using the :mod:`sys.doc
<salt.modules.sys.doc>` function:
.. code-block:: bash
salt bsdminion sys.doc pkg
This module acts as the default package provider for FreeBSD 9 and older. If
you need to use pkgng on a FreeBSD 9 system, you will need to override the
``pkg`` provider by setting the :conf_minion:`providers` parameter in your
Minion config file, in order to use pkgng.
.. code-block:: yaml
providers:
pkg: pkgng
More information on pkgng support can be found in the documentation for the
:mod:`pkgng <salt.modules.pkgng>` module.
This module will respect the ``PACKAGEROOT`` and ``PACKAGESITE`` environment
variables, if set, but these values can also be overridden in several ways:
1. :strong:`Salt configuration parameters.` The configuration parameters
``freebsdpkg.PACKAGEROOT`` and ``freebsdpkg.PACKAGESITE`` are recognized.
These config parameters are looked up using :mod:`config.get
<salt.modules.config.get>` and can thus be specified in the Master config
file, Grains, Pillar, or in the Minion config file. Example:
.. code-block:: yaml
freebsdpkg.PACKAGEROOT: ftp://ftp.freebsd.org/
freebsdpkg.PACKAGESITE: ftp://ftp.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
2. :strong:`CLI arguments.` Both the ``packageroot`` (used interchangeably with
``fromrepo`` for API compatibility) and ``packagesite`` CLI arguments are
recognized, and override their config counterparts from section 1 above.
.. code-block:: bash
salt -G 'os:FreeBSD' pkg.install zsh fromrepo=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packageroot=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packagesite=ftp://ftp2.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
.. note::
These arguments can also be passed through in states:
.. code-block:: yaml
zsh:
pkg.installed:
- fromrepo: ftp://ftp2.freebsd.org/
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import logging
import re
# Import salt libs
import salt.utils.data
import salt.utils.functools
import salt.utils.pkg
from salt.exceptions import CommandExecutionError, MinionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Load as 'pkg' on FreeBSD versions less than 10.
Don't load on FreeBSD 9 when the config option
``providers:pkg`` is set to 'pkgng'.
'''
if __grains__['os'] == 'FreeBSD' and float(__grains__['osrelease']) < 10:
providers = {}
if 'providers' in __opts__:
providers = __opts__['providers']
if providers and 'pkg' in providers and providers['pkg'] == 'pkgng':
log.debug('Configuration option \'providers:pkg\' is set to '
'\'pkgng\', won\'t load old provider \'freebsdpkg\'.')
return (False, 'The freebsdpkg execution module cannot be loaded: the configuration option \'providers:pkg\' is set to \'pkgng\'')
return __virtualname__
return (False, 'The freebsdpkg execution module cannot be loaded: either the os is not FreeBSD or the version of FreeBSD is >= 10.')
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 latest_version(*names, **kwargs):
'''
``pkg_add(1)`` is not capable of querying for remote packages, so this
function will always return results as if there is no package available for
install or upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
return '' if len(names) == 1 else dict((x, '') for x in names)
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
with_origin : False
Return a nested dictionary containing both the origin name and version
for each specified package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
with_origin = kwargs.pop('with_origin', False)
ret = __salt__['pkg_resource.version'](*names, **kwargs)
if not salt.utils.data.is_true(with_origin):
return ret
# Put the return value back into a dict since we're adding a subdict
if len(names) == 1:
ret = {names[0]: ret}
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
def refresh_db(**kwargs):
'''
``pkg_add(1)`` does not use a local database of available packages, so this
function simply returns ``True``. it exists merely for API compatibility.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
return True
def list_pkgs(versions_as_list=False, with_origin=False, **kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
with_origin : False
Return a nested dictionary containing both the origin name and version
for each installed package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
ret = {}
origins = {}
out = __salt__['cmd.run_stdout'](['pkg_info', '-ao'],
output_loglevel='trace',
python_shell=False)
pkgs_re = re.compile(r'Information for ([^:]+):\s*Origin:\n([^\n]+)')
for pkg, origin in pkgs_re.findall(out):
if not pkg:
continue
try:
pkgname, pkgver = pkg.rsplit('-', 1)
except ValueError:
continue
__salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver)
origins[pkgname] = origin
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
__context__['pkg.origin'] = origins
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
**kwargs):
'''
Install package(s) using ``pkg_add(1)``
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo or packageroot
Specify a package repository from which to install. Overrides the
system default, as well as the PACKAGEROOT environment variable.
packagesite
Specify the exact directory from which to install the remote package.
Overrides the PACKAGESITE environment variable, if present.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
sources
A list of packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"}, {"bar": "salt://bar.deb"}]'
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
'''
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
packageroot = kwargs.get('packageroot')
if not fromrepo and packageroot:
fromrepo = packageroot
env = _get_repo_options(fromrepo, kwargs.get('packagesite'))
args = []
if pkg_type == 'repository':
args.append('-r') # use remote repo
args.extend(pkg_params)
old = list_pkgs()
out = __salt__['cmd.run_all'](
['pkg_add'] + args,
env=env,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
_rehash()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def remove(name=None, pkgs=None, **kwargs):
'''
Remove packages using ``pkg_delete(1)``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets, errors = _match([x for x in pkg_params])
for error in errors:
log.error(error)
if not targets:
return {}
out = __salt__['cmd.run_all'](
['pkg_delete'] + targets,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
# Support pkg.delete to remove packages to more closely match pkg_delete
delete = salt.utils.functools.alias_function(remove, 'delete')
# No equivalent to purge packages, use remove instead
purge = salt.utils.functools.alias_function(remove, 'purge')
def _rehash():
'''
Recomputes internal hash table for the PATH variable. Use whenever a new
command is created during the current session.
'''
shell = __salt__['environ.get']('SHELL')
if shell.split('/')[-1] in ('csh', 'tcsh'):
__salt__['cmd.shell']('rehash', output_loglevel='trace')
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
ret = file_dict(*packages)
files = []
for pkg_files in six.itervalues(ret['files']):
files.extend(pkg_files)
ret['files'] = files
return ret
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the
system's package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
files = {}
if packages:
match_pattern = '\'{0}-[0-9]*\''
cmd = ['pkg_info', '-QL'] + [match_pattern.format(p) for p in packages]
else:
cmd = ['pkg_info', '-QLa']
ret = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in ret['stderr'].splitlines():
errors.append(line)
pkg = None
for line in ret['stdout'].splitlines():
if pkg is not None and line.startswith('/'):
files[pkg].append(line)
elif ':/' in line:
pkg, fn = line.split(':', 1)
pkg, ver = pkg.rsplit('-', 1)
files[pkg] = [fn]
else:
continue # unexpected string
return {'errors': errors, 'files': files}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.