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/states/panos.py
|
remove_config_lock
|
python
|
def remove_config_lock(name):
'''
Release config lock previously held.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/takelock:
panos.remove_config_lock
'''
ret = _default_ret(name)
ret.update({
'changes': __salt__['panos.remove_config_lock'](),
'result': True
})
return ret
|
Release config lock previously held.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/takelock:
panos.remove_config_lock
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L891-L912
|
[
"def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
A state module to manage Palo Alto network devices.
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
About
=====
This state module was designed to handle connections to a Palo Alto based
firewall. This module relies on the Palo Alto proxy module to interface with the devices.
This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It
exposes the core XML API commands and allows state modules to chain complex XPATH commands.
Below is an example of how to construct a security rule and move to the top of the policy. This will take a config
lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will
commit to the device.
.. code-block:: yaml
panos/takelock:
panos.add_config_lock
panos/service_tcp_22:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service
- value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry>
- commit: False
panos/create_rule1:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules
- value: '
<entry name="rule1">
<from><member>trust</member></from>
<to><member>untrust</member></to>
<source><member>10.0.0.1</member></source>
<destination><member>10.0.1.1</member></destination>
<service><member>tcp-22</member></service>
<application><member>any</member></application>
<action>allow</action>
<disabled>no</disabled>
</entry>'
- commit: False
panos/moveruletop:
panos.move_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: top
- commit: False
panos/removelock:
panos.remove_config_lock
panos/commit:
panos.commit
Version Specific Configurations
===============================
Palo Alto devices running different versions will have different supported features and different command structures. In
order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision
level.
The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or
greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and
8.0.0.
.. code-block:: jinja
{% if proxy['panos.is_required_version']('8.0.0') %}
panos/deviceconfig/system/motd-and-banner:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner
- value: |
<banner-header>BANNER TEXT</banner-header>
<banner-header-color>color2</banner-header-color>
<banner-header-text-color>color18</banner-header-text-color>
<banner-header-footer-match>yes</banner-header-footer-match>
- commit: False
{% endif %}
.. seealso::
:py:mod:`Palo Alto Proxy Module <salt.proxy.panos>`
'''
# Import Python Libs
from __future__ import absolute_import
import logging
# Import salt libs
import salt.utils.xmlutil as xml
from salt._compat import ElementTree as ET
log = logging.getLogger(__name__)
def __virtual__():
return 'panos.commit' in __salt__
def _build_members(members, anycheck=False):
'''
Builds a member formatted string for XML operation.
'''
if isinstance(members, list):
# This check will strip down members to a single any statement
if anycheck and 'any' in members:
return "<member>any</member>"
response = ""
for m in members:
response += "<member>{0}</member>".format(m)
return response
else:
return "<member>{0}</member>".format(members)
def _default_ret(name):
'''
Set the default response values.
'''
ret = {
'name': name,
'changes': {},
'commit': None,
'result': False,
'comment': ''
}
return ret
def _edit_config(xpath, element):
'''
Sends an edit request to the device.
'''
query = {'type': 'config',
'action': 'edit',
'xpath': xpath,
'element': element}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _get_config(xpath):
'''
Retrieves an xpath from the device.
'''
query = {'type': 'config',
'action': 'get',
'xpath': xpath}
response = __proxy__['panos.call'](query)
return response
def _move_after(xpath, target):
'''
Moves an xpath to the after of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'after',
'dst': target}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_before(xpath, target):
'''
Moves an xpath to the bottom of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'before',
'dst': target}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_bottom(xpath):
'''
Moves an xpath to the bottom of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'bottom'}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_top(xpath):
'''
Moves an xpath to the top of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'top'}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _set_config(xpath, element):
'''
Sends a set request to the device.
'''
query = {'type': 'config',
'action': 'set',
'xpath': xpath,
'element': element}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _validate_response(response):
'''
Validates a response from a Palo Alto device. Used to verify success of commands.
'''
if not response:
return False, 'Unable to validate response from device.'
elif 'msg' in response:
if 'line' in response['msg']:
if response['msg']['line'] == 'already at the top':
return True, response
elif response['msg']['line'] == 'already at the bottom':
return True, response
else:
return False, response
elif response['msg'] == 'command succeeded':
return True, response
else:
return False, response
elif 'status' in response:
if response['status'] == "success":
return True, response
else:
return False, response
else:
return False, response
def add_config_lock(name):
'''
Prevent other users from changing configuration until the lock is released.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/takelock:
panos.add_config_lock
'''
ret = _default_ret(name)
ret.update({
'changes': __salt__['panos.add_config_lock'](),
'result': True
})
return ret
def address_exists(name,
addressname=None,
vsys=1,
ipnetmask=None,
iprange=None,
fqdn=None,
description=None,
commit=False):
'''
Ensures that an address object exists in the configured state. If it does not exist or is not configured with the
specified attributes, it will be adjusted to match the specified values.
This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified
value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address
type.
name: The name of the module function to execute.
addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where
the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6,
you specify only the network portion, not the host portion.
iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both
can be IPv6.
fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are
subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the
entries are picked up at the refresh cycle.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/address/h-10.10.10.10:
panos.address_exists:
- addressname: h-10.10.10.10
- vsys: 1
- ipnetmask: 10.10.10.10
- commit: False
panos/address/10.0.0.1-10.0.0.50:
panos.address_exists:
- addressname: r-10.0.0.1-10.0.0.50
- vsys: 1
- iprange: 10.0.0.1-10.0.0.50
- commit: False
panos/address/foo.bar.com:
panos.address_exists:
- addressname: foo.bar.com
- vsys: 1
- fqdn: foo.bar.com
- description: My fqdn object
- commit: False
'''
ret = _default_ret(name)
if not addressname:
ret.update({'comment': "The service name field must be provided."})
return ret
# Check if address object currently exists
address = __salt__['panos.get_address'](addressname, vsys)['result']
if address and 'entry' in address:
address = address['entry']
else:
address = {}
element = ""
# Verify the arguments
if ipnetmask:
element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask)
elif iprange:
element = "<ip-range>{0}</ip-range>".format(iprange)
elif fqdn:
element = "<fqdn>{0}</fqdn>".format(fqdn)
else:
ret.update({'comment': "A valid address type must be specified."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element)
new_address = xml.to_dict(ET.fromstring(full_element), True)
if address == new_address:
ret.update({
'comment': 'Address object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \
"entry[@name=\'{1}\']".format(vsys, addressname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': address, 'after': new_address},
'commit': __salt__['panos.commit'](),
'comment': 'Address object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': address, 'after': new_address},
'comment': 'Service object successfully configured.',
'result': True
})
return ret
def address_group_exists(name,
groupname=None,
vsys=1,
members=None,
description=None,
commit=False):
'''
Ensures that an address group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the address group. These must be valid address objects or address groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/address-group/my-group:
panos.address_group_exists:
- groupname: my-group
- vsys: 1
- members:
- my-address-object
- my-other-address-group
- description: A group that needs to exist
- commit: False
'''
ret = _default_ret(name)
if not groupname:
ret.update({'comment': "The group name field must be provided."})
return ret
# Check if address group object currently exists
group = __salt__['panos.get_address_group'](groupname, vsys)['result']
if group and 'entry' in group:
group = group['entry']
else:
group = {}
# Verify the arguments
if members:
element = "<static>{0}</static>".format(_build_members(members, True))
else:
ret.update({'comment': "The group members must be provided."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element)
new_group = xml.to_dict(ET.fromstring(full_element), True)
if group == new_group:
ret.update({
'comment': 'Address group object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \
"entry[@name=\'{1}\']".format(vsys, groupname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': group, 'after': new_group},
'commit': __salt__['panos.commit'](),
'comment': 'Address group object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': group, 'after': new_group},
'comment': 'Address group object successfully configured.',
'result': True
})
return ret
def clone_config(name, xpath=None, newname=None, commit=False):
'''
Clone a specific XPATH and set it to a new name.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to clone.
newname(str): The new name of the XPATH clone.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/clonerule:
panos.clone_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/
entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- value: rule2
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not newname:
return ret
query = {'type': 'config',
'action': 'clone',
'xpath': xpath,
'newname': newname}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def commit_config(name):
'''
Commits the candidate configuration to the running configuration.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/commit:
panos.commit_config
'''
ret = _default_ret(name)
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def delete_config(name, xpath=None, commit=False):
'''
Deletes a Palo Alto XPATH to a specific value.
Use the xpath parameter to specify the location of the object to be deleted.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/deletegroup:
panos.delete_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test']
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
query = {'type': 'config',
'action': 'delete',
'xpath': xpath}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def download_software(name, version=None, synch=False, check=False):
'''
Ensures that a software version is downloaded.
name: The name of the module function to execute.
version(str): The software version to check. If this version is not already downloaded, it will attempt to download
the file from Palo Alto.
synch(bool): If true, after downloading the file it will be synched to its peer.
check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo
Alto.
SLS Example:
.. code-block:: yaml
panos/version8.0.0:
panos.download_software:
- version: 8.0.0
- synch: False
- check: True
'''
ret = _default_ret(name)
if check is True:
__salt__['panos.check_software']()
versions = __salt__['panos.get_software_info']()['result']
if 'sw-updates' not in versions \
or 'versions' not in versions['sw-updates'] \
or 'entry' not in versions['sw-updates']['versions']:
ret.update({
'comment': 'Software version is not found in the local software list.',
'result': False
})
return ret
for entry in versions['sw-updates']['versions']['entry']:
if entry['version'] == version and entry['downloaded'] == "yes":
ret.update({
'comment': 'Software version is already downloaded.',
'result': True
})
return ret
ret.update({
'changes': __salt__['panos.download_software_version'](version=version, synch=synch)
})
versions = __salt__['panos.get_software_info']()['result']
if 'sw-updates' not in versions \
or 'versions' not in versions['sw-updates'] \
or 'entry' not in versions['sw-updates']['versions']:
ret.update({
'result': False
})
return ret
for entry in versions['sw-updates']['versions']['entry']:
if entry['version'] == version and entry['downloaded'] == "yes":
ret.update({
'result': True
})
return ret
return ret
def edit_config(name, xpath=None, value=None, commit=False):
'''
Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not
changed.
You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use
the xpath parameter to specify the location of the object, including the node to be replaced.
This is the recommended state to enforce configurations on a xpath.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
value(str): The XML value to edit. This must be a child to the XPATH.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/addressgroup:
panos.edit_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test']
- value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static>
- commit: True
'''
ret = _default_ret(name)
# Verify if the current XPATH is equal to the specified value.
# If we are equal, no changes required.
xpath_split = xpath.split("/")
# Retrieve the head of the xpath for validation.
if xpath_split:
head = xpath_split[-1]
if "[" in head:
head = head.split("[")[0]
current_element = __salt__['panos.get_xpath'](xpath)['result']
if head and current_element and head in current_element:
current_element = current_element[head]
else:
current_element = {}
new_element = xml.to_dict(ET.fromstring(value), True)
if current_element == new_element:
ret.update({
'comment': 'XPATH is already equal to the specified value.',
'result': True
})
return ret
result, msg = _edit_config(xpath, value)
ret.update({
'comment': msg,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'changes': {'before': current_element, 'after': new_element},
'commit': __salt__['panos.commit'](),
'result': True
})
else:
ret.update({
'changes': {'before': current_element, 'after': new_element},
'result': True
})
return ret
def move_config(name, xpath=None, where=None, dst=None, commit=False):
'''
Moves a XPATH value to a new location.
Use the xpath parameter to specify the location of the object to be moved, the where parameter to
specify type of move, and dst parameter to specify the destination path.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to move.
where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before
options will require the dst option to specify the destination of the action. The top action will move the
XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure.
dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top
or bottom action.
commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is
not successful, it will not commit.
SLS Example:
.. code-block:: yaml
panos/moveruletop:
panos.move_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: top
- commit: True
panos/moveruleafter:
panos.move_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: after
- dst: rule2
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not where:
return ret
if where == 'after':
result, msg = _move_after(xpath, dst)
elif where == 'before':
result, msg = _move_before(xpath, dst)
elif where == 'top':
result, msg = _move_top(xpath)
elif where == 'bottom':
result, msg = _move_bottom(xpath)
ret.update({
'result': result,
'comment': msg
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def rename_config(name, xpath=None, newname=None, commit=False):
'''
Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
newname(str): The new name of the XPATH value.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/renamegroup:
panos.rename_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address']
- value: new_address
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not newname:
return ret
query = {'type': 'config',
'action': 'rename',
'xpath': xpath,
'newname': newname}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def security_rule_exists(name,
rulename=None,
vsys='1',
action=None,
disabled=None,
sourcezone=None,
destinationzone=None,
source=None,
destination=None,
application=None,
service=None,
description=None,
logsetting=None,
logstart=None,
logend=None,
negatesource=None,
negatedestination=None,
profilegroup=None,
datafilter=None,
fileblock=None,
spyware=None,
urlfilter=None,
virus=None,
vulnerability=None,
wildfire=None,
move=None,
movetarget=None,
commit=False):
'''
Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately.
This method will create the rule if it does not exist. If the rule does exist, it will ensure that the
configurations are set appropriately.
If the rule does not exist and is created, any value that is not provided will be provided as the default.
The action, to, from, source, destination, application, and service fields are mandatory and must be provided.
This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end
option, but this option is not specified in the state method, it will be removed and reset to the system default.
It is strongly recommended to specify all options to ensure proper operation.
When defining the profile group settings, the device can only support either a profile group or individual settings.
If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are
specified, the value will be set to system default of none.
name: The name of the module function to execute.
rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which
can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama,
unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client,
reset-server, reset-both.
disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable.
sourcezone(str, list): The source zone(s). The value 'any' will match all zones.
destinationzone(str, list): The destination zone(s). The value 'any' will match all zones.
source(str, list): The source address(es). The value 'any' will match all addresses.
destination(str, list): The destination address(es). The value 'any' will match all addresses.
application(str, list): The application(s) matched. The value 'any' will match all applications.
service(str, list): The service(s) matched. The value 'any' will match all services. The value
'application-default' will match based upon the application defined ports.
description(str): A description for the policy (up to 255 characters).
logsetting(str): The name of a valid log forwarding profile.
logstart(bool): Generates a traffic log entry for the start of a session (disabled by default).
logend(bool): Generates a traffic log entry for the end of a session (enabled by default).
negatesource(bool): Match all but the specified source addresses.
negatedestination(bool): Match all but the specified destination addresses.
profilegroup(str): A valid profile group name.
datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set.
fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set.
spyware(str): A valid spyware profile name. Ignored with the profilegroup option set.
urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set.
virus(str): A valid virus profile name. Ignored with the profilegroup option set.
vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top',
'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument
to define the location of the move request.
movetarget(str): An optional argument that defines the target of the move operation if the move argument is
set to 'before' or 'after'.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: True
- negatesource: False
- negatedestination: False
- profilegroup: myprofilegroup
- move: top
- commit: False
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: False
- datafilter: foobar
- fileblock: foobar
- spyware: foobar
- urlfilter: foobar
- virus: foobar
- vulnerability: foobar
- wildfire: foobar
- move: after
- movetarget: rule02
- commit: False
'''
ret = _default_ret(name)
if not rulename:
return ret
# Check if rule currently exists
rule = __salt__['panos.get_security_rule'](rulename, vsys)['result']
if rule and 'entry' in rule:
rule = rule['entry']
else:
rule = {}
# Build the rule element
element = ""
if sourcezone:
element += "<from>{0}</from>".format(_build_members(sourcezone, True))
else:
ret.update({'comment': "The sourcezone field must be provided."})
return ret
if destinationzone:
element += "<to>{0}</to>".format(_build_members(destinationzone, True))
else:
ret.update({'comment': "The destinationzone field must be provided."})
return ret
if source:
element += "<source>{0}</source>".format(_build_members(source, True))
else:
ret.update({'comment': "The source field must be provided."})
return
if destination:
element += "<destination>{0}</destination>".format(_build_members(destination, True))
else:
ret.update({'comment': "The destination field must be provided."})
return ret
if application:
element += "<application>{0}</application>".format(_build_members(application, True))
else:
ret.update({'comment': "The application field must be provided."})
return ret
if service:
element += "<service>{0}</service>".format(_build_members(service, True))
else:
ret.update({'comment': "The service field must be provided."})
return ret
if action:
element += "<action>{0}</action>".format(action)
else:
ret.update({'comment': "The action field must be provided."})
return ret
if disabled is not None:
if disabled:
element += "<disabled>yes</disabled>"
else:
element += "<disabled>no</disabled>"
if description:
element += "<description>{0}</description>".format(description)
if logsetting:
element += "<log-setting>{0}</log-setting>".format(logsetting)
if logstart is not None:
if logstart:
element += "<log-start>yes</log-start>"
else:
element += "<log-start>no</log-start>"
if logend is not None:
if logend:
element += "<log-end>yes</log-end>"
else:
element += "<log-end>no</log-end>"
if negatesource is not None:
if negatesource:
element += "<negate-source>yes</negate-source>"
else:
element += "<negate-source>no</negate-source>"
if negatedestination is not None:
if negatedestination:
element += "<negate-destination>yes</negate-destination>"
else:
element += "<negate-destination>no</negate-destination>"
# Build the profile settings
profile_string = None
if profilegroup:
profile_string = "<group><member>{0}</member></group>".format(profilegroup)
else:
member_string = ""
if datafilter:
member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter)
if fileblock:
member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock)
if spyware:
member_string += "<spyware><member>{0}</member></spyware>".format(spyware)
if urlfilter:
member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter)
if virus:
member_string += "<virus><member>{0}</member></virus>".format(virus)
if vulnerability:
member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability)
if wildfire:
member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire)
if member_string != "":
profile_string = "<profiles>{0}</profiles>".format(member_string)
if profile_string:
element += "<profile-setting>{0}</profile-setting>".format(profile_string)
full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element)
new_rule = xml.to_dict(ET.fromstring(full_element), True)
config_change = False
if rule == new_rule:
ret.update({
'comment': 'Security rule already exists. No changes required.'
})
else:
config_change = True
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \
"security/rules/entry[@name=\'{1}\']".format(vsys, rulename)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
ret.update({
'changes': {'before': rule, 'after': new_rule},
'comment': 'Security rule verified successfully.'
})
if move:
movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \
"security/rules/entry[@name=\'{1}\']".format(vsys, rulename)
move_result = False
move_msg = ''
if move == "before" and movetarget:
move_result, move_msg = _move_before(movepath, movetarget)
elif move == "after":
move_result, move_msg = _move_after(movepath, movetarget)
elif move == "top":
move_result, move_msg = _move_top(movepath)
elif move == "bottom":
move_result, move_msg = _move_bottom(movepath)
if config_change:
ret.update({
'changes': {'before': rule, 'after': new_rule, 'move': move_msg}
})
else:
ret.update({
'changes': {'move': move_msg}
})
if not move_result:
ret.update({
'comment': move_msg
})
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
else:
ret.update({
'result': True
})
return ret
def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False):
'''
Ensures that a service object exists in the configured state. If it does not exist or is not configured with the
specified attributes, it will be adjusted to match the specified values.
name: The name of the module function to execute.
servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp.
port(str): The port number that is used by the service object. This can be specified as a single integer or a
valid range of ports.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service/tcp-80:
panos.service_exists:
- servicename: tcp-80
- vsys: 1
- protocol: tcp
- port: 80
- description: Hypertext Transfer Protocol
- commit: False
panos/service/udp-500-550:
panos.service_exists:
- servicename: udp-500-550
- vsys: 3
- protocol: udp
- port: 500-550
- commit: False
'''
ret = _default_ret(name)
if not servicename:
ret.update({'comment': "The service name field must be provided."})
return ret
# Check if service object currently exists
service = __salt__['panos.get_service'](servicename, vsys)['result']
if service and 'entry' in service:
service = service['entry']
else:
service = {}
# Verify the arguments
if not protocol and protocol not in ['tcp', 'udp']:
ret.update({'comment': "The protocol must be provided and must be tcp or udp."})
return ret
if not port:
ret.update({'comment': "The port field must be provided."})
return ret
element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port)
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element)
new_service = xml.to_dict(ET.fromstring(full_element), True)
if service == new_service:
ret.update({
'comment': 'Service object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \
"entry[@name=\'{1}\']".format(vsys, servicename)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': service, 'after': new_service},
'commit': __salt__['panos.commit'](),
'comment': 'Service object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': service, 'after': new_service},
'comment': 'Service object successfully configured.',
'result': True
})
return ret
def service_group_exists(name,
groupname=None,
vsys=1,
members=None,
description=None,
commit=False):
'''
Ensures that a service group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the service group. These must be valid service objects or service groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service-group/my-group:
panos.service_group_exists:
- groupname: my-group
- vsys: 1
- members:
- tcp-80
- custom-port-group
- description: A group that needs to exist
- commit: False
'''
ret = _default_ret(name)
if not groupname:
ret.update({'comment': "The group name field must be provided."})
return ret
# Check if service group object currently exists
group = __salt__['panos.get_service_group'](groupname, vsys)['result']
if group and 'entry' in group:
group = group['entry']
else:
group = {}
# Verify the arguments
if members:
element = "<members>{0}</members>".format(_build_members(members, True))
else:
ret.update({'comment': "The group members must be provided."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element)
new_group = xml.to_dict(ET.fromstring(full_element), True)
if group == new_group:
ret.update({
'comment': 'Service group object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \
"entry[@name=\'{1}\']".format(vsys, groupname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': group, 'after': new_group},
'commit': __salt__['panos.commit'](),
'comment': 'Service group object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': group, 'after': new_group},
'comment': 'Service group object successfully configured.',
'result': True
})
return ret
def set_config(name, xpath=None, value=None, commit=False):
'''
Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not
changed.
You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter
to specify the location of the object in the configuration
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
value(str): The XML value to set. This must be a child to the XPATH.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/hostname:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system
- value: <hostname>foobar</hostname>
- commit: True
'''
ret = _default_ret(name)
result, msg = _set_config(xpath, value)
ret.update({
'comment': msg,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
|
saltstack/salt
|
salt/states/panos.py
|
security_rule_exists
|
python
|
def security_rule_exists(name,
rulename=None,
vsys='1',
action=None,
disabled=None,
sourcezone=None,
destinationzone=None,
source=None,
destination=None,
application=None,
service=None,
description=None,
logsetting=None,
logstart=None,
logend=None,
negatesource=None,
negatedestination=None,
profilegroup=None,
datafilter=None,
fileblock=None,
spyware=None,
urlfilter=None,
virus=None,
vulnerability=None,
wildfire=None,
move=None,
movetarget=None,
commit=False):
'''
Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately.
This method will create the rule if it does not exist. If the rule does exist, it will ensure that the
configurations are set appropriately.
If the rule does not exist and is created, any value that is not provided will be provided as the default.
The action, to, from, source, destination, application, and service fields are mandatory and must be provided.
This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end
option, but this option is not specified in the state method, it will be removed and reset to the system default.
It is strongly recommended to specify all options to ensure proper operation.
When defining the profile group settings, the device can only support either a profile group or individual settings.
If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are
specified, the value will be set to system default of none.
name: The name of the module function to execute.
rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which
can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama,
unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client,
reset-server, reset-both.
disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable.
sourcezone(str, list): The source zone(s). The value 'any' will match all zones.
destinationzone(str, list): The destination zone(s). The value 'any' will match all zones.
source(str, list): The source address(es). The value 'any' will match all addresses.
destination(str, list): The destination address(es). The value 'any' will match all addresses.
application(str, list): The application(s) matched. The value 'any' will match all applications.
service(str, list): The service(s) matched. The value 'any' will match all services. The value
'application-default' will match based upon the application defined ports.
description(str): A description for the policy (up to 255 characters).
logsetting(str): The name of a valid log forwarding profile.
logstart(bool): Generates a traffic log entry for the start of a session (disabled by default).
logend(bool): Generates a traffic log entry for the end of a session (enabled by default).
negatesource(bool): Match all but the specified source addresses.
negatedestination(bool): Match all but the specified destination addresses.
profilegroup(str): A valid profile group name.
datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set.
fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set.
spyware(str): A valid spyware profile name. Ignored with the profilegroup option set.
urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set.
virus(str): A valid virus profile name. Ignored with the profilegroup option set.
vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top',
'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument
to define the location of the move request.
movetarget(str): An optional argument that defines the target of the move operation if the move argument is
set to 'before' or 'after'.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: True
- negatesource: False
- negatedestination: False
- profilegroup: myprofilegroup
- move: top
- commit: False
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: False
- datafilter: foobar
- fileblock: foobar
- spyware: foobar
- urlfilter: foobar
- virus: foobar
- vulnerability: foobar
- wildfire: foobar
- move: after
- movetarget: rule02
- commit: False
'''
ret = _default_ret(name)
if not rulename:
return ret
# Check if rule currently exists
rule = __salt__['panos.get_security_rule'](rulename, vsys)['result']
if rule and 'entry' in rule:
rule = rule['entry']
else:
rule = {}
# Build the rule element
element = ""
if sourcezone:
element += "<from>{0}</from>".format(_build_members(sourcezone, True))
else:
ret.update({'comment': "The sourcezone field must be provided."})
return ret
if destinationzone:
element += "<to>{0}</to>".format(_build_members(destinationzone, True))
else:
ret.update({'comment': "The destinationzone field must be provided."})
return ret
if source:
element += "<source>{0}</source>".format(_build_members(source, True))
else:
ret.update({'comment': "The source field must be provided."})
return
if destination:
element += "<destination>{0}</destination>".format(_build_members(destination, True))
else:
ret.update({'comment': "The destination field must be provided."})
return ret
if application:
element += "<application>{0}</application>".format(_build_members(application, True))
else:
ret.update({'comment': "The application field must be provided."})
return ret
if service:
element += "<service>{0}</service>".format(_build_members(service, True))
else:
ret.update({'comment': "The service field must be provided."})
return ret
if action:
element += "<action>{0}</action>".format(action)
else:
ret.update({'comment': "The action field must be provided."})
return ret
if disabled is not None:
if disabled:
element += "<disabled>yes</disabled>"
else:
element += "<disabled>no</disabled>"
if description:
element += "<description>{0}</description>".format(description)
if logsetting:
element += "<log-setting>{0}</log-setting>".format(logsetting)
if logstart is not None:
if logstart:
element += "<log-start>yes</log-start>"
else:
element += "<log-start>no</log-start>"
if logend is not None:
if logend:
element += "<log-end>yes</log-end>"
else:
element += "<log-end>no</log-end>"
if negatesource is not None:
if negatesource:
element += "<negate-source>yes</negate-source>"
else:
element += "<negate-source>no</negate-source>"
if negatedestination is not None:
if negatedestination:
element += "<negate-destination>yes</negate-destination>"
else:
element += "<negate-destination>no</negate-destination>"
# Build the profile settings
profile_string = None
if profilegroup:
profile_string = "<group><member>{0}</member></group>".format(profilegroup)
else:
member_string = ""
if datafilter:
member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter)
if fileblock:
member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock)
if spyware:
member_string += "<spyware><member>{0}</member></spyware>".format(spyware)
if urlfilter:
member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter)
if virus:
member_string += "<virus><member>{0}</member></virus>".format(virus)
if vulnerability:
member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability)
if wildfire:
member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire)
if member_string != "":
profile_string = "<profiles>{0}</profiles>".format(member_string)
if profile_string:
element += "<profile-setting>{0}</profile-setting>".format(profile_string)
full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element)
new_rule = xml.to_dict(ET.fromstring(full_element), True)
config_change = False
if rule == new_rule:
ret.update({
'comment': 'Security rule already exists. No changes required.'
})
else:
config_change = True
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \
"security/rules/entry[@name=\'{1}\']".format(vsys, rulename)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
ret.update({
'changes': {'before': rule, 'after': new_rule},
'comment': 'Security rule verified successfully.'
})
if move:
movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \
"security/rules/entry[@name=\'{1}\']".format(vsys, rulename)
move_result = False
move_msg = ''
if move == "before" and movetarget:
move_result, move_msg = _move_before(movepath, movetarget)
elif move == "after":
move_result, move_msg = _move_after(movepath, movetarget)
elif move == "top":
move_result, move_msg = _move_top(movepath)
elif move == "bottom":
move_result, move_msg = _move_bottom(movepath)
if config_change:
ret.update({
'changes': {'before': rule, 'after': new_rule, 'move': move_msg}
})
else:
ret.update({
'changes': {'move': move_msg}
})
if not move_result:
ret.update({
'comment': move_msg
})
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
else:
ret.update({
'result': True
})
return ret
|
Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately.
This method will create the rule if it does not exist. If the rule does exist, it will ensure that the
configurations are set appropriately.
If the rule does not exist and is created, any value that is not provided will be provided as the default.
The action, to, from, source, destination, application, and service fields are mandatory and must be provided.
This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end
option, but this option is not specified in the state method, it will be removed and reset to the system default.
It is strongly recommended to specify all options to ensure proper operation.
When defining the profile group settings, the device can only support either a profile group or individual settings.
If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are
specified, the value will be set to system default of none.
name: The name of the module function to execute.
rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which
can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama,
unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client,
reset-server, reset-both.
disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable.
sourcezone(str, list): The source zone(s). The value 'any' will match all zones.
destinationzone(str, list): The destination zone(s). The value 'any' will match all zones.
source(str, list): The source address(es). The value 'any' will match all addresses.
destination(str, list): The destination address(es). The value 'any' will match all addresses.
application(str, list): The application(s) matched. The value 'any' will match all applications.
service(str, list): The service(s) matched. The value 'any' will match all services. The value
'application-default' will match based upon the application defined ports.
description(str): A description for the policy (up to 255 characters).
logsetting(str): The name of a valid log forwarding profile.
logstart(bool): Generates a traffic log entry for the start of a session (disabled by default).
logend(bool): Generates a traffic log entry for the end of a session (enabled by default).
negatesource(bool): Match all but the specified source addresses.
negatedestination(bool): Match all but the specified destination addresses.
profilegroup(str): A valid profile group name.
datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set.
fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set.
spyware(str): A valid spyware profile name. Ignored with the profilegroup option set.
urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set.
virus(str): A valid virus profile name. Ignored with the profilegroup option set.
vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top',
'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument
to define the location of the move request.
movetarget(str): An optional argument that defines the target of the move operation if the move argument is
set to 'before' or 'after'.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: True
- negatesource: False
- negatedestination: False
- profilegroup: myprofilegroup
- move: top
- commit: False
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: False
- datafilter: foobar
- fileblock: foobar
- spyware: foobar
- urlfilter: foobar
- virus: foobar
- vulnerability: foobar
- wildfire: foobar
- move: after
- movetarget: rule02
- commit: False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L970-L1328
|
[
"def to_dict(xmltree, attr=False):\n '''\n Convert an XML tree into a dict. The tree that is passed in must be an\n ElementTree object.\n Args:\n xmltree: An ElementTree object.\n attr: If true, attributes will be parsed. If false, they will be ignored.\n\n '''\n if attr:\n return _to_full_dict(xmltree)\n else:\n return _to_dict(xmltree)\n",
"def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n",
"def _build_members(members, anycheck=False):\n '''\n Builds a member formatted string for XML operation.\n\n '''\n if isinstance(members, list):\n\n # This check will strip down members to a single any statement\n if anycheck and 'any' in members:\n return \"<member>any</member>\"\n response = \"\"\n for m in members:\n response += \"<member>{0}</member>\".format(m)\n return response\n else:\n return \"<member>{0}</member>\".format(members)\n",
"def _edit_config(xpath, element):\n '''\n Sends an edit request to the device.\n\n '''\n query = {'type': 'config',\n 'action': 'edit',\n 'xpath': xpath,\n 'element': element}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n",
"def _move_after(xpath, target):\n '''\n Moves an xpath to the after of its section.\n\n '''\n query = {'type': 'config',\n 'action': 'move',\n 'xpath': xpath,\n 'where': 'after',\n 'dst': target}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n",
"def _move_before(xpath, target):\n '''\n Moves an xpath to the bottom of its section.\n\n '''\n query = {'type': 'config',\n 'action': 'move',\n 'xpath': xpath,\n 'where': 'before',\n 'dst': target}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n",
"def _move_bottom(xpath):\n '''\n Moves an xpath to the bottom of its section.\n\n '''\n query = {'type': 'config',\n 'action': 'move',\n 'xpath': xpath,\n 'where': 'bottom'}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n",
"def _move_top(xpath):\n '''\n Moves an xpath to the top of its section.\n\n '''\n query = {'type': 'config',\n 'action': 'move',\n 'xpath': xpath,\n 'where': 'top'}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n"
] |
# -*- coding: utf-8 -*-
'''
A state module to manage Palo Alto network devices.
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
About
=====
This state module was designed to handle connections to a Palo Alto based
firewall. This module relies on the Palo Alto proxy module to interface with the devices.
This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It
exposes the core XML API commands and allows state modules to chain complex XPATH commands.
Below is an example of how to construct a security rule and move to the top of the policy. This will take a config
lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will
commit to the device.
.. code-block:: yaml
panos/takelock:
panos.add_config_lock
panos/service_tcp_22:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service
- value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry>
- commit: False
panos/create_rule1:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules
- value: '
<entry name="rule1">
<from><member>trust</member></from>
<to><member>untrust</member></to>
<source><member>10.0.0.1</member></source>
<destination><member>10.0.1.1</member></destination>
<service><member>tcp-22</member></service>
<application><member>any</member></application>
<action>allow</action>
<disabled>no</disabled>
</entry>'
- commit: False
panos/moveruletop:
panos.move_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: top
- commit: False
panos/removelock:
panos.remove_config_lock
panos/commit:
panos.commit
Version Specific Configurations
===============================
Palo Alto devices running different versions will have different supported features and different command structures. In
order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision
level.
The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or
greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and
8.0.0.
.. code-block:: jinja
{% if proxy['panos.is_required_version']('8.0.0') %}
panos/deviceconfig/system/motd-and-banner:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner
- value: |
<banner-header>BANNER TEXT</banner-header>
<banner-header-color>color2</banner-header-color>
<banner-header-text-color>color18</banner-header-text-color>
<banner-header-footer-match>yes</banner-header-footer-match>
- commit: False
{% endif %}
.. seealso::
:py:mod:`Palo Alto Proxy Module <salt.proxy.panos>`
'''
# Import Python Libs
from __future__ import absolute_import
import logging
# Import salt libs
import salt.utils.xmlutil as xml
from salt._compat import ElementTree as ET
log = logging.getLogger(__name__)
def __virtual__():
return 'panos.commit' in __salt__
def _build_members(members, anycheck=False):
'''
Builds a member formatted string for XML operation.
'''
if isinstance(members, list):
# This check will strip down members to a single any statement
if anycheck and 'any' in members:
return "<member>any</member>"
response = ""
for m in members:
response += "<member>{0}</member>".format(m)
return response
else:
return "<member>{0}</member>".format(members)
def _default_ret(name):
'''
Set the default response values.
'''
ret = {
'name': name,
'changes': {},
'commit': None,
'result': False,
'comment': ''
}
return ret
def _edit_config(xpath, element):
'''
Sends an edit request to the device.
'''
query = {'type': 'config',
'action': 'edit',
'xpath': xpath,
'element': element}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _get_config(xpath):
'''
Retrieves an xpath from the device.
'''
query = {'type': 'config',
'action': 'get',
'xpath': xpath}
response = __proxy__['panos.call'](query)
return response
def _move_after(xpath, target):
'''
Moves an xpath to the after of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'after',
'dst': target}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_before(xpath, target):
'''
Moves an xpath to the bottom of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'before',
'dst': target}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_bottom(xpath):
'''
Moves an xpath to the bottom of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'bottom'}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_top(xpath):
'''
Moves an xpath to the top of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'top'}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _set_config(xpath, element):
'''
Sends a set request to the device.
'''
query = {'type': 'config',
'action': 'set',
'xpath': xpath,
'element': element}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _validate_response(response):
'''
Validates a response from a Palo Alto device. Used to verify success of commands.
'''
if not response:
return False, 'Unable to validate response from device.'
elif 'msg' in response:
if 'line' in response['msg']:
if response['msg']['line'] == 'already at the top':
return True, response
elif response['msg']['line'] == 'already at the bottom':
return True, response
else:
return False, response
elif response['msg'] == 'command succeeded':
return True, response
else:
return False, response
elif 'status' in response:
if response['status'] == "success":
return True, response
else:
return False, response
else:
return False, response
def add_config_lock(name):
'''
Prevent other users from changing configuration until the lock is released.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/takelock:
panos.add_config_lock
'''
ret = _default_ret(name)
ret.update({
'changes': __salt__['panos.add_config_lock'](),
'result': True
})
return ret
def address_exists(name,
addressname=None,
vsys=1,
ipnetmask=None,
iprange=None,
fqdn=None,
description=None,
commit=False):
'''
Ensures that an address object exists in the configured state. If it does not exist or is not configured with the
specified attributes, it will be adjusted to match the specified values.
This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified
value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address
type.
name: The name of the module function to execute.
addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where
the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6,
you specify only the network portion, not the host portion.
iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both
can be IPv6.
fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are
subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the
entries are picked up at the refresh cycle.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/address/h-10.10.10.10:
panos.address_exists:
- addressname: h-10.10.10.10
- vsys: 1
- ipnetmask: 10.10.10.10
- commit: False
panos/address/10.0.0.1-10.0.0.50:
panos.address_exists:
- addressname: r-10.0.0.1-10.0.0.50
- vsys: 1
- iprange: 10.0.0.1-10.0.0.50
- commit: False
panos/address/foo.bar.com:
panos.address_exists:
- addressname: foo.bar.com
- vsys: 1
- fqdn: foo.bar.com
- description: My fqdn object
- commit: False
'''
ret = _default_ret(name)
if not addressname:
ret.update({'comment': "The service name field must be provided."})
return ret
# Check if address object currently exists
address = __salt__['panos.get_address'](addressname, vsys)['result']
if address and 'entry' in address:
address = address['entry']
else:
address = {}
element = ""
# Verify the arguments
if ipnetmask:
element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask)
elif iprange:
element = "<ip-range>{0}</ip-range>".format(iprange)
elif fqdn:
element = "<fqdn>{0}</fqdn>".format(fqdn)
else:
ret.update({'comment': "A valid address type must be specified."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element)
new_address = xml.to_dict(ET.fromstring(full_element), True)
if address == new_address:
ret.update({
'comment': 'Address object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \
"entry[@name=\'{1}\']".format(vsys, addressname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': address, 'after': new_address},
'commit': __salt__['panos.commit'](),
'comment': 'Address object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': address, 'after': new_address},
'comment': 'Service object successfully configured.',
'result': True
})
return ret
def address_group_exists(name,
groupname=None,
vsys=1,
members=None,
description=None,
commit=False):
'''
Ensures that an address group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the address group. These must be valid address objects or address groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/address-group/my-group:
panos.address_group_exists:
- groupname: my-group
- vsys: 1
- members:
- my-address-object
- my-other-address-group
- description: A group that needs to exist
- commit: False
'''
ret = _default_ret(name)
if not groupname:
ret.update({'comment': "The group name field must be provided."})
return ret
# Check if address group object currently exists
group = __salt__['panos.get_address_group'](groupname, vsys)['result']
if group and 'entry' in group:
group = group['entry']
else:
group = {}
# Verify the arguments
if members:
element = "<static>{0}</static>".format(_build_members(members, True))
else:
ret.update({'comment': "The group members must be provided."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element)
new_group = xml.to_dict(ET.fromstring(full_element), True)
if group == new_group:
ret.update({
'comment': 'Address group object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \
"entry[@name=\'{1}\']".format(vsys, groupname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': group, 'after': new_group},
'commit': __salt__['panos.commit'](),
'comment': 'Address group object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': group, 'after': new_group},
'comment': 'Address group object successfully configured.',
'result': True
})
return ret
def clone_config(name, xpath=None, newname=None, commit=False):
'''
Clone a specific XPATH and set it to a new name.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to clone.
newname(str): The new name of the XPATH clone.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/clonerule:
panos.clone_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/
entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- value: rule2
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not newname:
return ret
query = {'type': 'config',
'action': 'clone',
'xpath': xpath,
'newname': newname}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def commit_config(name):
'''
Commits the candidate configuration to the running configuration.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/commit:
panos.commit_config
'''
ret = _default_ret(name)
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def delete_config(name, xpath=None, commit=False):
'''
Deletes a Palo Alto XPATH to a specific value.
Use the xpath parameter to specify the location of the object to be deleted.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/deletegroup:
panos.delete_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test']
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
query = {'type': 'config',
'action': 'delete',
'xpath': xpath}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def download_software(name, version=None, synch=False, check=False):
'''
Ensures that a software version is downloaded.
name: The name of the module function to execute.
version(str): The software version to check. If this version is not already downloaded, it will attempt to download
the file from Palo Alto.
synch(bool): If true, after downloading the file it will be synched to its peer.
check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo
Alto.
SLS Example:
.. code-block:: yaml
panos/version8.0.0:
panos.download_software:
- version: 8.0.0
- synch: False
- check: True
'''
ret = _default_ret(name)
if check is True:
__salt__['panos.check_software']()
versions = __salt__['panos.get_software_info']()['result']
if 'sw-updates' not in versions \
or 'versions' not in versions['sw-updates'] \
or 'entry' not in versions['sw-updates']['versions']:
ret.update({
'comment': 'Software version is not found in the local software list.',
'result': False
})
return ret
for entry in versions['sw-updates']['versions']['entry']:
if entry['version'] == version and entry['downloaded'] == "yes":
ret.update({
'comment': 'Software version is already downloaded.',
'result': True
})
return ret
ret.update({
'changes': __salt__['panos.download_software_version'](version=version, synch=synch)
})
versions = __salt__['panos.get_software_info']()['result']
if 'sw-updates' not in versions \
or 'versions' not in versions['sw-updates'] \
or 'entry' not in versions['sw-updates']['versions']:
ret.update({
'result': False
})
return ret
for entry in versions['sw-updates']['versions']['entry']:
if entry['version'] == version and entry['downloaded'] == "yes":
ret.update({
'result': True
})
return ret
return ret
def edit_config(name, xpath=None, value=None, commit=False):
'''
Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not
changed.
You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use
the xpath parameter to specify the location of the object, including the node to be replaced.
This is the recommended state to enforce configurations on a xpath.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
value(str): The XML value to edit. This must be a child to the XPATH.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/addressgroup:
panos.edit_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test']
- value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static>
- commit: True
'''
ret = _default_ret(name)
# Verify if the current XPATH is equal to the specified value.
# If we are equal, no changes required.
xpath_split = xpath.split("/")
# Retrieve the head of the xpath for validation.
if xpath_split:
head = xpath_split[-1]
if "[" in head:
head = head.split("[")[0]
current_element = __salt__['panos.get_xpath'](xpath)['result']
if head and current_element and head in current_element:
current_element = current_element[head]
else:
current_element = {}
new_element = xml.to_dict(ET.fromstring(value), True)
if current_element == new_element:
ret.update({
'comment': 'XPATH is already equal to the specified value.',
'result': True
})
return ret
result, msg = _edit_config(xpath, value)
ret.update({
'comment': msg,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'changes': {'before': current_element, 'after': new_element},
'commit': __salt__['panos.commit'](),
'result': True
})
else:
ret.update({
'changes': {'before': current_element, 'after': new_element},
'result': True
})
return ret
def move_config(name, xpath=None, where=None, dst=None, commit=False):
'''
Moves a XPATH value to a new location.
Use the xpath parameter to specify the location of the object to be moved, the where parameter to
specify type of move, and dst parameter to specify the destination path.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to move.
where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before
options will require the dst option to specify the destination of the action. The top action will move the
XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure.
dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top
or bottom action.
commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is
not successful, it will not commit.
SLS Example:
.. code-block:: yaml
panos/moveruletop:
panos.move_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: top
- commit: True
panos/moveruleafter:
panos.move_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: after
- dst: rule2
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not where:
return ret
if where == 'after':
result, msg = _move_after(xpath, dst)
elif where == 'before':
result, msg = _move_before(xpath, dst)
elif where == 'top':
result, msg = _move_top(xpath)
elif where == 'bottom':
result, msg = _move_bottom(xpath)
ret.update({
'result': result,
'comment': msg
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def remove_config_lock(name):
'''
Release config lock previously held.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/takelock:
panos.remove_config_lock
'''
ret = _default_ret(name)
ret.update({
'changes': __salt__['panos.remove_config_lock'](),
'result': True
})
return ret
def rename_config(name, xpath=None, newname=None, commit=False):
'''
Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
newname(str): The new name of the XPATH value.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/renamegroup:
panos.rename_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address']
- value: new_address
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not newname:
return ret
query = {'type': 'config',
'action': 'rename',
'xpath': xpath,
'newname': newname}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False):
'''
Ensures that a service object exists in the configured state. If it does not exist or is not configured with the
specified attributes, it will be adjusted to match the specified values.
name: The name of the module function to execute.
servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp.
port(str): The port number that is used by the service object. This can be specified as a single integer or a
valid range of ports.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service/tcp-80:
panos.service_exists:
- servicename: tcp-80
- vsys: 1
- protocol: tcp
- port: 80
- description: Hypertext Transfer Protocol
- commit: False
panos/service/udp-500-550:
panos.service_exists:
- servicename: udp-500-550
- vsys: 3
- protocol: udp
- port: 500-550
- commit: False
'''
ret = _default_ret(name)
if not servicename:
ret.update({'comment': "The service name field must be provided."})
return ret
# Check if service object currently exists
service = __salt__['panos.get_service'](servicename, vsys)['result']
if service and 'entry' in service:
service = service['entry']
else:
service = {}
# Verify the arguments
if not protocol and protocol not in ['tcp', 'udp']:
ret.update({'comment': "The protocol must be provided and must be tcp or udp."})
return ret
if not port:
ret.update({'comment': "The port field must be provided."})
return ret
element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port)
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element)
new_service = xml.to_dict(ET.fromstring(full_element), True)
if service == new_service:
ret.update({
'comment': 'Service object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \
"entry[@name=\'{1}\']".format(vsys, servicename)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': service, 'after': new_service},
'commit': __salt__['panos.commit'](),
'comment': 'Service object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': service, 'after': new_service},
'comment': 'Service object successfully configured.',
'result': True
})
return ret
def service_group_exists(name,
groupname=None,
vsys=1,
members=None,
description=None,
commit=False):
'''
Ensures that a service group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the service group. These must be valid service objects or service groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service-group/my-group:
panos.service_group_exists:
- groupname: my-group
- vsys: 1
- members:
- tcp-80
- custom-port-group
- description: A group that needs to exist
- commit: False
'''
ret = _default_ret(name)
if not groupname:
ret.update({'comment': "The group name field must be provided."})
return ret
# Check if service group object currently exists
group = __salt__['panos.get_service_group'](groupname, vsys)['result']
if group and 'entry' in group:
group = group['entry']
else:
group = {}
# Verify the arguments
if members:
element = "<members>{0}</members>".format(_build_members(members, True))
else:
ret.update({'comment': "The group members must be provided."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element)
new_group = xml.to_dict(ET.fromstring(full_element), True)
if group == new_group:
ret.update({
'comment': 'Service group object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \
"entry[@name=\'{1}\']".format(vsys, groupname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': group, 'after': new_group},
'commit': __salt__['panos.commit'](),
'comment': 'Service group object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': group, 'after': new_group},
'comment': 'Service group object successfully configured.',
'result': True
})
return ret
def set_config(name, xpath=None, value=None, commit=False):
'''
Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not
changed.
You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter
to specify the location of the object in the configuration
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
value(str): The XML value to set. This must be a child to the XPATH.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/hostname:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system
- value: <hostname>foobar</hostname>
- commit: True
'''
ret = _default_ret(name)
result, msg = _set_config(xpath, value)
ret.update({
'comment': msg,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
|
saltstack/salt
|
salt/states/panos.py
|
service_exists
|
python
|
def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False):
'''
Ensures that a service object exists in the configured state. If it does not exist or is not configured with the
specified attributes, it will be adjusted to match the specified values.
name: The name of the module function to execute.
servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp.
port(str): The port number that is used by the service object. This can be specified as a single integer or a
valid range of ports.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service/tcp-80:
panos.service_exists:
- servicename: tcp-80
- vsys: 1
- protocol: tcp
- port: 80
- description: Hypertext Transfer Protocol
- commit: False
panos/service/udp-500-550:
panos.service_exists:
- servicename: udp-500-550
- vsys: 3
- protocol: udp
- port: 500-550
- commit: False
'''
ret = _default_ret(name)
if not servicename:
ret.update({'comment': "The service name field must be provided."})
return ret
# Check if service object currently exists
service = __salt__['panos.get_service'](servicename, vsys)['result']
if service and 'entry' in service:
service = service['entry']
else:
service = {}
# Verify the arguments
if not protocol and protocol not in ['tcp', 'udp']:
ret.update({'comment': "The protocol must be provided and must be tcp or udp."})
return ret
if not port:
ret.update({'comment': "The port field must be provided."})
return ret
element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port)
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element)
new_service = xml.to_dict(ET.fromstring(full_element), True)
if service == new_service:
ret.update({
'comment': 'Service object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \
"entry[@name=\'{1}\']".format(vsys, servicename)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': service, 'after': new_service},
'commit': __salt__['panos.commit'](),
'comment': 'Service object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': service, 'after': new_service},
'comment': 'Service object successfully configured.',
'result': True
})
return ret
|
Ensures that a service object exists in the configured state. If it does not exist or is not configured with the
specified attributes, it will be adjusted to match the specified values.
name: The name of the module function to execute.
servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp.
port(str): The port number that is used by the service object. This can be specified as a single integer or a
valid range of ports.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service/tcp-80:
panos.service_exists:
- servicename: tcp-80
- vsys: 1
- protocol: tcp
- port: 80
- description: Hypertext Transfer Protocol
- commit: False
panos/service/udp-500-550:
panos.service_exists:
- servicename: udp-500-550
- vsys: 3
- protocol: udp
- port: 500-550
- commit: False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L1331-L1438
|
[
"def to_dict(xmltree, attr=False):\n '''\n Convert an XML tree into a dict. The tree that is passed in must be an\n ElementTree object.\n Args:\n xmltree: An ElementTree object.\n attr: If true, attributes will be parsed. If false, they will be ignored.\n\n '''\n if attr:\n return _to_full_dict(xmltree)\n else:\n return _to_dict(xmltree)\n",
"def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n",
"def _edit_config(xpath, element):\n '''\n Sends an edit request to the device.\n\n '''\n query = {'type': 'config',\n 'action': 'edit',\n 'xpath': xpath,\n 'element': element}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n"
] |
# -*- coding: utf-8 -*-
'''
A state module to manage Palo Alto network devices.
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
About
=====
This state module was designed to handle connections to a Palo Alto based
firewall. This module relies on the Palo Alto proxy module to interface with the devices.
This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It
exposes the core XML API commands and allows state modules to chain complex XPATH commands.
Below is an example of how to construct a security rule and move to the top of the policy. This will take a config
lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will
commit to the device.
.. code-block:: yaml
panos/takelock:
panos.add_config_lock
panos/service_tcp_22:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service
- value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry>
- commit: False
panos/create_rule1:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules
- value: '
<entry name="rule1">
<from><member>trust</member></from>
<to><member>untrust</member></to>
<source><member>10.0.0.1</member></source>
<destination><member>10.0.1.1</member></destination>
<service><member>tcp-22</member></service>
<application><member>any</member></application>
<action>allow</action>
<disabled>no</disabled>
</entry>'
- commit: False
panos/moveruletop:
panos.move_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: top
- commit: False
panos/removelock:
panos.remove_config_lock
panos/commit:
panos.commit
Version Specific Configurations
===============================
Palo Alto devices running different versions will have different supported features and different command structures. In
order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision
level.
The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or
greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and
8.0.0.
.. code-block:: jinja
{% if proxy['panos.is_required_version']('8.0.0') %}
panos/deviceconfig/system/motd-and-banner:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner
- value: |
<banner-header>BANNER TEXT</banner-header>
<banner-header-color>color2</banner-header-color>
<banner-header-text-color>color18</banner-header-text-color>
<banner-header-footer-match>yes</banner-header-footer-match>
- commit: False
{% endif %}
.. seealso::
:py:mod:`Palo Alto Proxy Module <salt.proxy.panos>`
'''
# Import Python Libs
from __future__ import absolute_import
import logging
# Import salt libs
import salt.utils.xmlutil as xml
from salt._compat import ElementTree as ET
log = logging.getLogger(__name__)
def __virtual__():
return 'panos.commit' in __salt__
def _build_members(members, anycheck=False):
'''
Builds a member formatted string for XML operation.
'''
if isinstance(members, list):
# This check will strip down members to a single any statement
if anycheck and 'any' in members:
return "<member>any</member>"
response = ""
for m in members:
response += "<member>{0}</member>".format(m)
return response
else:
return "<member>{0}</member>".format(members)
def _default_ret(name):
'''
Set the default response values.
'''
ret = {
'name': name,
'changes': {},
'commit': None,
'result': False,
'comment': ''
}
return ret
def _edit_config(xpath, element):
'''
Sends an edit request to the device.
'''
query = {'type': 'config',
'action': 'edit',
'xpath': xpath,
'element': element}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _get_config(xpath):
'''
Retrieves an xpath from the device.
'''
query = {'type': 'config',
'action': 'get',
'xpath': xpath}
response = __proxy__['panos.call'](query)
return response
def _move_after(xpath, target):
'''
Moves an xpath to the after of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'after',
'dst': target}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_before(xpath, target):
'''
Moves an xpath to the bottom of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'before',
'dst': target}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_bottom(xpath):
'''
Moves an xpath to the bottom of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'bottom'}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_top(xpath):
'''
Moves an xpath to the top of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'top'}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _set_config(xpath, element):
'''
Sends a set request to the device.
'''
query = {'type': 'config',
'action': 'set',
'xpath': xpath,
'element': element}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _validate_response(response):
'''
Validates a response from a Palo Alto device. Used to verify success of commands.
'''
if not response:
return False, 'Unable to validate response from device.'
elif 'msg' in response:
if 'line' in response['msg']:
if response['msg']['line'] == 'already at the top':
return True, response
elif response['msg']['line'] == 'already at the bottom':
return True, response
else:
return False, response
elif response['msg'] == 'command succeeded':
return True, response
else:
return False, response
elif 'status' in response:
if response['status'] == "success":
return True, response
else:
return False, response
else:
return False, response
def add_config_lock(name):
'''
Prevent other users from changing configuration until the lock is released.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/takelock:
panos.add_config_lock
'''
ret = _default_ret(name)
ret.update({
'changes': __salt__['panos.add_config_lock'](),
'result': True
})
return ret
def address_exists(name,
addressname=None,
vsys=1,
ipnetmask=None,
iprange=None,
fqdn=None,
description=None,
commit=False):
'''
Ensures that an address object exists in the configured state. If it does not exist or is not configured with the
specified attributes, it will be adjusted to match the specified values.
This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified
value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address
type.
name: The name of the module function to execute.
addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where
the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6,
you specify only the network portion, not the host portion.
iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both
can be IPv6.
fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are
subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the
entries are picked up at the refresh cycle.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/address/h-10.10.10.10:
panos.address_exists:
- addressname: h-10.10.10.10
- vsys: 1
- ipnetmask: 10.10.10.10
- commit: False
panos/address/10.0.0.1-10.0.0.50:
panos.address_exists:
- addressname: r-10.0.0.1-10.0.0.50
- vsys: 1
- iprange: 10.0.0.1-10.0.0.50
- commit: False
panos/address/foo.bar.com:
panos.address_exists:
- addressname: foo.bar.com
- vsys: 1
- fqdn: foo.bar.com
- description: My fqdn object
- commit: False
'''
ret = _default_ret(name)
if not addressname:
ret.update({'comment': "The service name field must be provided."})
return ret
# Check if address object currently exists
address = __salt__['panos.get_address'](addressname, vsys)['result']
if address and 'entry' in address:
address = address['entry']
else:
address = {}
element = ""
# Verify the arguments
if ipnetmask:
element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask)
elif iprange:
element = "<ip-range>{0}</ip-range>".format(iprange)
elif fqdn:
element = "<fqdn>{0}</fqdn>".format(fqdn)
else:
ret.update({'comment': "A valid address type must be specified."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element)
new_address = xml.to_dict(ET.fromstring(full_element), True)
if address == new_address:
ret.update({
'comment': 'Address object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \
"entry[@name=\'{1}\']".format(vsys, addressname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': address, 'after': new_address},
'commit': __salt__['panos.commit'](),
'comment': 'Address object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': address, 'after': new_address},
'comment': 'Service object successfully configured.',
'result': True
})
return ret
def address_group_exists(name,
groupname=None,
vsys=1,
members=None,
description=None,
commit=False):
'''
Ensures that an address group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the address group. These must be valid address objects or address groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/address-group/my-group:
panos.address_group_exists:
- groupname: my-group
- vsys: 1
- members:
- my-address-object
- my-other-address-group
- description: A group that needs to exist
- commit: False
'''
ret = _default_ret(name)
if not groupname:
ret.update({'comment': "The group name field must be provided."})
return ret
# Check if address group object currently exists
group = __salt__['panos.get_address_group'](groupname, vsys)['result']
if group and 'entry' in group:
group = group['entry']
else:
group = {}
# Verify the arguments
if members:
element = "<static>{0}</static>".format(_build_members(members, True))
else:
ret.update({'comment': "The group members must be provided."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element)
new_group = xml.to_dict(ET.fromstring(full_element), True)
if group == new_group:
ret.update({
'comment': 'Address group object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \
"entry[@name=\'{1}\']".format(vsys, groupname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': group, 'after': new_group},
'commit': __salt__['panos.commit'](),
'comment': 'Address group object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': group, 'after': new_group},
'comment': 'Address group object successfully configured.',
'result': True
})
return ret
def clone_config(name, xpath=None, newname=None, commit=False):
'''
Clone a specific XPATH and set it to a new name.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to clone.
newname(str): The new name of the XPATH clone.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/clonerule:
panos.clone_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/
entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- value: rule2
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not newname:
return ret
query = {'type': 'config',
'action': 'clone',
'xpath': xpath,
'newname': newname}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def commit_config(name):
'''
Commits the candidate configuration to the running configuration.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/commit:
panos.commit_config
'''
ret = _default_ret(name)
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def delete_config(name, xpath=None, commit=False):
'''
Deletes a Palo Alto XPATH to a specific value.
Use the xpath parameter to specify the location of the object to be deleted.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/deletegroup:
panos.delete_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test']
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
query = {'type': 'config',
'action': 'delete',
'xpath': xpath}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def download_software(name, version=None, synch=False, check=False):
'''
Ensures that a software version is downloaded.
name: The name of the module function to execute.
version(str): The software version to check. If this version is not already downloaded, it will attempt to download
the file from Palo Alto.
synch(bool): If true, after downloading the file it will be synched to its peer.
check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo
Alto.
SLS Example:
.. code-block:: yaml
panos/version8.0.0:
panos.download_software:
- version: 8.0.0
- synch: False
- check: True
'''
ret = _default_ret(name)
if check is True:
__salt__['panos.check_software']()
versions = __salt__['panos.get_software_info']()['result']
if 'sw-updates' not in versions \
or 'versions' not in versions['sw-updates'] \
or 'entry' not in versions['sw-updates']['versions']:
ret.update({
'comment': 'Software version is not found in the local software list.',
'result': False
})
return ret
for entry in versions['sw-updates']['versions']['entry']:
if entry['version'] == version and entry['downloaded'] == "yes":
ret.update({
'comment': 'Software version is already downloaded.',
'result': True
})
return ret
ret.update({
'changes': __salt__['panos.download_software_version'](version=version, synch=synch)
})
versions = __salt__['panos.get_software_info']()['result']
if 'sw-updates' not in versions \
or 'versions' not in versions['sw-updates'] \
or 'entry' not in versions['sw-updates']['versions']:
ret.update({
'result': False
})
return ret
for entry in versions['sw-updates']['versions']['entry']:
if entry['version'] == version and entry['downloaded'] == "yes":
ret.update({
'result': True
})
return ret
return ret
def edit_config(name, xpath=None, value=None, commit=False):
'''
Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not
changed.
You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use
the xpath parameter to specify the location of the object, including the node to be replaced.
This is the recommended state to enforce configurations on a xpath.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
value(str): The XML value to edit. This must be a child to the XPATH.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/addressgroup:
panos.edit_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test']
- value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static>
- commit: True
'''
ret = _default_ret(name)
# Verify if the current XPATH is equal to the specified value.
# If we are equal, no changes required.
xpath_split = xpath.split("/")
# Retrieve the head of the xpath for validation.
if xpath_split:
head = xpath_split[-1]
if "[" in head:
head = head.split("[")[0]
current_element = __salt__['panos.get_xpath'](xpath)['result']
if head and current_element and head in current_element:
current_element = current_element[head]
else:
current_element = {}
new_element = xml.to_dict(ET.fromstring(value), True)
if current_element == new_element:
ret.update({
'comment': 'XPATH is already equal to the specified value.',
'result': True
})
return ret
result, msg = _edit_config(xpath, value)
ret.update({
'comment': msg,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'changes': {'before': current_element, 'after': new_element},
'commit': __salt__['panos.commit'](),
'result': True
})
else:
ret.update({
'changes': {'before': current_element, 'after': new_element},
'result': True
})
return ret
def move_config(name, xpath=None, where=None, dst=None, commit=False):
'''
Moves a XPATH value to a new location.
Use the xpath parameter to specify the location of the object to be moved, the where parameter to
specify type of move, and dst parameter to specify the destination path.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to move.
where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before
options will require the dst option to specify the destination of the action. The top action will move the
XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure.
dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top
or bottom action.
commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is
not successful, it will not commit.
SLS Example:
.. code-block:: yaml
panos/moveruletop:
panos.move_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: top
- commit: True
panos/moveruleafter:
panos.move_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: after
- dst: rule2
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not where:
return ret
if where == 'after':
result, msg = _move_after(xpath, dst)
elif where == 'before':
result, msg = _move_before(xpath, dst)
elif where == 'top':
result, msg = _move_top(xpath)
elif where == 'bottom':
result, msg = _move_bottom(xpath)
ret.update({
'result': result,
'comment': msg
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def remove_config_lock(name):
'''
Release config lock previously held.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/takelock:
panos.remove_config_lock
'''
ret = _default_ret(name)
ret.update({
'changes': __salt__['panos.remove_config_lock'](),
'result': True
})
return ret
def rename_config(name, xpath=None, newname=None, commit=False):
'''
Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
newname(str): The new name of the XPATH value.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/renamegroup:
panos.rename_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address']
- value: new_address
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not newname:
return ret
query = {'type': 'config',
'action': 'rename',
'xpath': xpath,
'newname': newname}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def security_rule_exists(name,
rulename=None,
vsys='1',
action=None,
disabled=None,
sourcezone=None,
destinationzone=None,
source=None,
destination=None,
application=None,
service=None,
description=None,
logsetting=None,
logstart=None,
logend=None,
negatesource=None,
negatedestination=None,
profilegroup=None,
datafilter=None,
fileblock=None,
spyware=None,
urlfilter=None,
virus=None,
vulnerability=None,
wildfire=None,
move=None,
movetarget=None,
commit=False):
'''
Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately.
This method will create the rule if it does not exist. If the rule does exist, it will ensure that the
configurations are set appropriately.
If the rule does not exist and is created, any value that is not provided will be provided as the default.
The action, to, from, source, destination, application, and service fields are mandatory and must be provided.
This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end
option, but this option is not specified in the state method, it will be removed and reset to the system default.
It is strongly recommended to specify all options to ensure proper operation.
When defining the profile group settings, the device can only support either a profile group or individual settings.
If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are
specified, the value will be set to system default of none.
name: The name of the module function to execute.
rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which
can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama,
unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client,
reset-server, reset-both.
disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable.
sourcezone(str, list): The source zone(s). The value 'any' will match all zones.
destinationzone(str, list): The destination zone(s). The value 'any' will match all zones.
source(str, list): The source address(es). The value 'any' will match all addresses.
destination(str, list): The destination address(es). The value 'any' will match all addresses.
application(str, list): The application(s) matched. The value 'any' will match all applications.
service(str, list): The service(s) matched. The value 'any' will match all services. The value
'application-default' will match based upon the application defined ports.
description(str): A description for the policy (up to 255 characters).
logsetting(str): The name of a valid log forwarding profile.
logstart(bool): Generates a traffic log entry for the start of a session (disabled by default).
logend(bool): Generates a traffic log entry for the end of a session (enabled by default).
negatesource(bool): Match all but the specified source addresses.
negatedestination(bool): Match all but the specified destination addresses.
profilegroup(str): A valid profile group name.
datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set.
fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set.
spyware(str): A valid spyware profile name. Ignored with the profilegroup option set.
urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set.
virus(str): A valid virus profile name. Ignored with the profilegroup option set.
vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top',
'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument
to define the location of the move request.
movetarget(str): An optional argument that defines the target of the move operation if the move argument is
set to 'before' or 'after'.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: True
- negatesource: False
- negatedestination: False
- profilegroup: myprofilegroup
- move: top
- commit: False
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: False
- datafilter: foobar
- fileblock: foobar
- spyware: foobar
- urlfilter: foobar
- virus: foobar
- vulnerability: foobar
- wildfire: foobar
- move: after
- movetarget: rule02
- commit: False
'''
ret = _default_ret(name)
if not rulename:
return ret
# Check if rule currently exists
rule = __salt__['panos.get_security_rule'](rulename, vsys)['result']
if rule and 'entry' in rule:
rule = rule['entry']
else:
rule = {}
# Build the rule element
element = ""
if sourcezone:
element += "<from>{0}</from>".format(_build_members(sourcezone, True))
else:
ret.update({'comment': "The sourcezone field must be provided."})
return ret
if destinationzone:
element += "<to>{0}</to>".format(_build_members(destinationzone, True))
else:
ret.update({'comment': "The destinationzone field must be provided."})
return ret
if source:
element += "<source>{0}</source>".format(_build_members(source, True))
else:
ret.update({'comment': "The source field must be provided."})
return
if destination:
element += "<destination>{0}</destination>".format(_build_members(destination, True))
else:
ret.update({'comment': "The destination field must be provided."})
return ret
if application:
element += "<application>{0}</application>".format(_build_members(application, True))
else:
ret.update({'comment': "The application field must be provided."})
return ret
if service:
element += "<service>{0}</service>".format(_build_members(service, True))
else:
ret.update({'comment': "The service field must be provided."})
return ret
if action:
element += "<action>{0}</action>".format(action)
else:
ret.update({'comment': "The action field must be provided."})
return ret
if disabled is not None:
if disabled:
element += "<disabled>yes</disabled>"
else:
element += "<disabled>no</disabled>"
if description:
element += "<description>{0}</description>".format(description)
if logsetting:
element += "<log-setting>{0}</log-setting>".format(logsetting)
if logstart is not None:
if logstart:
element += "<log-start>yes</log-start>"
else:
element += "<log-start>no</log-start>"
if logend is not None:
if logend:
element += "<log-end>yes</log-end>"
else:
element += "<log-end>no</log-end>"
if negatesource is not None:
if negatesource:
element += "<negate-source>yes</negate-source>"
else:
element += "<negate-source>no</negate-source>"
if negatedestination is not None:
if negatedestination:
element += "<negate-destination>yes</negate-destination>"
else:
element += "<negate-destination>no</negate-destination>"
# Build the profile settings
profile_string = None
if profilegroup:
profile_string = "<group><member>{0}</member></group>".format(profilegroup)
else:
member_string = ""
if datafilter:
member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter)
if fileblock:
member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock)
if spyware:
member_string += "<spyware><member>{0}</member></spyware>".format(spyware)
if urlfilter:
member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter)
if virus:
member_string += "<virus><member>{0}</member></virus>".format(virus)
if vulnerability:
member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability)
if wildfire:
member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire)
if member_string != "":
profile_string = "<profiles>{0}</profiles>".format(member_string)
if profile_string:
element += "<profile-setting>{0}</profile-setting>".format(profile_string)
full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element)
new_rule = xml.to_dict(ET.fromstring(full_element), True)
config_change = False
if rule == new_rule:
ret.update({
'comment': 'Security rule already exists. No changes required.'
})
else:
config_change = True
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \
"security/rules/entry[@name=\'{1}\']".format(vsys, rulename)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
ret.update({
'changes': {'before': rule, 'after': new_rule},
'comment': 'Security rule verified successfully.'
})
if move:
movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \
"security/rules/entry[@name=\'{1}\']".format(vsys, rulename)
move_result = False
move_msg = ''
if move == "before" and movetarget:
move_result, move_msg = _move_before(movepath, movetarget)
elif move == "after":
move_result, move_msg = _move_after(movepath, movetarget)
elif move == "top":
move_result, move_msg = _move_top(movepath)
elif move == "bottom":
move_result, move_msg = _move_bottom(movepath)
if config_change:
ret.update({
'changes': {'before': rule, 'after': new_rule, 'move': move_msg}
})
else:
ret.update({
'changes': {'move': move_msg}
})
if not move_result:
ret.update({
'comment': move_msg
})
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
else:
ret.update({
'result': True
})
return ret
def service_group_exists(name,
groupname=None,
vsys=1,
members=None,
description=None,
commit=False):
'''
Ensures that a service group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the service group. These must be valid service objects or service groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service-group/my-group:
panos.service_group_exists:
- groupname: my-group
- vsys: 1
- members:
- tcp-80
- custom-port-group
- description: A group that needs to exist
- commit: False
'''
ret = _default_ret(name)
if not groupname:
ret.update({'comment': "The group name field must be provided."})
return ret
# Check if service group object currently exists
group = __salt__['panos.get_service_group'](groupname, vsys)['result']
if group and 'entry' in group:
group = group['entry']
else:
group = {}
# Verify the arguments
if members:
element = "<members>{0}</members>".format(_build_members(members, True))
else:
ret.update({'comment': "The group members must be provided."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element)
new_group = xml.to_dict(ET.fromstring(full_element), True)
if group == new_group:
ret.update({
'comment': 'Service group object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \
"entry[@name=\'{1}\']".format(vsys, groupname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': group, 'after': new_group},
'commit': __salt__['panos.commit'](),
'comment': 'Service group object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': group, 'after': new_group},
'comment': 'Service group object successfully configured.',
'result': True
})
return ret
def set_config(name, xpath=None, value=None, commit=False):
'''
Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not
changed.
You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter
to specify the location of the object in the configuration
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
value(str): The XML value to set. This must be a child to the XPATH.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/hostname:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system
- value: <hostname>foobar</hostname>
- commit: True
'''
ret = _default_ret(name)
result, msg = _set_config(xpath, value)
ret.update({
'comment': msg,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
|
saltstack/salt
|
salt/states/panos.py
|
service_group_exists
|
python
|
def service_group_exists(name,
groupname=None,
vsys=1,
members=None,
description=None,
commit=False):
'''
Ensures that a service group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the service group. These must be valid service objects or service groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service-group/my-group:
panos.service_group_exists:
- groupname: my-group
- vsys: 1
- members:
- tcp-80
- custom-port-group
- description: A group that needs to exist
- commit: False
'''
ret = _default_ret(name)
if not groupname:
ret.update({'comment': "The group name field must be provided."})
return ret
# Check if service group object currently exists
group = __salt__['panos.get_service_group'](groupname, vsys)['result']
if group and 'entry' in group:
group = group['entry']
else:
group = {}
# Verify the arguments
if members:
element = "<members>{0}</members>".format(_build_members(members, True))
else:
ret.update({'comment': "The group members must be provided."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element)
new_group = xml.to_dict(ET.fromstring(full_element), True)
if group == new_group:
ret.update({
'comment': 'Service group object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \
"entry[@name=\'{1}\']".format(vsys, groupname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': group, 'after': new_group},
'commit': __salt__['panos.commit'](),
'comment': 'Service group object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': group, 'after': new_group},
'comment': 'Service group object successfully configured.',
'result': True
})
return ret
|
Ensures that a service group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the service group. These must be valid service objects or service groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service-group/my-group:
panos.service_group_exists:
- groupname: my-group
- vsys: 1
- members:
- tcp-80
- custom-port-group
- description: A group that needs to exist
- commit: False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L1441-L1544
|
[
"def to_dict(xmltree, attr=False):\n '''\n Convert an XML tree into a dict. The tree that is passed in must be an\n ElementTree object.\n Args:\n xmltree: An ElementTree object.\n attr: If true, attributes will be parsed. If false, they will be ignored.\n\n '''\n if attr:\n return _to_full_dict(xmltree)\n else:\n return _to_dict(xmltree)\n",
"def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n",
"def _build_members(members, anycheck=False):\n '''\n Builds a member formatted string for XML operation.\n\n '''\n if isinstance(members, list):\n\n # This check will strip down members to a single any statement\n if anycheck and 'any' in members:\n return \"<member>any</member>\"\n response = \"\"\n for m in members:\n response += \"<member>{0}</member>\".format(m)\n return response\n else:\n return \"<member>{0}</member>\".format(members)\n",
"def _edit_config(xpath, element):\n '''\n Sends an edit request to the device.\n\n '''\n query = {'type': 'config',\n 'action': 'edit',\n 'xpath': xpath,\n 'element': element}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n"
] |
# -*- coding: utf-8 -*-
'''
A state module to manage Palo Alto network devices.
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
About
=====
This state module was designed to handle connections to a Palo Alto based
firewall. This module relies on the Palo Alto proxy module to interface with the devices.
This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It
exposes the core XML API commands and allows state modules to chain complex XPATH commands.
Below is an example of how to construct a security rule and move to the top of the policy. This will take a config
lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will
commit to the device.
.. code-block:: yaml
panos/takelock:
panos.add_config_lock
panos/service_tcp_22:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service
- value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry>
- commit: False
panos/create_rule1:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules
- value: '
<entry name="rule1">
<from><member>trust</member></from>
<to><member>untrust</member></to>
<source><member>10.0.0.1</member></source>
<destination><member>10.0.1.1</member></destination>
<service><member>tcp-22</member></service>
<application><member>any</member></application>
<action>allow</action>
<disabled>no</disabled>
</entry>'
- commit: False
panos/moveruletop:
panos.move_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: top
- commit: False
panos/removelock:
panos.remove_config_lock
panos/commit:
panos.commit
Version Specific Configurations
===============================
Palo Alto devices running different versions will have different supported features and different command structures. In
order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision
level.
The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or
greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and
8.0.0.
.. code-block:: jinja
{% if proxy['panos.is_required_version']('8.0.0') %}
panos/deviceconfig/system/motd-and-banner:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner
- value: |
<banner-header>BANNER TEXT</banner-header>
<banner-header-color>color2</banner-header-color>
<banner-header-text-color>color18</banner-header-text-color>
<banner-header-footer-match>yes</banner-header-footer-match>
- commit: False
{% endif %}
.. seealso::
:py:mod:`Palo Alto Proxy Module <salt.proxy.panos>`
'''
# Import Python Libs
from __future__ import absolute_import
import logging
# Import salt libs
import salt.utils.xmlutil as xml
from salt._compat import ElementTree as ET
log = logging.getLogger(__name__)
def __virtual__():
return 'panos.commit' in __salt__
def _build_members(members, anycheck=False):
'''
Builds a member formatted string for XML operation.
'''
if isinstance(members, list):
# This check will strip down members to a single any statement
if anycheck and 'any' in members:
return "<member>any</member>"
response = ""
for m in members:
response += "<member>{0}</member>".format(m)
return response
else:
return "<member>{0}</member>".format(members)
def _default_ret(name):
'''
Set the default response values.
'''
ret = {
'name': name,
'changes': {},
'commit': None,
'result': False,
'comment': ''
}
return ret
def _edit_config(xpath, element):
'''
Sends an edit request to the device.
'''
query = {'type': 'config',
'action': 'edit',
'xpath': xpath,
'element': element}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _get_config(xpath):
'''
Retrieves an xpath from the device.
'''
query = {'type': 'config',
'action': 'get',
'xpath': xpath}
response = __proxy__['panos.call'](query)
return response
def _move_after(xpath, target):
'''
Moves an xpath to the after of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'after',
'dst': target}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_before(xpath, target):
'''
Moves an xpath to the bottom of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'before',
'dst': target}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_bottom(xpath):
'''
Moves an xpath to the bottom of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'bottom'}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_top(xpath):
'''
Moves an xpath to the top of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'top'}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _set_config(xpath, element):
'''
Sends a set request to the device.
'''
query = {'type': 'config',
'action': 'set',
'xpath': xpath,
'element': element}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _validate_response(response):
'''
Validates a response from a Palo Alto device. Used to verify success of commands.
'''
if not response:
return False, 'Unable to validate response from device.'
elif 'msg' in response:
if 'line' in response['msg']:
if response['msg']['line'] == 'already at the top':
return True, response
elif response['msg']['line'] == 'already at the bottom':
return True, response
else:
return False, response
elif response['msg'] == 'command succeeded':
return True, response
else:
return False, response
elif 'status' in response:
if response['status'] == "success":
return True, response
else:
return False, response
else:
return False, response
def add_config_lock(name):
'''
Prevent other users from changing configuration until the lock is released.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/takelock:
panos.add_config_lock
'''
ret = _default_ret(name)
ret.update({
'changes': __salt__['panos.add_config_lock'](),
'result': True
})
return ret
def address_exists(name,
addressname=None,
vsys=1,
ipnetmask=None,
iprange=None,
fqdn=None,
description=None,
commit=False):
'''
Ensures that an address object exists in the configured state. If it does not exist or is not configured with the
specified attributes, it will be adjusted to match the specified values.
This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified
value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address
type.
name: The name of the module function to execute.
addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where
the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6,
you specify only the network portion, not the host portion.
iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both
can be IPv6.
fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are
subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the
entries are picked up at the refresh cycle.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/address/h-10.10.10.10:
panos.address_exists:
- addressname: h-10.10.10.10
- vsys: 1
- ipnetmask: 10.10.10.10
- commit: False
panos/address/10.0.0.1-10.0.0.50:
panos.address_exists:
- addressname: r-10.0.0.1-10.0.0.50
- vsys: 1
- iprange: 10.0.0.1-10.0.0.50
- commit: False
panos/address/foo.bar.com:
panos.address_exists:
- addressname: foo.bar.com
- vsys: 1
- fqdn: foo.bar.com
- description: My fqdn object
- commit: False
'''
ret = _default_ret(name)
if not addressname:
ret.update({'comment': "The service name field must be provided."})
return ret
# Check if address object currently exists
address = __salt__['panos.get_address'](addressname, vsys)['result']
if address and 'entry' in address:
address = address['entry']
else:
address = {}
element = ""
# Verify the arguments
if ipnetmask:
element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask)
elif iprange:
element = "<ip-range>{0}</ip-range>".format(iprange)
elif fqdn:
element = "<fqdn>{0}</fqdn>".format(fqdn)
else:
ret.update({'comment': "A valid address type must be specified."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element)
new_address = xml.to_dict(ET.fromstring(full_element), True)
if address == new_address:
ret.update({
'comment': 'Address object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \
"entry[@name=\'{1}\']".format(vsys, addressname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': address, 'after': new_address},
'commit': __salt__['panos.commit'](),
'comment': 'Address object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': address, 'after': new_address},
'comment': 'Service object successfully configured.',
'result': True
})
return ret
def address_group_exists(name,
groupname=None,
vsys=1,
members=None,
description=None,
commit=False):
'''
Ensures that an address group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the address group. These must be valid address objects or address groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/address-group/my-group:
panos.address_group_exists:
- groupname: my-group
- vsys: 1
- members:
- my-address-object
- my-other-address-group
- description: A group that needs to exist
- commit: False
'''
ret = _default_ret(name)
if not groupname:
ret.update({'comment': "The group name field must be provided."})
return ret
# Check if address group object currently exists
group = __salt__['panos.get_address_group'](groupname, vsys)['result']
if group and 'entry' in group:
group = group['entry']
else:
group = {}
# Verify the arguments
if members:
element = "<static>{0}</static>".format(_build_members(members, True))
else:
ret.update({'comment': "The group members must be provided."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element)
new_group = xml.to_dict(ET.fromstring(full_element), True)
if group == new_group:
ret.update({
'comment': 'Address group object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \
"entry[@name=\'{1}\']".format(vsys, groupname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': group, 'after': new_group},
'commit': __salt__['panos.commit'](),
'comment': 'Address group object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': group, 'after': new_group},
'comment': 'Address group object successfully configured.',
'result': True
})
return ret
def clone_config(name, xpath=None, newname=None, commit=False):
'''
Clone a specific XPATH and set it to a new name.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to clone.
newname(str): The new name of the XPATH clone.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/clonerule:
panos.clone_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/
entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- value: rule2
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not newname:
return ret
query = {'type': 'config',
'action': 'clone',
'xpath': xpath,
'newname': newname}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def commit_config(name):
'''
Commits the candidate configuration to the running configuration.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/commit:
panos.commit_config
'''
ret = _default_ret(name)
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def delete_config(name, xpath=None, commit=False):
'''
Deletes a Palo Alto XPATH to a specific value.
Use the xpath parameter to specify the location of the object to be deleted.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/deletegroup:
panos.delete_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test']
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
query = {'type': 'config',
'action': 'delete',
'xpath': xpath}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def download_software(name, version=None, synch=False, check=False):
'''
Ensures that a software version is downloaded.
name: The name of the module function to execute.
version(str): The software version to check. If this version is not already downloaded, it will attempt to download
the file from Palo Alto.
synch(bool): If true, after downloading the file it will be synched to its peer.
check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo
Alto.
SLS Example:
.. code-block:: yaml
panos/version8.0.0:
panos.download_software:
- version: 8.0.0
- synch: False
- check: True
'''
ret = _default_ret(name)
if check is True:
__salt__['panos.check_software']()
versions = __salt__['panos.get_software_info']()['result']
if 'sw-updates' not in versions \
or 'versions' not in versions['sw-updates'] \
or 'entry' not in versions['sw-updates']['versions']:
ret.update({
'comment': 'Software version is not found in the local software list.',
'result': False
})
return ret
for entry in versions['sw-updates']['versions']['entry']:
if entry['version'] == version and entry['downloaded'] == "yes":
ret.update({
'comment': 'Software version is already downloaded.',
'result': True
})
return ret
ret.update({
'changes': __salt__['panos.download_software_version'](version=version, synch=synch)
})
versions = __salt__['panos.get_software_info']()['result']
if 'sw-updates' not in versions \
or 'versions' not in versions['sw-updates'] \
or 'entry' not in versions['sw-updates']['versions']:
ret.update({
'result': False
})
return ret
for entry in versions['sw-updates']['versions']['entry']:
if entry['version'] == version and entry['downloaded'] == "yes":
ret.update({
'result': True
})
return ret
return ret
def edit_config(name, xpath=None, value=None, commit=False):
'''
Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not
changed.
You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use
the xpath parameter to specify the location of the object, including the node to be replaced.
This is the recommended state to enforce configurations on a xpath.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
value(str): The XML value to edit. This must be a child to the XPATH.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/addressgroup:
panos.edit_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test']
- value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static>
- commit: True
'''
ret = _default_ret(name)
# Verify if the current XPATH is equal to the specified value.
# If we are equal, no changes required.
xpath_split = xpath.split("/")
# Retrieve the head of the xpath for validation.
if xpath_split:
head = xpath_split[-1]
if "[" in head:
head = head.split("[")[0]
current_element = __salt__['panos.get_xpath'](xpath)['result']
if head and current_element and head in current_element:
current_element = current_element[head]
else:
current_element = {}
new_element = xml.to_dict(ET.fromstring(value), True)
if current_element == new_element:
ret.update({
'comment': 'XPATH is already equal to the specified value.',
'result': True
})
return ret
result, msg = _edit_config(xpath, value)
ret.update({
'comment': msg,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'changes': {'before': current_element, 'after': new_element},
'commit': __salt__['panos.commit'](),
'result': True
})
else:
ret.update({
'changes': {'before': current_element, 'after': new_element},
'result': True
})
return ret
def move_config(name, xpath=None, where=None, dst=None, commit=False):
'''
Moves a XPATH value to a new location.
Use the xpath parameter to specify the location of the object to be moved, the where parameter to
specify type of move, and dst parameter to specify the destination path.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to move.
where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before
options will require the dst option to specify the destination of the action. The top action will move the
XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure.
dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top
or bottom action.
commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is
not successful, it will not commit.
SLS Example:
.. code-block:: yaml
panos/moveruletop:
panos.move_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: top
- commit: True
panos/moveruleafter:
panos.move_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: after
- dst: rule2
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not where:
return ret
if where == 'after':
result, msg = _move_after(xpath, dst)
elif where == 'before':
result, msg = _move_before(xpath, dst)
elif where == 'top':
result, msg = _move_top(xpath)
elif where == 'bottom':
result, msg = _move_bottom(xpath)
ret.update({
'result': result,
'comment': msg
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def remove_config_lock(name):
'''
Release config lock previously held.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/takelock:
panos.remove_config_lock
'''
ret = _default_ret(name)
ret.update({
'changes': __salt__['panos.remove_config_lock'](),
'result': True
})
return ret
def rename_config(name, xpath=None, newname=None, commit=False):
'''
Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
newname(str): The new name of the XPATH value.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/renamegroup:
panos.rename_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address']
- value: new_address
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not newname:
return ret
query = {'type': 'config',
'action': 'rename',
'xpath': xpath,
'newname': newname}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def security_rule_exists(name,
rulename=None,
vsys='1',
action=None,
disabled=None,
sourcezone=None,
destinationzone=None,
source=None,
destination=None,
application=None,
service=None,
description=None,
logsetting=None,
logstart=None,
logend=None,
negatesource=None,
negatedestination=None,
profilegroup=None,
datafilter=None,
fileblock=None,
spyware=None,
urlfilter=None,
virus=None,
vulnerability=None,
wildfire=None,
move=None,
movetarget=None,
commit=False):
'''
Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately.
This method will create the rule if it does not exist. If the rule does exist, it will ensure that the
configurations are set appropriately.
If the rule does not exist and is created, any value that is not provided will be provided as the default.
The action, to, from, source, destination, application, and service fields are mandatory and must be provided.
This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end
option, but this option is not specified in the state method, it will be removed and reset to the system default.
It is strongly recommended to specify all options to ensure proper operation.
When defining the profile group settings, the device can only support either a profile group or individual settings.
If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are
specified, the value will be set to system default of none.
name: The name of the module function to execute.
rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which
can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama,
unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client,
reset-server, reset-both.
disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable.
sourcezone(str, list): The source zone(s). The value 'any' will match all zones.
destinationzone(str, list): The destination zone(s). The value 'any' will match all zones.
source(str, list): The source address(es). The value 'any' will match all addresses.
destination(str, list): The destination address(es). The value 'any' will match all addresses.
application(str, list): The application(s) matched. The value 'any' will match all applications.
service(str, list): The service(s) matched. The value 'any' will match all services. The value
'application-default' will match based upon the application defined ports.
description(str): A description for the policy (up to 255 characters).
logsetting(str): The name of a valid log forwarding profile.
logstart(bool): Generates a traffic log entry for the start of a session (disabled by default).
logend(bool): Generates a traffic log entry for the end of a session (enabled by default).
negatesource(bool): Match all but the specified source addresses.
negatedestination(bool): Match all but the specified destination addresses.
profilegroup(str): A valid profile group name.
datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set.
fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set.
spyware(str): A valid spyware profile name. Ignored with the profilegroup option set.
urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set.
virus(str): A valid virus profile name. Ignored with the profilegroup option set.
vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top',
'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument
to define the location of the move request.
movetarget(str): An optional argument that defines the target of the move operation if the move argument is
set to 'before' or 'after'.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: True
- negatesource: False
- negatedestination: False
- profilegroup: myprofilegroup
- move: top
- commit: False
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: False
- datafilter: foobar
- fileblock: foobar
- spyware: foobar
- urlfilter: foobar
- virus: foobar
- vulnerability: foobar
- wildfire: foobar
- move: after
- movetarget: rule02
- commit: False
'''
ret = _default_ret(name)
if not rulename:
return ret
# Check if rule currently exists
rule = __salt__['panos.get_security_rule'](rulename, vsys)['result']
if rule and 'entry' in rule:
rule = rule['entry']
else:
rule = {}
# Build the rule element
element = ""
if sourcezone:
element += "<from>{0}</from>".format(_build_members(sourcezone, True))
else:
ret.update({'comment': "The sourcezone field must be provided."})
return ret
if destinationzone:
element += "<to>{0}</to>".format(_build_members(destinationzone, True))
else:
ret.update({'comment': "The destinationzone field must be provided."})
return ret
if source:
element += "<source>{0}</source>".format(_build_members(source, True))
else:
ret.update({'comment': "The source field must be provided."})
return
if destination:
element += "<destination>{0}</destination>".format(_build_members(destination, True))
else:
ret.update({'comment': "The destination field must be provided."})
return ret
if application:
element += "<application>{0}</application>".format(_build_members(application, True))
else:
ret.update({'comment': "The application field must be provided."})
return ret
if service:
element += "<service>{0}</service>".format(_build_members(service, True))
else:
ret.update({'comment': "The service field must be provided."})
return ret
if action:
element += "<action>{0}</action>".format(action)
else:
ret.update({'comment': "The action field must be provided."})
return ret
if disabled is not None:
if disabled:
element += "<disabled>yes</disabled>"
else:
element += "<disabled>no</disabled>"
if description:
element += "<description>{0}</description>".format(description)
if logsetting:
element += "<log-setting>{0}</log-setting>".format(logsetting)
if logstart is not None:
if logstart:
element += "<log-start>yes</log-start>"
else:
element += "<log-start>no</log-start>"
if logend is not None:
if logend:
element += "<log-end>yes</log-end>"
else:
element += "<log-end>no</log-end>"
if negatesource is not None:
if negatesource:
element += "<negate-source>yes</negate-source>"
else:
element += "<negate-source>no</negate-source>"
if negatedestination is not None:
if negatedestination:
element += "<negate-destination>yes</negate-destination>"
else:
element += "<negate-destination>no</negate-destination>"
# Build the profile settings
profile_string = None
if profilegroup:
profile_string = "<group><member>{0}</member></group>".format(profilegroup)
else:
member_string = ""
if datafilter:
member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter)
if fileblock:
member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock)
if spyware:
member_string += "<spyware><member>{0}</member></spyware>".format(spyware)
if urlfilter:
member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter)
if virus:
member_string += "<virus><member>{0}</member></virus>".format(virus)
if vulnerability:
member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability)
if wildfire:
member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire)
if member_string != "":
profile_string = "<profiles>{0}</profiles>".format(member_string)
if profile_string:
element += "<profile-setting>{0}</profile-setting>".format(profile_string)
full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element)
new_rule = xml.to_dict(ET.fromstring(full_element), True)
config_change = False
if rule == new_rule:
ret.update({
'comment': 'Security rule already exists. No changes required.'
})
else:
config_change = True
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \
"security/rules/entry[@name=\'{1}\']".format(vsys, rulename)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
ret.update({
'changes': {'before': rule, 'after': new_rule},
'comment': 'Security rule verified successfully.'
})
if move:
movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \
"security/rules/entry[@name=\'{1}\']".format(vsys, rulename)
move_result = False
move_msg = ''
if move == "before" and movetarget:
move_result, move_msg = _move_before(movepath, movetarget)
elif move == "after":
move_result, move_msg = _move_after(movepath, movetarget)
elif move == "top":
move_result, move_msg = _move_top(movepath)
elif move == "bottom":
move_result, move_msg = _move_bottom(movepath)
if config_change:
ret.update({
'changes': {'before': rule, 'after': new_rule, 'move': move_msg}
})
else:
ret.update({
'changes': {'move': move_msg}
})
if not move_result:
ret.update({
'comment': move_msg
})
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
else:
ret.update({
'result': True
})
return ret
def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False):
'''
Ensures that a service object exists in the configured state. If it does not exist or is not configured with the
specified attributes, it will be adjusted to match the specified values.
name: The name of the module function to execute.
servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp.
port(str): The port number that is used by the service object. This can be specified as a single integer or a
valid range of ports.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service/tcp-80:
panos.service_exists:
- servicename: tcp-80
- vsys: 1
- protocol: tcp
- port: 80
- description: Hypertext Transfer Protocol
- commit: False
panos/service/udp-500-550:
panos.service_exists:
- servicename: udp-500-550
- vsys: 3
- protocol: udp
- port: 500-550
- commit: False
'''
ret = _default_ret(name)
if not servicename:
ret.update({'comment': "The service name field must be provided."})
return ret
# Check if service object currently exists
service = __salt__['panos.get_service'](servicename, vsys)['result']
if service and 'entry' in service:
service = service['entry']
else:
service = {}
# Verify the arguments
if not protocol and protocol not in ['tcp', 'udp']:
ret.update({'comment': "The protocol must be provided and must be tcp or udp."})
return ret
if not port:
ret.update({'comment': "The port field must be provided."})
return ret
element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port)
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element)
new_service = xml.to_dict(ET.fromstring(full_element), True)
if service == new_service:
ret.update({
'comment': 'Service object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \
"entry[@name=\'{1}\']".format(vsys, servicename)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': service, 'after': new_service},
'commit': __salt__['panos.commit'](),
'comment': 'Service object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': service, 'after': new_service},
'comment': 'Service object successfully configured.',
'result': True
})
return ret
def set_config(name, xpath=None, value=None, commit=False):
'''
Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not
changed.
You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter
to specify the location of the object in the configuration
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
value(str): The XML value to set. This must be a child to the XPATH.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/hostname:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system
- value: <hostname>foobar</hostname>
- commit: True
'''
ret = _default_ret(name)
result, msg = _set_config(xpath, value)
ret.update({
'comment': msg,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
|
saltstack/salt
|
salt/states/panos.py
|
set_config
|
python
|
def set_config(name, xpath=None, value=None, commit=False):
'''
Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not
changed.
You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter
to specify the location of the object in the configuration
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
value(str): The XML value to set. This must be a child to the XPATH.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/hostname:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system
- value: <hostname>foobar</hostname>
- commit: True
'''
ret = _default_ret(name)
result, msg = _set_config(xpath, value)
ret.update({
'comment': msg,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
|
Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not
changed.
You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter
to specify the location of the object in the configuration
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
value(str): The XML value to set. This must be a child to the XPATH.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/hostname:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system
- value: <hostname>foobar</hostname>
- commit: True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L1547-L1592
|
[
"def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n",
"def _set_config(xpath, element):\n '''\n Sends a set request to the device.\n\n '''\n query = {'type': 'config',\n 'action': 'set',\n 'xpath': xpath,\n 'element': element}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n"
] |
# -*- coding: utf-8 -*-
'''
A state module to manage Palo Alto network devices.
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
About
=====
This state module was designed to handle connections to a Palo Alto based
firewall. This module relies on the Palo Alto proxy module to interface with the devices.
This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It
exposes the core XML API commands and allows state modules to chain complex XPATH commands.
Below is an example of how to construct a security rule and move to the top of the policy. This will take a config
lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will
commit to the device.
.. code-block:: yaml
panos/takelock:
panos.add_config_lock
panos/service_tcp_22:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service
- value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry>
- commit: False
panos/create_rule1:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules
- value: '
<entry name="rule1">
<from><member>trust</member></from>
<to><member>untrust</member></to>
<source><member>10.0.0.1</member></source>
<destination><member>10.0.1.1</member></destination>
<service><member>tcp-22</member></service>
<application><member>any</member></application>
<action>allow</action>
<disabled>no</disabled>
</entry>'
- commit: False
panos/moveruletop:
panos.move_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: top
- commit: False
panos/removelock:
panos.remove_config_lock
panos/commit:
panos.commit
Version Specific Configurations
===============================
Palo Alto devices running different versions will have different supported features and different command structures. In
order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision
level.
The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or
greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and
8.0.0.
.. code-block:: jinja
{% if proxy['panos.is_required_version']('8.0.0') %}
panos/deviceconfig/system/motd-and-banner:
panos.set_config:
- xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner
- value: |
<banner-header>BANNER TEXT</banner-header>
<banner-header-color>color2</banner-header-color>
<banner-header-text-color>color18</banner-header-text-color>
<banner-header-footer-match>yes</banner-header-footer-match>
- commit: False
{% endif %}
.. seealso::
:py:mod:`Palo Alto Proxy Module <salt.proxy.panos>`
'''
# Import Python Libs
from __future__ import absolute_import
import logging
# Import salt libs
import salt.utils.xmlutil as xml
from salt._compat import ElementTree as ET
log = logging.getLogger(__name__)
def __virtual__():
return 'panos.commit' in __salt__
def _build_members(members, anycheck=False):
'''
Builds a member formatted string for XML operation.
'''
if isinstance(members, list):
# This check will strip down members to a single any statement
if anycheck and 'any' in members:
return "<member>any</member>"
response = ""
for m in members:
response += "<member>{0}</member>".format(m)
return response
else:
return "<member>{0}</member>".format(members)
def _default_ret(name):
'''
Set the default response values.
'''
ret = {
'name': name,
'changes': {},
'commit': None,
'result': False,
'comment': ''
}
return ret
def _edit_config(xpath, element):
'''
Sends an edit request to the device.
'''
query = {'type': 'config',
'action': 'edit',
'xpath': xpath,
'element': element}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _get_config(xpath):
'''
Retrieves an xpath from the device.
'''
query = {'type': 'config',
'action': 'get',
'xpath': xpath}
response = __proxy__['panos.call'](query)
return response
def _move_after(xpath, target):
'''
Moves an xpath to the after of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'after',
'dst': target}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_before(xpath, target):
'''
Moves an xpath to the bottom of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'before',
'dst': target}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_bottom(xpath):
'''
Moves an xpath to the bottom of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'bottom'}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _move_top(xpath):
'''
Moves an xpath to the top of its section.
'''
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'top'}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _set_config(xpath, element):
'''
Sends a set request to the device.
'''
query = {'type': 'config',
'action': 'set',
'xpath': xpath,
'element': element}
response = __proxy__['panos.call'](query)
return _validate_response(response)
def _validate_response(response):
'''
Validates a response from a Palo Alto device. Used to verify success of commands.
'''
if not response:
return False, 'Unable to validate response from device.'
elif 'msg' in response:
if 'line' in response['msg']:
if response['msg']['line'] == 'already at the top':
return True, response
elif response['msg']['line'] == 'already at the bottom':
return True, response
else:
return False, response
elif response['msg'] == 'command succeeded':
return True, response
else:
return False, response
elif 'status' in response:
if response['status'] == "success":
return True, response
else:
return False, response
else:
return False, response
def add_config_lock(name):
'''
Prevent other users from changing configuration until the lock is released.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/takelock:
panos.add_config_lock
'''
ret = _default_ret(name)
ret.update({
'changes': __salt__['panos.add_config_lock'](),
'result': True
})
return ret
def address_exists(name,
addressname=None,
vsys=1,
ipnetmask=None,
iprange=None,
fqdn=None,
description=None,
commit=False):
'''
Ensures that an address object exists in the configured state. If it does not exist or is not configured with the
specified attributes, it will be adjusted to match the specified values.
This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified
value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address
type.
name: The name of the module function to execute.
addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where
the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6,
you specify only the network portion, not the host portion.
iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both
can be IPv6.
fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are
subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the
entries are picked up at the refresh cycle.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/address/h-10.10.10.10:
panos.address_exists:
- addressname: h-10.10.10.10
- vsys: 1
- ipnetmask: 10.10.10.10
- commit: False
panos/address/10.0.0.1-10.0.0.50:
panos.address_exists:
- addressname: r-10.0.0.1-10.0.0.50
- vsys: 1
- iprange: 10.0.0.1-10.0.0.50
- commit: False
panos/address/foo.bar.com:
panos.address_exists:
- addressname: foo.bar.com
- vsys: 1
- fqdn: foo.bar.com
- description: My fqdn object
- commit: False
'''
ret = _default_ret(name)
if not addressname:
ret.update({'comment': "The service name field must be provided."})
return ret
# Check if address object currently exists
address = __salt__['panos.get_address'](addressname, vsys)['result']
if address and 'entry' in address:
address = address['entry']
else:
address = {}
element = ""
# Verify the arguments
if ipnetmask:
element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask)
elif iprange:
element = "<ip-range>{0}</ip-range>".format(iprange)
elif fqdn:
element = "<fqdn>{0}</fqdn>".format(fqdn)
else:
ret.update({'comment': "A valid address type must be specified."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element)
new_address = xml.to_dict(ET.fromstring(full_element), True)
if address == new_address:
ret.update({
'comment': 'Address object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \
"entry[@name=\'{1}\']".format(vsys, addressname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': address, 'after': new_address},
'commit': __salt__['panos.commit'](),
'comment': 'Address object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': address, 'after': new_address},
'comment': 'Service object successfully configured.',
'result': True
})
return ret
def address_group_exists(name,
groupname=None,
vsys=1,
members=None,
description=None,
commit=False):
'''
Ensures that an address group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the address group. These must be valid address objects or address groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/address-group/my-group:
panos.address_group_exists:
- groupname: my-group
- vsys: 1
- members:
- my-address-object
- my-other-address-group
- description: A group that needs to exist
- commit: False
'''
ret = _default_ret(name)
if not groupname:
ret.update({'comment': "The group name field must be provided."})
return ret
# Check if address group object currently exists
group = __salt__['panos.get_address_group'](groupname, vsys)['result']
if group and 'entry' in group:
group = group['entry']
else:
group = {}
# Verify the arguments
if members:
element = "<static>{0}</static>".format(_build_members(members, True))
else:
ret.update({'comment': "The group members must be provided."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element)
new_group = xml.to_dict(ET.fromstring(full_element), True)
if group == new_group:
ret.update({
'comment': 'Address group object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \
"entry[@name=\'{1}\']".format(vsys, groupname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': group, 'after': new_group},
'commit': __salt__['panos.commit'](),
'comment': 'Address group object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': group, 'after': new_group},
'comment': 'Address group object successfully configured.',
'result': True
})
return ret
def clone_config(name, xpath=None, newname=None, commit=False):
'''
Clone a specific XPATH and set it to a new name.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to clone.
newname(str): The new name of the XPATH clone.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/clonerule:
panos.clone_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/
entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- value: rule2
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not newname:
return ret
query = {'type': 'config',
'action': 'clone',
'xpath': xpath,
'newname': newname}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def commit_config(name):
'''
Commits the candidate configuration to the running configuration.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/commit:
panos.commit_config
'''
ret = _default_ret(name)
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def delete_config(name, xpath=None, commit=False):
'''
Deletes a Palo Alto XPATH to a specific value.
Use the xpath parameter to specify the location of the object to be deleted.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/deletegroup:
panos.delete_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test']
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
query = {'type': 'config',
'action': 'delete',
'xpath': xpath}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def download_software(name, version=None, synch=False, check=False):
'''
Ensures that a software version is downloaded.
name: The name of the module function to execute.
version(str): The software version to check. If this version is not already downloaded, it will attempt to download
the file from Palo Alto.
synch(bool): If true, after downloading the file it will be synched to its peer.
check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo
Alto.
SLS Example:
.. code-block:: yaml
panos/version8.0.0:
panos.download_software:
- version: 8.0.0
- synch: False
- check: True
'''
ret = _default_ret(name)
if check is True:
__salt__['panos.check_software']()
versions = __salt__['panos.get_software_info']()['result']
if 'sw-updates' not in versions \
or 'versions' not in versions['sw-updates'] \
or 'entry' not in versions['sw-updates']['versions']:
ret.update({
'comment': 'Software version is not found in the local software list.',
'result': False
})
return ret
for entry in versions['sw-updates']['versions']['entry']:
if entry['version'] == version and entry['downloaded'] == "yes":
ret.update({
'comment': 'Software version is already downloaded.',
'result': True
})
return ret
ret.update({
'changes': __salt__['panos.download_software_version'](version=version, synch=synch)
})
versions = __salt__['panos.get_software_info']()['result']
if 'sw-updates' not in versions \
or 'versions' not in versions['sw-updates'] \
or 'entry' not in versions['sw-updates']['versions']:
ret.update({
'result': False
})
return ret
for entry in versions['sw-updates']['versions']['entry']:
if entry['version'] == version and entry['downloaded'] == "yes":
ret.update({
'result': True
})
return ret
return ret
def edit_config(name, xpath=None, value=None, commit=False):
'''
Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not
changed.
You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use
the xpath parameter to specify the location of the object, including the node to be replaced.
This is the recommended state to enforce configurations on a xpath.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
value(str): The XML value to edit. This must be a child to the XPATH.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/addressgroup:
panos.edit_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test']
- value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static>
- commit: True
'''
ret = _default_ret(name)
# Verify if the current XPATH is equal to the specified value.
# If we are equal, no changes required.
xpath_split = xpath.split("/")
# Retrieve the head of the xpath for validation.
if xpath_split:
head = xpath_split[-1]
if "[" in head:
head = head.split("[")[0]
current_element = __salt__['panos.get_xpath'](xpath)['result']
if head and current_element and head in current_element:
current_element = current_element[head]
else:
current_element = {}
new_element = xml.to_dict(ET.fromstring(value), True)
if current_element == new_element:
ret.update({
'comment': 'XPATH is already equal to the specified value.',
'result': True
})
return ret
result, msg = _edit_config(xpath, value)
ret.update({
'comment': msg,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'changes': {'before': current_element, 'after': new_element},
'commit': __salt__['panos.commit'](),
'result': True
})
else:
ret.update({
'changes': {'before': current_element, 'after': new_element},
'result': True
})
return ret
def move_config(name, xpath=None, where=None, dst=None, commit=False):
'''
Moves a XPATH value to a new location.
Use the xpath parameter to specify the location of the object to be moved, the where parameter to
specify type of move, and dst parameter to specify the destination path.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to move.
where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before
options will require the dst option to specify the destination of the action. The top action will move the
XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure.
dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top
or bottom action.
commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is
not successful, it will not commit.
SLS Example:
.. code-block:: yaml
panos/moveruletop:
panos.move_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: top
- commit: True
panos/moveruleafter:
panos.move_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1']
- where: after
- dst: rule2
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not where:
return ret
if where == 'after':
result, msg = _move_after(xpath, dst)
elif where == 'before':
result, msg = _move_before(xpath, dst)
elif where == 'top':
result, msg = _move_top(xpath)
elif where == 'bottom':
result, msg = _move_bottom(xpath)
ret.update({
'result': result,
'comment': msg
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def remove_config_lock(name):
'''
Release config lock previously held.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/takelock:
panos.remove_config_lock
'''
ret = _default_ret(name)
ret.update({
'changes': __salt__['panos.remove_config_lock'](),
'result': True
})
return ret
def rename_config(name, xpath=None, newname=None, commit=False):
'''
Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed.
name: The name of the module function to execute.
xpath(str): The XPATH of the configuration API tree to control.
newname(str): The new name of the XPATH value.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/renamegroup:
panos.rename_config:
- xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address']
- value: new_address
- commit: True
'''
ret = _default_ret(name)
if not xpath:
return ret
if not newname:
return ret
query = {'type': 'config',
'action': 'rename',
'xpath': xpath,
'newname': newname}
result, response = _validate_response(__proxy__['panos.call'](query))
ret.update({
'changes': response,
'result': result
})
if not result:
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
return ret
def security_rule_exists(name,
rulename=None,
vsys='1',
action=None,
disabled=None,
sourcezone=None,
destinationzone=None,
source=None,
destination=None,
application=None,
service=None,
description=None,
logsetting=None,
logstart=None,
logend=None,
negatesource=None,
negatedestination=None,
profilegroup=None,
datafilter=None,
fileblock=None,
spyware=None,
urlfilter=None,
virus=None,
vulnerability=None,
wildfire=None,
move=None,
movetarget=None,
commit=False):
'''
Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately.
This method will create the rule if it does not exist. If the rule does exist, it will ensure that the
configurations are set appropriately.
If the rule does not exist and is created, any value that is not provided will be provided as the default.
The action, to, from, source, destination, application, and service fields are mandatory and must be provided.
This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end
option, but this option is not specified in the state method, it will be removed and reset to the system default.
It is strongly recommended to specify all options to ensure proper operation.
When defining the profile group settings, the device can only support either a profile group or individual settings.
If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are
specified, the value will be set to system default of none.
name: The name of the module function to execute.
rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which
can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama,
unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client,
reset-server, reset-both.
disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable.
sourcezone(str, list): The source zone(s). The value 'any' will match all zones.
destinationzone(str, list): The destination zone(s). The value 'any' will match all zones.
source(str, list): The source address(es). The value 'any' will match all addresses.
destination(str, list): The destination address(es). The value 'any' will match all addresses.
application(str, list): The application(s) matched. The value 'any' will match all applications.
service(str, list): The service(s) matched. The value 'any' will match all services. The value
'application-default' will match based upon the application defined ports.
description(str): A description for the policy (up to 255 characters).
logsetting(str): The name of a valid log forwarding profile.
logstart(bool): Generates a traffic log entry for the start of a session (disabled by default).
logend(bool): Generates a traffic log entry for the end of a session (enabled by default).
negatesource(bool): Match all but the specified source addresses.
negatedestination(bool): Match all but the specified destination addresses.
profilegroup(str): A valid profile group name.
datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set.
fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set.
spyware(str): A valid spyware profile name. Ignored with the profilegroup option set.
urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set.
virus(str): A valid virus profile name. Ignored with the profilegroup option set.
vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set.
move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top',
'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument
to define the location of the move request.
movetarget(str): An optional argument that defines the target of the move operation if the move argument is
set to 'before' or 'after'.
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: True
- negatesource: False
- negatedestination: False
- profilegroup: myprofilegroup
- move: top
- commit: False
panos/rulebase/security/rule01:
panos.security_rule_exists:
- rulename: rule01
- vsys: 1
- action: allow
- disabled: False
- sourcezone: untrust
- destinationzone: trust
- source:
- 10.10.10.0/24
- 1.1.1.1
- destination:
- 2.2.2.2-2.2.2.4
- application:
- any
- service:
- tcp-25
- description: My test security rule
- logsetting: logprofile
- logstart: False
- logend: False
- datafilter: foobar
- fileblock: foobar
- spyware: foobar
- urlfilter: foobar
- virus: foobar
- vulnerability: foobar
- wildfire: foobar
- move: after
- movetarget: rule02
- commit: False
'''
ret = _default_ret(name)
if not rulename:
return ret
# Check if rule currently exists
rule = __salt__['panos.get_security_rule'](rulename, vsys)['result']
if rule and 'entry' in rule:
rule = rule['entry']
else:
rule = {}
# Build the rule element
element = ""
if sourcezone:
element += "<from>{0}</from>".format(_build_members(sourcezone, True))
else:
ret.update({'comment': "The sourcezone field must be provided."})
return ret
if destinationzone:
element += "<to>{0}</to>".format(_build_members(destinationzone, True))
else:
ret.update({'comment': "The destinationzone field must be provided."})
return ret
if source:
element += "<source>{0}</source>".format(_build_members(source, True))
else:
ret.update({'comment': "The source field must be provided."})
return
if destination:
element += "<destination>{0}</destination>".format(_build_members(destination, True))
else:
ret.update({'comment': "The destination field must be provided."})
return ret
if application:
element += "<application>{0}</application>".format(_build_members(application, True))
else:
ret.update({'comment': "The application field must be provided."})
return ret
if service:
element += "<service>{0}</service>".format(_build_members(service, True))
else:
ret.update({'comment': "The service field must be provided."})
return ret
if action:
element += "<action>{0}</action>".format(action)
else:
ret.update({'comment': "The action field must be provided."})
return ret
if disabled is not None:
if disabled:
element += "<disabled>yes</disabled>"
else:
element += "<disabled>no</disabled>"
if description:
element += "<description>{0}</description>".format(description)
if logsetting:
element += "<log-setting>{0}</log-setting>".format(logsetting)
if logstart is not None:
if logstart:
element += "<log-start>yes</log-start>"
else:
element += "<log-start>no</log-start>"
if logend is not None:
if logend:
element += "<log-end>yes</log-end>"
else:
element += "<log-end>no</log-end>"
if negatesource is not None:
if negatesource:
element += "<negate-source>yes</negate-source>"
else:
element += "<negate-source>no</negate-source>"
if negatedestination is not None:
if negatedestination:
element += "<negate-destination>yes</negate-destination>"
else:
element += "<negate-destination>no</negate-destination>"
# Build the profile settings
profile_string = None
if profilegroup:
profile_string = "<group><member>{0}</member></group>".format(profilegroup)
else:
member_string = ""
if datafilter:
member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter)
if fileblock:
member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock)
if spyware:
member_string += "<spyware><member>{0}</member></spyware>".format(spyware)
if urlfilter:
member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter)
if virus:
member_string += "<virus><member>{0}</member></virus>".format(virus)
if vulnerability:
member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability)
if wildfire:
member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire)
if member_string != "":
profile_string = "<profiles>{0}</profiles>".format(member_string)
if profile_string:
element += "<profile-setting>{0}</profile-setting>".format(profile_string)
full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element)
new_rule = xml.to_dict(ET.fromstring(full_element), True)
config_change = False
if rule == new_rule:
ret.update({
'comment': 'Security rule already exists. No changes required.'
})
else:
config_change = True
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \
"security/rules/entry[@name=\'{1}\']".format(vsys, rulename)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
ret.update({
'changes': {'before': rule, 'after': new_rule},
'comment': 'Security rule verified successfully.'
})
if move:
movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \
"security/rules/entry[@name=\'{1}\']".format(vsys, rulename)
move_result = False
move_msg = ''
if move == "before" and movetarget:
move_result, move_msg = _move_before(movepath, movetarget)
elif move == "after":
move_result, move_msg = _move_after(movepath, movetarget)
elif move == "top":
move_result, move_msg = _move_top(movepath)
elif move == "bottom":
move_result, move_msg = _move_bottom(movepath)
if config_change:
ret.update({
'changes': {'before': rule, 'after': new_rule, 'move': move_msg}
})
else:
ret.update({
'changes': {'move': move_msg}
})
if not move_result:
ret.update({
'comment': move_msg
})
return ret
if commit is True:
ret.update({
'commit': __salt__['panos.commit'](),
'result': True
})
else:
ret.update({
'result': True
})
return ret
def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False):
'''
Ensures that a service object exists in the configured state. If it does not exist or is not configured with the
specified attributes, it will be adjusted to match the specified values.
name: The name of the module function to execute.
servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp.
port(str): The port number that is used by the service object. This can be specified as a single integer or a
valid range of ports.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service/tcp-80:
panos.service_exists:
- servicename: tcp-80
- vsys: 1
- protocol: tcp
- port: 80
- description: Hypertext Transfer Protocol
- commit: False
panos/service/udp-500-550:
panos.service_exists:
- servicename: udp-500-550
- vsys: 3
- protocol: udp
- port: 500-550
- commit: False
'''
ret = _default_ret(name)
if not servicename:
ret.update({'comment': "The service name field must be provided."})
return ret
# Check if service object currently exists
service = __salt__['panos.get_service'](servicename, vsys)['result']
if service and 'entry' in service:
service = service['entry']
else:
service = {}
# Verify the arguments
if not protocol and protocol not in ['tcp', 'udp']:
ret.update({'comment': "The protocol must be provided and must be tcp or udp."})
return ret
if not port:
ret.update({'comment': "The port field must be provided."})
return ret
element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port)
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element)
new_service = xml.to_dict(ET.fromstring(full_element), True)
if service == new_service:
ret.update({
'comment': 'Service object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \
"entry[@name=\'{1}\']".format(vsys, servicename)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': service, 'after': new_service},
'commit': __salt__['panos.commit'](),
'comment': 'Service object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': service, 'after': new_service},
'comment': 'Service object successfully configured.',
'result': True
})
return ret
def service_group_exists(name,
groupname=None,
vsys=1,
members=None,
description=None,
commit=False):
'''
Ensures that a service group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the service group. These must be valid service objects or service groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service-group/my-group:
panos.service_group_exists:
- groupname: my-group
- vsys: 1
- members:
- tcp-80
- custom-port-group
- description: A group that needs to exist
- commit: False
'''
ret = _default_ret(name)
if not groupname:
ret.update({'comment': "The group name field must be provided."})
return ret
# Check if service group object currently exists
group = __salt__['panos.get_service_group'](groupname, vsys)['result']
if group and 'entry' in group:
group = group['entry']
else:
group = {}
# Verify the arguments
if members:
element = "<members>{0}</members>".format(_build_members(members, True))
else:
ret.update({'comment': "The group members must be provided."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element)
new_group = xml.to_dict(ET.fromstring(full_element), True)
if group == new_group:
ret.update({
'comment': 'Service group object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \
"entry[@name=\'{1}\']".format(vsys, groupname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': group, 'after': new_group},
'commit': __salt__['panos.commit'](),
'comment': 'Service group object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': group, 'after': new_group},
'comment': 'Service group object successfully configured.',
'result': True
})
return ret
|
saltstack/salt
|
salt/modules/cmdmod.py
|
_check_cb
|
python
|
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns
the value passed.
'''
if cb_ is not None:
if hasattr(cb_, '__call__'):
return cb_
else:
log.error('log_callback is not callable, ignoring')
return lambda x: x
|
If the callback is None or is not callable, return a lambda that returns
the value passed.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cmdmod.py#L79-L89
| null |
# -*- coding: utf-8 -*-
'''
A module for shelling out.
Keep in mind that this module is insecure, in that it can give whomever has
access to the master root execution access to all salt minions.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import functools
import glob
import logging
import os
import shutil
import subprocess
import sys
import time
import traceback
import fnmatch
import base64
import re
import tempfile
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.powershell
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.timed_subprocess
import salt.utils.user
import salt.utils.versions
import salt.utils.vt
import salt.utils.win_dacl
import salt.utils.win_reg
import salt.grains.extra
from salt.ext import six
from salt.exceptions import CommandExecutionError, TimedProcTimeoutError, \
SaltInvocationError
from salt.log import LOG_LEVELS
from salt.ext.six.moves import range, zip, map
# Only available on POSIX systems, nonfatal on windows
try:
import pwd
import grp
except ImportError:
pass
if salt.utils.platform.is_windows():
from salt.utils.win_runas import runas as win_runas
from salt.utils.win_functions import escape_argument as _cmd_quote
HAS_WIN_RUNAS = True
else:
from salt.ext.six.moves import shlex_quote as _cmd_quote
HAS_WIN_RUNAS = False
__proxyenabled__ = ['*']
# Define the module's virtual name
__virtualname__ = 'cmd'
# Set up logging
log = logging.getLogger(__name__)
DEFAULT_SHELL = salt.grains.extra.shell()['shell']
# Overwriting the cmd python module makes debugging modules with pdb a bit
# harder so lets do it this way instead.
def __virtual__():
return __virtualname__
def _python_shell_default(python_shell, __pub_jid):
'''
Set python_shell default based on remote execution and __opts__['cmd_safe']
'''
try:
# Default to python_shell=True when run directly from remote execution
# system. Cross-module calls won't have a jid.
if __pub_jid and python_shell is None:
return True
elif __opts__.get('cmd_safe', True) is False and python_shell is None:
# Override-switch for python_shell
return True
except NameError:
pass
return python_shell
def _chroot_pids(chroot):
pids = []
for root in glob.glob('/proc/[0-9]*/root'):
try:
link = os.path.realpath(root)
if link.startswith(chroot):
pids.append(int(os.path.basename(
os.path.dirname(root)
)))
except OSError:
pass
return pids
def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):
'''
If template is a valid template engine, process the cmd and cwd through
that engine.
'''
if not template:
return (cmd, cwd)
# render the path as a template using path_template_engine as the engine
if template not in salt.utils.templates.TEMPLATE_REGISTRY:
raise CommandExecutionError(
'Attempted to render file paths with unavailable engine '
'{0}'.format(template)
)
kwargs = {}
kwargs['salt'] = __salt__
if pillarenv is not None or pillar_override is not None:
pillarenv = pillarenv or __opts__['pillarenv']
kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override)
else:
kwargs['pillar'] = __pillar__
kwargs['grains'] = __grains__
kwargs['opts'] = __opts__
kwargs['saltenv'] = saltenv
def _render(contents):
# write out path to temp file
tmp_path_fn = salt.utils.files.mkstemp()
with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(contents))
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
tmp_path_fn,
to_str=True,
**kwargs
)
salt.utils.files.safe_rm(tmp_path_fn)
if not data['result']:
# Failed to render the template
raise CommandExecutionError(
'Failed to execute cmd with error: {0}'.format(
data['data']
)
)
else:
return data['data']
cmd = _render(cmd)
cwd = _render(cwd)
return (cmd, cwd)
def _check_loglevel(level='info'):
'''
Retrieve the level code for use in logging.Logger.log().
'''
try:
level = level.lower()
if level == 'quiet':
return None
else:
return LOG_LEVELS[level]
except (AttributeError, KeyError):
log.error(
'Invalid output_loglevel \'%s\'. Valid levels are: %s. Falling '
'back to \'info\'.',
level, ', '.join(sorted(LOG_LEVELS, reverse=True))
)
return LOG_LEVELS['info']
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
return env
def _gather_pillar(pillarenv, pillar_override):
'''
Whenever a state run starts, gather the pillar data fresh
'''
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
pillar_override=pillar_override,
pillarenv=pillarenv
)
ret = pillar.compile_pillar()
if pillar_override and isinstance(pillar_override, dict):
ret.update(pillar_override)
return ret
def _check_avail(cmd):
'''
Check to see if the given command can be run
'''
if isinstance(cmd, list):
cmd = ' '.join([six.text_type(x) if not isinstance(x, six.string_types) else x
for x in cmd])
bret = True
wret = False
if __salt__['config.get']('cmd_blacklist_glob'):
blist = __salt__['config.get']('cmd_blacklist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# BAD! you are blacklisted
bret = False
if __salt__['config.get']('cmd_whitelist_glob', []):
blist = __salt__['config.get']('cmd_whitelist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# GOOD! You are whitelisted
wret = True
break
else:
# If no whitelist set then alls good!
wret = True
return bret and wret
def _run(cmd,
cwd=None,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
prepend_path=None,
rstrip=True,
template=None,
umask=None,
timeout=None,
with_communicate=True,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
pillarenv=None,
pillar_override=None,
use_vt=False,
password=None,
bg=False,
encoded_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Do the DRY thing and only call subprocess.Popen() once
'''
if 'pillar' in kwargs and not pillar_override:
pillar_override = kwargs['pillar']
if output_loglevel != 'quiet' and _is_valid_shell(shell) is False:
log.warning(
'Attempt to run a shell command with what may be an invalid shell! '
'Check to ensure that the shell <%s> is valid for this user.',
shell
)
output_loglevel = _check_loglevel(output_loglevel)
log_callback = _check_cb(log_callback)
use_sudo = False
if runas is None and '__context__' in globals():
runas = __context__.get('runas')
if password is None and '__context__' in globals():
password = __context__.get('runas_password')
# Set the default working directory to the home directory of the user
# salt-minion is running as. Defaults to home directory of user under which
# the minion is running.
if not cwd:
cwd = os.path.expanduser('~{0}'.format('' if not runas else runas))
# make sure we can access the cwd
# when run from sudo or another environment where the euid is
# changed ~ will expand to the home of the original uid and
# the euid might not have access to it. See issue #1844
if not os.access(cwd, os.R_OK):
cwd = '/'
if salt.utils.platform.is_windows():
cwd = os.path.abspath(os.sep)
else:
# Handle edge cases where numeric/other input is entered, and would be
# yaml-ified into non-string types
cwd = six.text_type(cwd)
if bg:
ignore_retcode = True
use_vt = False
if not salt.utils.platform.is_windows():
if not os.path.isfile(shell) or not os.access(shell, os.X_OK):
msg = 'The shell {0} is not available'.format(shell)
raise CommandExecutionError(msg)
if salt.utils.platform.is_windows() and use_vt: # Memozation so not much overhead
raise CommandExecutionError('VT not available on windows')
if shell.lower().strip() == 'powershell':
# Strip whitespace
if isinstance(cmd, six.string_types):
cmd = cmd.strip()
# If we were called by script(), then fakeout the Windows
# shell to run a Powershell script.
# Else just run a Powershell command.
stack = traceback.extract_stack(limit=2)
# extract_stack() returns a list of tuples.
# The last item in the list [-1] is the current method.
# The third item[2] in each tuple is the name of that method.
if stack[-2][2] == 'script':
cmd = 'Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -File ' + cmd
elif encoded_cmd:
cmd = 'Powershell -NonInteractive -EncodedCommand {0}'.format(cmd)
else:
cmd = 'Powershell -NonInteractive -NoProfile "{0}"'.format(cmd.replace('"', '\\"'))
# munge the cmd and cwd through the template
(cmd, cwd) = _render_cmd(cmd, cwd, template, saltenv, pillarenv, pillar_override)
ret = {}
# If the pub jid is here then this is a remote ex or salt call command and needs to be
# checked if blacklisted
if '__pub_jid' in kwargs:
if not _check_avail(cmd):
raise CommandExecutionError(
'The shell command "{0}" is not permitted'.format(cmd)
)
env = _parse_env(env)
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, six.string_types) else x for x in cmd]
elif isinstance(cmd, six.string_types):
return cmd.strip()
else:
return cmd
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' parameter.
msg = (
'Executing command {0}{1}{0} {2}{3}in directory \'{4}\'{5}'.format(
'\'' if not isinstance(cmd, list) else '',
_get_stripped(cmd),
'as user \'{0}\' '.format(runas) if runas else '',
'in group \'{0}\' '.format(group) if group else '',
cwd,
'. Executing command in the background, no output will be '
'logged.' if bg else ''
)
)
log.info(log_callback(msg))
if runas and salt.utils.platform.is_windows():
if not HAS_WIN_RUNAS:
msg = 'missing salt/utils/win_runas.py'
raise CommandExecutionError(msg)
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(cmd)
return win_runas(cmd, runas, password, cwd)
if runas and salt.utils.platform.is_darwin():
# we need to insert the user simulation into the command itself and not
# just run it from the environment on macOS as that
# method doesn't work properly when run as root for certain commands.
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(map(_cmd_quote, cmd))
cmd = 'su -l {0} -c "cd {1}; {2}"'.format(runas, cwd, cmd)
# set runas to None, because if you try to run `su -l` as well as
# simulate the environment macOS will prompt for the password of the
# user and will cause salt to hang.
runas = None
if runas:
# Save the original command before munging it
try:
pwd.getpwnam(runas)
except KeyError:
raise CommandExecutionError(
'User \'{0}\' is not available'.format(runas)
)
if group:
if salt.utils.platform.is_windows():
msg = 'group is not currently available on Windows'
raise SaltInvocationError(msg)
if not which_bin(['sudo']):
msg = 'group argument requires sudo but not found'
raise CommandExecutionError(msg)
try:
grp.getgrnam(group)
except KeyError:
raise CommandExecutionError(
'Group \'{0}\' is not available'.format(runas)
)
else:
use_sudo = True
if runas or group:
try:
# Getting the environment for the runas user
# Use markers to thwart any stdout noise
# There must be a better way to do this.
import uuid
marker = '<<<' + str(uuid.uuid4()) + '>>>'
marker_b = marker.encode(__salt_system_encoding__)
py_code = (
'import sys, os, itertools; '
'sys.stdout.write(\"' + marker + '\"); '
'sys.stdout.write(\"\\0\".join(itertools.chain(*os.environ.items()))); '
'sys.stdout.write(\"' + marker + '\");'
)
if use_sudo or __grains__['os'] in ['MacOS', 'Darwin']:
env_cmd = ['sudo']
# runas is optional if use_sudo is set.
if runas:
env_cmd.extend(['-u', runas])
if group:
env_cmd.extend(['-g', group])
if shell != DEFAULT_SHELL:
env_cmd.extend(['-s', '--', shell, '-c'])
else:
env_cmd.extend(['-i', '--'])
env_cmd.extend([sys.executable])
elif __grains__['os'] in ['FreeBSD']:
env_cmd = ('su', '-', runas, '-c',
"{0} -c {1}".format(shell, sys.executable))
elif __grains__['os_family'] in ['Solaris']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
elif __grains__['os_family'] in ['AIX']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
else:
env_cmd = ('su', '-s', shell, '-', runas, '-c', sys.executable)
msg = 'env command: {0}'.format(env_cmd)
log.debug(log_callback(msg))
env_bytes, env_encoded_err = subprocess.Popen(
env_cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
).communicate(salt.utils.stringutils.to_bytes(py_code))
marker_count = env_bytes.count(marker_b)
if marker_count == 0:
# Possibly PAM prevented the login
log.error(
'Environment could not be retrieved for user \'%s\': '
'stderr=%r stdout=%r',
runas, env_encoded_err, env_bytes
)
# Ensure that we get an empty env_runas dict below since we
# were not able to get the environment.
env_bytes = b''
elif marker_count != 2:
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\'',
info={'stderr': repr(env_encoded_err),
'stdout': repr(env_bytes)}
)
else:
# Strip the marker
env_bytes = env_bytes.split(marker_b)[1]
if six.PY2:
import itertools
env_runas = dict(itertools.izip(*[iter(env_bytes.split(b'\0'))]*2))
elif six.PY3:
env_runas = dict(list(zip(*[iter(env_bytes.split(b'\0'))]*2)))
env_runas = dict(
(salt.utils.stringutils.to_str(k),
salt.utils.stringutils.to_str(v))
for k, v in six.iteritems(env_runas)
)
env_runas.update(env)
# Fix platforms like Solaris that don't set a USER env var in the
# user's default environment as obtained above.
if env_runas.get('USER') != runas:
env_runas['USER'] = runas
# Fix some corner cases where shelling out to get the user's
# environment returns the wrong home directory.
runas_home = os.path.expanduser('~{0}'.format(runas))
if env_runas.get('HOME') != runas_home:
env_runas['HOME'] = runas_home
env = env_runas
except ValueError as exc:
log.exception('Error raised retrieving environment for user %s', runas)
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\': {1}'.format(
runas, exc
)
)
if reset_system_locale is True:
if not salt.utils.platform.is_windows():
# Default to C!
# Salt only knows how to parse English words
# Don't override if the user has passed LC_ALL
env.setdefault('LC_CTYPE', 'C')
env.setdefault('LC_NUMERIC', 'C')
env.setdefault('LC_TIME', 'C')
env.setdefault('LC_COLLATE', 'C')
env.setdefault('LC_MONETARY', 'C')
env.setdefault('LC_MESSAGES', 'C')
env.setdefault('LC_PAPER', 'C')
env.setdefault('LC_NAME', 'C')
env.setdefault('LC_ADDRESS', 'C')
env.setdefault('LC_TELEPHONE', 'C')
env.setdefault('LC_MEASUREMENT', 'C')
env.setdefault('LC_IDENTIFICATION', 'C')
env.setdefault('LANGUAGE', 'C')
else:
# On Windows set the codepage to US English.
if python_shell:
cmd = 'chcp 437 > nul & ' + cmd
if clean_env:
run_env = env
else:
run_env = os.environ.copy()
run_env.update(env)
if prepend_path:
run_env['PATH'] = ':'.join((prepend_path, run_env['PATH']))
if python_shell is None:
python_shell = False
new_kwargs = {'cwd': cwd,
'shell': python_shell,
'env': run_env if six.PY3 else salt.utils.data.encode(run_env),
'stdin': six.text_type(stdin) if stdin is not None else stdin,
'stdout': stdout,
'stderr': stderr,
'with_communicate': with_communicate,
'timeout': timeout,
'bg': bg,
}
if 'stdin_raw_newlines' in kwargs:
new_kwargs['stdin_raw_newlines'] = kwargs['stdin_raw_newlines']
if umask is not None:
_umask = six.text_type(umask).lstrip('0')
if _umask == '':
msg = 'Zero umask is not allowed.'
raise CommandExecutionError(msg)
try:
_umask = int(_umask, 8)
except ValueError:
raise CommandExecutionError("Invalid umask: '{0}'".format(umask))
else:
_umask = None
if runas or group or umask:
new_kwargs['preexec_fn'] = functools.partial(
salt.utils.user.chugid_and_umask,
runas,
_umask,
group)
if not salt.utils.platform.is_windows():
# close_fds is not supported on Windows platforms if you redirect
# stdin/stdout/stderr
if new_kwargs['shell'] is True:
new_kwargs['executable'] = shell
new_kwargs['close_fds'] = True
if not os.path.isabs(cwd) or not os.path.isdir(cwd):
raise CommandExecutionError(
'Specified cwd \'{0}\' either not absolute or does not exist'
.format(cwd)
)
if python_shell is not True \
and not salt.utils.platform.is_windows() \
and not isinstance(cmd, list):
cmd = salt.utils.args.shlex_split(cmd)
if success_retcodes is None:
success_retcodes = [0]
else:
try:
success_retcodes = [int(i) for i in
salt.utils.args.split_input(
success_retcodes
)]
except ValueError:
raise SaltInvocationError(
'success_retcodes must be a list of integers'
)
if success_stdout is None:
success_stdout = []
else:
try:
success_stdout = [i for i in
salt.utils.args.split_input(
success_stdout
)]
except ValueError:
raise SaltInvocationError(
'success_stdout must be a list of integers'
)
if success_stderr is None:
success_stderr = []
else:
try:
success_stderr = [i for i in
salt.utils.args.split_input(
success_stderr
)]
except ValueError:
raise SaltInvocationError(
'success_stderr must be a list of integers'
)
if not use_vt:
# This is where the magic happens
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **new_kwargs)
except (OSError, IOError) as exc:
msg = (
'Unable to run command \'{0}\' with the context \'{1}\', '
'reason: {2}'.format(
cmd if output_loglevel is not None else 'REDACTED',
new_kwargs,
exc
)
)
raise CommandExecutionError(msg)
try:
proc.run()
except TimedProcTimeoutError as exc:
ret['stdout'] = six.text_type(exc)
ret['stderr'] = ''
ret['retcode'] = None
ret['pid'] = proc.process.pid
# ok return code for timeouts?
ret['retcode'] = 1
return ret
if output_loglevel != 'quiet' and output_encoding is not None:
log.debug('Decoding output from command %s using %s encoding',
cmd, output_encoding)
try:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding)
except TypeError:
# stdout is None
out = ''
except UnicodeDecodeError:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', cmd
)
try:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding)
except TypeError:
# stderr is None
err = ''
except UnicodeDecodeError:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', cmd
)
if rstrip:
if out is not None:
out = out.rstrip()
if err is not None:
err = err.rstrip()
ret['pid'] = proc.process.pid
ret['retcode'] = proc.process.returncode
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
ret['stdout'] = out
ret['stderr'] = err
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
else:
formatted_timeout = ''
if timeout:
formatted_timeout = ' (timeout: {0}s)'.format(timeout)
if output_loglevel is not None:
msg = 'Running {0} in VT{1}'.format(cmd, formatted_timeout)
log.debug(log_callback(msg))
stdout, stderr = '', ''
now = time.time()
if timeout:
will_timeout = now + timeout
else:
will_timeout = -1
try:
proc = salt.utils.vt.Terminal(
cmd,
shell=True,
log_stdout=True,
log_stderr=True,
cwd=cwd,
preexec_fn=new_kwargs.get('preexec_fn', None),
env=run_env,
log_stdin_level=output_loglevel,
log_stdout_level=output_loglevel,
log_stderr_level=output_loglevel,
stream_stdout=True,
stream_stderr=True
)
ret['pid'] = proc.pid
while proc.has_unread_data:
try:
try:
time.sleep(0.5)
try:
cstdout, cstderr = proc.recv()
except IOError:
cstdout, cstderr = '', ''
if cstdout:
stdout += cstdout
else:
cstdout = ''
if cstderr:
stderr += cstderr
else:
cstderr = ''
if timeout and (time.time() > will_timeout):
ret['stderr'] = (
'SALT: Timeout after {0}s\n{1}').format(
timeout, stderr)
ret['retcode'] = None
break
except KeyboardInterrupt:
ret['stderr'] = 'SALT: User break\n{0}'.format(stderr)
ret['retcode'] = 1
break
except salt.utils.vt.TerminalException as exc:
log.error('VT: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
ret = {'retcode': 1, 'pid': '2'}
break
# only set stdout on success as we already mangled in other
# cases
ret['stdout'] = stdout
if not proc.isalive():
# Process terminated, i.e., not canceled by the user or by
# the timeout
ret['stderr'] = stderr
ret['retcode'] = proc.exitstatus
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
ret['pid'] = proc.pid
finally:
proc.close(terminate=True, kill=True)
try:
if ignore_retcode:
__context__['retcode'] = 0
else:
__context__['retcode'] = ret['retcode']
except NameError:
# Ignore the context error during grain generation
pass
# Log the output
if output_loglevel is not None:
if not ignore_retcode and ret['retcode'] != 0:
if output_loglevel < LOG_LEVELS['error']:
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if ret['stdout']:
log.log(output_loglevel, 'stdout: %s', log_callback(ret['stdout']))
if ret['stderr']:
log.log(output_loglevel, 'stderr: %s', log_callback(ret['stderr']))
if ret['retcode']:
log.log(output_loglevel, 'retcode: %s', ret['retcode'])
return ret
def _run_quiet(cmd,
cwd=None,
stdin=None,
output_encoding=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)['stdout']
def _run_all_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
output_encoding=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup.
Returns a dict of return data.
output_loglevel argument is ignored. This is here for when we alias
cmd.run_all directly to _run_all_quiet in certain chicken-and-egg
situations where modules need to work both before and after
the __salt__ dictionary is populated (cf dracr.py)
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)
def run(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
encoded_cmd=False,
raise_err=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
Execute the passed command and return the output as a string
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run 'echo '\''h=\"baz\"'\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If ``False``, let python handle the positional
arguments. Set to ``True`` to use shell features, such as pipes or
redirection.
:param bool bg: If ``True``, run command in background and do not await or
deliver it's results
.. versionadded:: 2016.3.0
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
:param bool raise_err: If ``True`` and the command has a nonzero exit code,
a CommandExecutionError exception will be raised.
.. warning::
This function does not process commands through a shell
unless the python_shell flag is set to True. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or
have the python_shell=True flag set here.
The use of python_shell=True means that the shell will accept _any_ input
including potentially malicious commands such as 'good_command;rm -rf /'.
Be absolutely certain that you have sanitized your input prior to using
python_shell=True
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run cmd='sed -e s/=/:/g'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
log_callback = _check_cb(log_callback)
lvl = _check_loglevel(output_loglevel)
if lvl is not None:
if not ignore_retcode and ret['retcode'] != 0:
if lvl < LOG_LEVELS['error']:
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if raise_err:
raise CommandExecutionError(
log_callback(ret['stdout'] if not hide_output else '')
)
log.log(lvl, 'output: %s', log_callback(ret['stdout']))
return ret['stdout'] if not hide_output else ''
def shell(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return the output as a string.
.. versionadded:: 2015.5.0
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.shell 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param int shell: Shell to execute under. Defaults to the system default
shell.
:param bool bg: If True, run command in background and do not await or
deliver its results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.shell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
.. warning::
This passes the cmd argument directly to the shell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.shell "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.shell template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.shell "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.shell "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.shell cmd='sed -e s/=/:/g'
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
return run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
def run_stdout(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command, and only return the standard out
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stdout 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stdout template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stdout "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stdout'] if not hide_output else ''
def run_stderr(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command and only return the standard error
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stderr 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stderr 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stderr "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stderr template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stderr "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stderr'] if not hide_output else ''
def run_all(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
redirect_stderr=False,
password=None,
encoded_cmd=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return a dict of return data
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_all 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
.. versionadded:: 2018.3.0
:param bool redirect_stderr: If set to ``True``, then stderr will be
redirected to stdout. This is helpful for cases where obtaining both
the retcode and output is desired, but it is not desired to have the
output separated into both stdout and stderr.
.. versionadded:: 2015.8.2
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param bool bg: If ``True``, run command in background and do not await or
deliver its results
.. versionadded:: 2016.3.6
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_all "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_all template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_all "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=stderr,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def retcode(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a shell command and return the command's return code.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.retcode 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.retcode 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:rtype: int
:rtype: None
:returns: Return Code as an int or None if there was an exception.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.retcode "file /bin/bash"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.retcode template=jinja "file {{grains.pythonpath[0]}}/python"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.retcode "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['retcode']
def _retcode_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Helper for running commands quietly for minion startup. Returns same as
the retcode() function.
'''
return retcode(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stderr,
success_stderr=success_stderr,
**kwargs)
def script(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
saltenv='base',
use_vt=False,
bg=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
.. code-block:: bash
salt myminion cmd.script salt://foo.sh "arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param bool bg: If True, run script in background and do not await or
deliver it's results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh
salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
def _cleanup_tempfile(path):
try:
__salt__['file.remove'](path)
except (SaltInvocationError, CommandExecutionError) as exc:
log.error(
'cmd.script: Unable to clean tempfile \'%s\': %s',
path, exc, exc_info_on_loglevel=logging.DEBUG
)
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
win_cwd = False
if salt.utils.platform.is_windows() and runas and cwd is None:
# Create a temp working directory
cwd = tempfile.mkdtemp(dir=__opts__['cachedir'])
win_cwd = True
salt.utils.win_dacl.set_permissions(obj_name=cwd,
principal=runas,
permissions='full_control')
path = salt.utils.files.mkstemp(dir=cwd, suffix=os.path.splitext(source)[1])
if template:
if 'pillarenv' in kwargs or 'pillar' in kwargs:
pillarenv = kwargs.get('pillarenv', __opts__.get('pillarenv'))
kwargs['pillar'] = _gather_pillar(pillarenv, kwargs.get('pillar'))
fn_ = __salt__['cp.get_template'](source,
path,
template,
saltenv,
**kwargs)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
else:
fn_ = __salt__['cp.cache_file'](source, saltenv)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
shutil.copyfile(fn_, path)
if not salt.utils.platform.is_windows():
os.chmod(path, 320)
os.chown(path, __salt__['file.user_to_uid'](runas), -1)
if salt.utils.platform.is_windows() and shell.lower() != 'powershell':
cmd_path = _cmd_quote(path, escape=False)
else:
cmd_path = _cmd_quote(path)
ret = _run(cmd_path + ' ' + six.text_type(args) if args else cmd_path,
cwd=cwd,
stdin=stdin,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def script_retcode(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template='jinja',
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
output_encoding=None,
output_loglevel='debug',
log_callback=None,
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
The script can also be formatted as a template, the default is jinja.
Only evaluate the script return code and do not block for terminal output
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
"arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script_retcode 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh
salt '*' cmd.script_retcode salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script_retcode salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
return script(source=source,
args=args,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)['retcode']
def which(cmd):
'''
Returns the path of an executable available on the minion, None otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.which cat
'''
return salt.utils.path.which(cmd)
def which_bin(cmds):
'''
Returns the first command found in a list of commands
CLI Example:
.. code-block:: bash
salt '*' cmd.which_bin '[pip2, pip, pip-python]'
'''
return salt.utils.path.which_bin(cmds)
def has_exec(cmd):
'''
Returns true if the executable is available on the minion, false otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.has_exec cat
'''
return which(cmd) is not None
def exec_code(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. The stdout will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code ruby 'puts "cheese"'
salt '*' cmd.exec_code ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
return exec_code_all(lang, code, cwd, args, **kwargs)['stdout']
def exec_code_all(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid)
will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code_all ruby 'puts "cheese"'
salt '*' cmd.exec_code_all ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
powershell = lang.lower().startswith("powershell")
if powershell:
codefile = salt.utils.files.mkstemp(suffix=".ps1")
else:
codefile = salt.utils.files.mkstemp()
with salt.utils.files.fopen(codefile, 'w+t', binary=False) as fp_:
fp_.write(salt.utils.stringutils.to_str(code))
if powershell:
cmd = [lang, "-File", codefile]
else:
cmd = [lang, codefile]
if isinstance(args, six.string_types):
cmd.append(args)
elif isinstance(args, list):
cmd += args
ret = run_all(cmd, cwd=cwd, python_shell=False, **kwargs)
os.remove(codefile)
return ret
def tty(device, echo=''):
'''
Echo a string to a specific tty
CLI Example:
.. code-block:: bash
salt '*' cmd.tty tty0 'This is a test'
salt '*' cmd.tty pts3 'This is a test'
'''
if device.startswith('tty'):
teletype = '/dev/{0}'.format(device)
elif device.startswith('pts'):
teletype = '/dev/{0}'.format(device.replace('pts', 'pts/'))
else:
return {'Error': 'The specified device is not a valid TTY'}
try:
with salt.utils.files.fopen(teletype, 'wb') as tty_device:
tty_device.write(salt.utils.stringutils.to_bytes(echo))
return {
'Success': 'Message was successfully echoed to {0}'.format(teletype)
}
except IOError:
return {
'Error': 'Echoing to {0} returned error'.format(teletype)
}
def run_chroot(root,
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=True,
binds=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='quiet',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
.. versionadded:: 2014.7.0
This function runs :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` wrapped
within a chroot, with dev and proc mounted in the chroot
:param str root: Path to the root of the jail to use.
:param str stdin: A string of standard input can be specified for
the command to be run using the ``stdin`` parameter. This can
be useful in cases where sensitive information must be read
from standard input.:
:param str runas: User to run script as.
:param str group: Group to run script as.
:param str shell: Shell to execute under. Defaults to the system
default shell.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:parar str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param list binds: List of directories that will be exported inside
the chroot with the bind option.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_chroot 'some command' env='{"FOO": "bar"}'
:param dict clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output
before it is returned.
:param str umask: The umask (in octal) to use when running the
command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout:
A timeout in seconds for the executed process to return.
:param bool use_vt:
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs. This is experimental.
:param success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' cmd.run_chroot /var/lib/lxc/container_name/rootfs 'sh /tmp/bootstrap.sh'
'''
__salt__['mount.mount'](
os.path.join(root, 'dev'),
'devtmpfs',
fstype='devtmpfs')
__salt__['mount.mount'](
os.path.join(root, 'proc'),
'proc',
fstype='proc')
__salt__['mount.mount'](
os.path.join(root, 'sys'),
'sysfs',
fstype='sysfs')
binds = binds if binds else []
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.mount'](
bind_exported_to,
bind_exported,
opts='default,bind')
# Execute chroot routine
sh_ = '/bin/sh'
if os.path.isfile(os.path.join(root, 'bin/bash')):
sh_ = '/bin/bash'
if isinstance(cmd, (list, tuple)):
cmd = ' '.join([six.text_type(i) for i in cmd])
cmd = 'chroot {0} {1} -c {2}'.format(root, sh_, _cmd_quote(cmd))
run_func = __context__.pop('cmd.run_chroot.func', run_all)
ret = run_func(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
pillarenv=kwargs.get('pillarenv'),
pillar=kwargs.get('pillar'),
use_vt=use_vt,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
bg=bg)
# Kill processes running in the chroot
for i in range(6):
pids = _chroot_pids(root)
if not pids:
break
for pid in pids:
# use sig 15 (TERM) for first 3 attempts, then 9 (KILL)
sig = 15 if i < 3 else 9
os.kill(pid, sig)
if _chroot_pids(root):
log.error('Processes running in chroot could not be killed, '
'filesystem will remain mounted')
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.umount'](bind_exported_to)
__salt__['mount.umount'](os.path.join(root, 'sys'))
__salt__['mount.umount'](os.path.join(root, 'proc'))
__salt__['mount.umount'](os.path.join(root, 'dev'))
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def _is_valid_shell(shell):
'''
Attempts to search for valid shells on a system and
see if a given shell is in the list
'''
if salt.utils.platform.is_windows():
return True # Don't even try this for Windows
shells = '/etc/shells'
available_shells = []
if os.path.exists(shells):
try:
with salt.utils.files.fopen(shells, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
if line.startswith('#'):
continue
else:
available_shells.append(line)
except OSError:
return True
else:
# No known method of determining available shells
return None
if shell in available_shells:
return True
else:
return False
def shells():
'''
Lists the valid shells on this system via the /etc/shells file
.. versionadded:: 2015.5.0
CLI Example::
salt '*' cmd.shells
'''
shells_fn = '/etc/shells'
ret = []
if os.path.exists(shells_fn):
try:
with salt.utils.files.fopen(shells_fn, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
line = line.strip()
if line.startswith('#'):
continue
elif not line:
continue
else:
ret.append(line)
except OSError:
log.error("File '%s' was not found", shells_fn)
return ret
def shell_info(shell, list_modules=False):
'''
.. versionadded:: 2016.11.0
Provides information about a shell or script languages which often use
``#!``. The values returned are dependent on the shell or scripting
languages all return the ``installed``, ``path``, ``version``,
``version_raw``
Args:
shell (str): Name of the shell. Support shells/script languages include
bash, cmd, perl, php, powershell, python, ruby and zsh
list_modules (bool): True to list modules available to the shell.
Currently only lists powershell modules.
Returns:
dict: A dictionary of information about the shell
.. code-block:: python
{'version': '<2 or 3 numeric components dot-separated>',
'version_raw': '<full version string>',
'path': '<full path to binary>',
'installed': <True, False or None>,
'<attribute>': '<attribute value>'}
.. note::
- ``installed`` is always returned, if ``None`` or ``False`` also
returns error and may also return ``stdout`` for diagnostics.
- ``version`` is for use in determine if a shell/script language has a
particular feature set, not for package management.
- The shell must be within the executable search path.
CLI Example:
.. code-block:: bash
salt '*' cmd.shell_info bash
salt '*' cmd.shell_info powershell
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
regex_shells = {
'bash': [r'version (\d\S*)', 'bash', '--version'],
'bash-test-error': [r'versioZ ([-\w.]+)', 'bash', '--version'], # used to test an error result
'bash-test-env': [r'(HOME=.*)', 'bash', '-c', 'declare'], # used to test an error result
'zsh': [r'^zsh (\d\S*)', 'zsh', '--version'],
'tcsh': [r'^tcsh (\d\S*)', 'tcsh', '--version'],
'cmd': [r'Version ([\d.]+)', 'cmd.exe', '/C', 'ver'],
'powershell': [r'PSVersion\s+(\d\S*)', 'powershell', '-NonInteractive', '$PSVersionTable'],
'perl': [r'^(\d\S*)', 'perl', '-e', 'printf "%vd\n", $^V;'],
'python': [r'^Python (\d\S*)', 'python', '-V'],
'ruby': [r'^ruby (\d\S*)', 'ruby', '-v'],
'php': [r'^PHP (\d\S*)', 'php', '-v']
}
# Ensure ret['installed'] always as a value of True, False or None (not sure)
ret = {'installed': False}
if salt.utils.platform.is_windows() and shell == 'powershell':
pw_keys = salt.utils.win_reg.list_keys(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell')
pw_keys.sort(key=int)
if not pw_keys:
return {
'error': 'Unable to locate \'powershell\' Reason: Cannot be '
'found in registry.',
'installed': False,
}
for reg_ver in pw_keys:
install_data = salt.utils.win_reg.read_value(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}'.format(reg_ver),
vname='Install')
if install_data.get('vtype') == 'REG_DWORD' and \
install_data.get('vdata') == 1:
details = salt.utils.win_reg.list_values(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}\\'
'PowerShellEngine'.format(reg_ver))
# reset data, want the newest version details only as powershell
# is backwards compatible
ret = {}
# if all goes well this will become True
ret['installed'] = None
ret['path'] = which('powershell.exe')
for attribute in details:
if attribute['vname'].lower() == '(default)':
continue
elif attribute['vname'].lower() == 'powershellversion':
ret['psversion'] = attribute['vdata']
ret['version_raw'] = attribute['vdata']
elif attribute['vname'].lower() == 'runtimeversion':
ret['crlversion'] = attribute['vdata']
if ret['crlversion'][0].lower() == 'v':
ret['crlversion'] = ret['crlversion'][1::]
elif attribute['vname'].lower() == 'pscompatibleversion':
# reg attribute does not end in s, the powershell
# attribute does
ret['pscompatibleversions'] = \
attribute['vdata'].replace(' ', '').split(',')
else:
# keys are lower case as python is case sensitive the
# registry is not
ret[attribute['vname'].lower()] = attribute['vdata']
else:
if shell not in regex_shells:
return {
'error': 'Salt does not know how to get the version number for '
'{0}'.format(shell),
'installed': None
}
shell_data = regex_shells[shell]
pattern = shell_data.pop(0)
# We need to make sure HOME set, so shells work correctly
# salt-call will general have home set, the salt-minion service may not
# We need to assume ports of unix shells to windows will look after
# themselves in setting HOME as they do it in many different ways
newenv = os.environ
if ('HOME' not in newenv) and (not salt.utils.platform.is_windows()):
newenv['HOME'] = os.path.expanduser('~')
log.debug('HOME environment set to %s', newenv['HOME'])
try:
proc = salt.utils.timed_subprocess.TimedProc(
shell_data,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=10,
env=newenv
)
except (OSError, IOError) as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: {1}'.format(' '.join(shell_data), exc),
'installed': False,
}
try:
proc.run()
except TimedProcTimeoutError as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: Timed out.'.format(' '.join(shell_data)),
'installed': False,
}
ret['path'] = which(shell_data[0])
pattern_result = re.search(pattern, proc.stdout, flags=re.IGNORECASE)
# only set version if we find it, so code later on can deal with it
if pattern_result:
ret['version_raw'] = pattern_result.group(1)
if 'version_raw' in ret:
version_results = re.match(r'(\d[\d.]*)', ret['version_raw'])
if version_results:
ret['installed'] = True
ver_list = version_results.group(1).split('.')[:3]
if len(ver_list) == 1:
ver_list.append('0')
ret['version'] = '.'.join(ver_list[:3])
else:
ret['installed'] = None # Have an unexpected result
# Get a list of the PowerShell modules which are potentially available
# to be imported
if shell == 'powershell' and ret['installed'] and list_modules:
ret['modules'] = salt.utils.powershell.get_modules()
if 'version' not in ret:
ret['error'] = 'The version regex pattern for shell {0}, could not ' \
'find the version string'.format(shell)
ret['stdout'] = proc.stdout # include stdout so they can see the issue
log.error(ret['error'])
return ret
def powershell(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return the output as a dictionary.
Other ``cmd.*`` functions (besides ``cmd.powershell_all``)
return the raw text output of the command. This
function appends ``| ConvertTo-JSON`` to the command and then parses the
JSON into a Python dictionary. If you want the raw textual result of your
PowerShell command you should use ``cmd.run`` with the ``shell=powershell``
option.
For example:
.. code-block:: bash
salt '*' cmd.run '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2016.3.0
.. warning::
This passes the cmd argument directly to PowerShell
without any further processing! Be absolutely sure that you
have properly sanitized the command passed to this function
and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in cases
where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
.. versionadded:: 2016.3.4
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:returns:
:dict: A dictionary of data returned by the powershell command.
CLI Example:
.. code-block:: powershell
salt '*' cmd.powershell "$PSVersionTable.CLRVersion"
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
# ConvertTo-JSON is only available on PowerShell 3.0 and later
psversion = shell_info('powershell')['psversion']
if salt.utils.versions.version_cmp(psversion, '2.0') == 1:
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Put the whole command inside a try / catch block
# Some errors in PowerShell are not "Terminating Errors" and will not be
# caught in a try/catch block. For example, the `Get-WmiObject` command will
# often return a "Non Terminating Error". To fix this, make sure
# `-ErrorAction Stop` is set in the powershell command
cmd = 'try {' + cmd + '} catch { "{}" }'
# Retrieve the response, while overriding shell with 'powershell'
response = run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
try:
return salt.utils.json.loads(response)
except Exception:
log.error("Error converting PowerShell JSON return", exc_info=True)
return {}
def powershell_all(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
quiet=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
force_list=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return a dictionary with a result
field representing the output of the command, as well as other fields
showing us what the PowerShell invocation wrote to ``stderr``, the process
id, and the exit code of the invocation.
This function appends ``| ConvertTo-JSON`` to the command before actually
invoking powershell.
An unquoted empty string is not valid JSON, but it's very normal for the
Powershell output to be exactly that. Therefore, we do not attempt to parse
empty Powershell output (which would result in an exception). Instead we
treat this as a special case and one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field of the return dictionary will be an empty list.
- If the value of the ``force_list`` parameter is ``False``, then the
return dictionary **will not have a result key added to it**. We aren't
setting ``result`` to ``None`` in this case, because ``None`` is the
Python representation of "null" in JSON. (We likewise can't use ``False``
for the equivalent reason.)
If Powershell's output is not an empty string and Python cannot parse its
content, then a ``CommandExecutionError`` exception will be raised.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is other than ``list``
then one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field will be a singleton list with the Python object as its
sole member.
- If the value of the ``force_list`` parameter is ``False``, then the value
of ``result`` will be the unmodified Python object.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is ``list``, then the
value of ``result`` will be the unmodified Python object. The
``force_list`` parameter has no effect in this case.
.. note::
An example of why the ``force_list`` parameter is useful is as
follows: The Powershell command ``dir x | Convert-ToJson`` results in
- no output when x is an empty directory.
- a dictionary object when x contains just one item.
- a list of dictionary objects when x contains multiple items.
By setting ``force_list`` to ``True`` we will always end up with a
list of dictionary items, representing files, no matter how many files
x contains. Conversely, if ``force_list`` is ``False``, we will end
up with no ``result`` key in our return dictionary when x is an empty
directory, and a dictionary object when x contains just one file.
If you want a similar function but with a raw textual result instead of a
Python dictionary, you should use ``cmd.run_all`` in combination with
``shell=powershell``.
The remaining fields in the return dictionary are described in more detail
in the ``Returns`` section.
Example:
.. code-block:: bash
salt '*' cmd.run_all '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run_all 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2018.3.0
.. warning::
This passes the cmd argument directly to PowerShell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param bool force_list: The purpose of this parameter is described in the
preamble of this function's documentation. Default value is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:return: A dictionary with the following entries:
result
For a complete description of this field, please refer to this
function's preamble. **This key will not be added to the dictionary
when force_list is False and Powershell's output is the empty
string.**
stderr
What the PowerShell invocation wrote to ``stderr``.
pid
The process id of the PowerShell invocation
retcode
This is the exit code of the invocation of PowerShell.
If the final execution status (in PowerShell) of our command
(with ``| ConvertTo-JSON`` appended) is ``False`` this should be non-0.
Likewise if PowerShell exited with ``$LASTEXITCODE`` set to some
non-0 value, then ``retcode`` will end up with this value.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "$PSVersionTable.CLRVersion"
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "dir mydirectory" force_list=True
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Retrieve the response, while overriding shell with 'powershell'
response = run_all(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
quiet=quiet,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
stdoutput = response['stdout']
# if stdoutput is the empty string and force_list is True we return an empty list
# Otherwise we return response with no result key
if not stdoutput:
response.pop('stdout')
if force_list:
response['result'] = []
return response
# If we fail to parse stdoutput we will raise an exception
try:
result = salt.utils.json.loads(stdoutput)
except Exception:
err_msg = "cmd.powershell_all " + \
"cannot parse the Powershell output."
response["cmd"] = cmd
raise CommandExecutionError(
message=err_msg,
info=response
)
response.pop("stdout")
if type(result) is not list:
if force_list:
response['result'] = [result]
else:
response['result'] = result
else:
# result type is list so the force_list param has no effect
response['result'] = result
return response
def run_bg(cmd,
cwd=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
timeout=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
.. versionadded: 2016.3.0
Execute the passed command in the background and return it's PID
.. note::
If the init system is systemd and the backgrounded task should run even
if the salt-minion process is restarted, prepend ``systemd-run
--scope`` to the command. This will reparent the process in its own
scope separate from salt-minion, and will not be affected by restarting
the minion service.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Shell to execute under. Defaults to the system default
shell.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_bg 'echo '\''h=\"baz\"'\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_bg 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param int timeout: A timeout in seconds for the executed process to return.
.. warning::
This function does not process commands through a shell unless the
``python_shell`` argument is set to ``True``. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or have the
python_shell=True flag set here.
The use of ``python_shell=True`` means that the shell will accept _any_
input including potentially malicious commands such as 'good_command;rm
-rf /'. Be absolutely certain that you have sanitized your input prior
to using ``python_shell=True``.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_bg "fstrim-all"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_bg template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run_bg "Get-ChildItem C:\\ " shell='powershell'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run_bg cmd='ls -lR / | sed -e s/=/:/g > /tmp/dontwait'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
res = _run(cmd,
stdin=None,
stderr=None,
stdout=None,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
use_vt=None,
bg=True,
with_communicate=False,
rstrip=False,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
umask=umask,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs
)
return {
'pid': res['pid']
}
|
saltstack/salt
|
salt/modules/cmdmod.py
|
_python_shell_default
|
python
|
def _python_shell_default(python_shell, __pub_jid):
'''
Set python_shell default based on remote execution and __opts__['cmd_safe']
'''
try:
# Default to python_shell=True when run directly from remote execution
# system. Cross-module calls won't have a jid.
if __pub_jid and python_shell is None:
return True
elif __opts__.get('cmd_safe', True) is False and python_shell is None:
# Override-switch for python_shell
return True
except NameError:
pass
return python_shell
|
Set python_shell default based on remote execution and __opts__['cmd_safe']
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cmdmod.py#L92-L106
| null |
# -*- coding: utf-8 -*-
'''
A module for shelling out.
Keep in mind that this module is insecure, in that it can give whomever has
access to the master root execution access to all salt minions.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import functools
import glob
import logging
import os
import shutil
import subprocess
import sys
import time
import traceback
import fnmatch
import base64
import re
import tempfile
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.powershell
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.timed_subprocess
import salt.utils.user
import salt.utils.versions
import salt.utils.vt
import salt.utils.win_dacl
import salt.utils.win_reg
import salt.grains.extra
from salt.ext import six
from salt.exceptions import CommandExecutionError, TimedProcTimeoutError, \
SaltInvocationError
from salt.log import LOG_LEVELS
from salt.ext.six.moves import range, zip, map
# Only available on POSIX systems, nonfatal on windows
try:
import pwd
import grp
except ImportError:
pass
if salt.utils.platform.is_windows():
from salt.utils.win_runas import runas as win_runas
from salt.utils.win_functions import escape_argument as _cmd_quote
HAS_WIN_RUNAS = True
else:
from salt.ext.six.moves import shlex_quote as _cmd_quote
HAS_WIN_RUNAS = False
__proxyenabled__ = ['*']
# Define the module's virtual name
__virtualname__ = 'cmd'
# Set up logging
log = logging.getLogger(__name__)
DEFAULT_SHELL = salt.grains.extra.shell()['shell']
# Overwriting the cmd python module makes debugging modules with pdb a bit
# harder so lets do it this way instead.
def __virtual__():
return __virtualname__
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns
the value passed.
'''
if cb_ is not None:
if hasattr(cb_, '__call__'):
return cb_
else:
log.error('log_callback is not callable, ignoring')
return lambda x: x
def _chroot_pids(chroot):
pids = []
for root in glob.glob('/proc/[0-9]*/root'):
try:
link = os.path.realpath(root)
if link.startswith(chroot):
pids.append(int(os.path.basename(
os.path.dirname(root)
)))
except OSError:
pass
return pids
def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):
'''
If template is a valid template engine, process the cmd and cwd through
that engine.
'''
if not template:
return (cmd, cwd)
# render the path as a template using path_template_engine as the engine
if template not in salt.utils.templates.TEMPLATE_REGISTRY:
raise CommandExecutionError(
'Attempted to render file paths with unavailable engine '
'{0}'.format(template)
)
kwargs = {}
kwargs['salt'] = __salt__
if pillarenv is not None or pillar_override is not None:
pillarenv = pillarenv or __opts__['pillarenv']
kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override)
else:
kwargs['pillar'] = __pillar__
kwargs['grains'] = __grains__
kwargs['opts'] = __opts__
kwargs['saltenv'] = saltenv
def _render(contents):
# write out path to temp file
tmp_path_fn = salt.utils.files.mkstemp()
with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(contents))
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
tmp_path_fn,
to_str=True,
**kwargs
)
salt.utils.files.safe_rm(tmp_path_fn)
if not data['result']:
# Failed to render the template
raise CommandExecutionError(
'Failed to execute cmd with error: {0}'.format(
data['data']
)
)
else:
return data['data']
cmd = _render(cmd)
cwd = _render(cwd)
return (cmd, cwd)
def _check_loglevel(level='info'):
'''
Retrieve the level code for use in logging.Logger.log().
'''
try:
level = level.lower()
if level == 'quiet':
return None
else:
return LOG_LEVELS[level]
except (AttributeError, KeyError):
log.error(
'Invalid output_loglevel \'%s\'. Valid levels are: %s. Falling '
'back to \'info\'.',
level, ', '.join(sorted(LOG_LEVELS, reverse=True))
)
return LOG_LEVELS['info']
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
return env
def _gather_pillar(pillarenv, pillar_override):
'''
Whenever a state run starts, gather the pillar data fresh
'''
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
pillar_override=pillar_override,
pillarenv=pillarenv
)
ret = pillar.compile_pillar()
if pillar_override and isinstance(pillar_override, dict):
ret.update(pillar_override)
return ret
def _check_avail(cmd):
'''
Check to see if the given command can be run
'''
if isinstance(cmd, list):
cmd = ' '.join([six.text_type(x) if not isinstance(x, six.string_types) else x
for x in cmd])
bret = True
wret = False
if __salt__['config.get']('cmd_blacklist_glob'):
blist = __salt__['config.get']('cmd_blacklist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# BAD! you are blacklisted
bret = False
if __salt__['config.get']('cmd_whitelist_glob', []):
blist = __salt__['config.get']('cmd_whitelist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# GOOD! You are whitelisted
wret = True
break
else:
# If no whitelist set then alls good!
wret = True
return bret and wret
def _run(cmd,
cwd=None,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
prepend_path=None,
rstrip=True,
template=None,
umask=None,
timeout=None,
with_communicate=True,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
pillarenv=None,
pillar_override=None,
use_vt=False,
password=None,
bg=False,
encoded_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Do the DRY thing and only call subprocess.Popen() once
'''
if 'pillar' in kwargs and not pillar_override:
pillar_override = kwargs['pillar']
if output_loglevel != 'quiet' and _is_valid_shell(shell) is False:
log.warning(
'Attempt to run a shell command with what may be an invalid shell! '
'Check to ensure that the shell <%s> is valid for this user.',
shell
)
output_loglevel = _check_loglevel(output_loglevel)
log_callback = _check_cb(log_callback)
use_sudo = False
if runas is None and '__context__' in globals():
runas = __context__.get('runas')
if password is None and '__context__' in globals():
password = __context__.get('runas_password')
# Set the default working directory to the home directory of the user
# salt-minion is running as. Defaults to home directory of user under which
# the minion is running.
if not cwd:
cwd = os.path.expanduser('~{0}'.format('' if not runas else runas))
# make sure we can access the cwd
# when run from sudo or another environment where the euid is
# changed ~ will expand to the home of the original uid and
# the euid might not have access to it. See issue #1844
if not os.access(cwd, os.R_OK):
cwd = '/'
if salt.utils.platform.is_windows():
cwd = os.path.abspath(os.sep)
else:
# Handle edge cases where numeric/other input is entered, and would be
# yaml-ified into non-string types
cwd = six.text_type(cwd)
if bg:
ignore_retcode = True
use_vt = False
if not salt.utils.platform.is_windows():
if not os.path.isfile(shell) or not os.access(shell, os.X_OK):
msg = 'The shell {0} is not available'.format(shell)
raise CommandExecutionError(msg)
if salt.utils.platform.is_windows() and use_vt: # Memozation so not much overhead
raise CommandExecutionError('VT not available on windows')
if shell.lower().strip() == 'powershell':
# Strip whitespace
if isinstance(cmd, six.string_types):
cmd = cmd.strip()
# If we were called by script(), then fakeout the Windows
# shell to run a Powershell script.
# Else just run a Powershell command.
stack = traceback.extract_stack(limit=2)
# extract_stack() returns a list of tuples.
# The last item in the list [-1] is the current method.
# The third item[2] in each tuple is the name of that method.
if stack[-2][2] == 'script':
cmd = 'Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -File ' + cmd
elif encoded_cmd:
cmd = 'Powershell -NonInteractive -EncodedCommand {0}'.format(cmd)
else:
cmd = 'Powershell -NonInteractive -NoProfile "{0}"'.format(cmd.replace('"', '\\"'))
# munge the cmd and cwd through the template
(cmd, cwd) = _render_cmd(cmd, cwd, template, saltenv, pillarenv, pillar_override)
ret = {}
# If the pub jid is here then this is a remote ex or salt call command and needs to be
# checked if blacklisted
if '__pub_jid' in kwargs:
if not _check_avail(cmd):
raise CommandExecutionError(
'The shell command "{0}" is not permitted'.format(cmd)
)
env = _parse_env(env)
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, six.string_types) else x for x in cmd]
elif isinstance(cmd, six.string_types):
return cmd.strip()
else:
return cmd
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' parameter.
msg = (
'Executing command {0}{1}{0} {2}{3}in directory \'{4}\'{5}'.format(
'\'' if not isinstance(cmd, list) else '',
_get_stripped(cmd),
'as user \'{0}\' '.format(runas) if runas else '',
'in group \'{0}\' '.format(group) if group else '',
cwd,
'. Executing command in the background, no output will be '
'logged.' if bg else ''
)
)
log.info(log_callback(msg))
if runas and salt.utils.platform.is_windows():
if not HAS_WIN_RUNAS:
msg = 'missing salt/utils/win_runas.py'
raise CommandExecutionError(msg)
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(cmd)
return win_runas(cmd, runas, password, cwd)
if runas and salt.utils.platform.is_darwin():
# we need to insert the user simulation into the command itself and not
# just run it from the environment on macOS as that
# method doesn't work properly when run as root for certain commands.
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(map(_cmd_quote, cmd))
cmd = 'su -l {0} -c "cd {1}; {2}"'.format(runas, cwd, cmd)
# set runas to None, because if you try to run `su -l` as well as
# simulate the environment macOS will prompt for the password of the
# user and will cause salt to hang.
runas = None
if runas:
# Save the original command before munging it
try:
pwd.getpwnam(runas)
except KeyError:
raise CommandExecutionError(
'User \'{0}\' is not available'.format(runas)
)
if group:
if salt.utils.platform.is_windows():
msg = 'group is not currently available on Windows'
raise SaltInvocationError(msg)
if not which_bin(['sudo']):
msg = 'group argument requires sudo but not found'
raise CommandExecutionError(msg)
try:
grp.getgrnam(group)
except KeyError:
raise CommandExecutionError(
'Group \'{0}\' is not available'.format(runas)
)
else:
use_sudo = True
if runas or group:
try:
# Getting the environment for the runas user
# Use markers to thwart any stdout noise
# There must be a better way to do this.
import uuid
marker = '<<<' + str(uuid.uuid4()) + '>>>'
marker_b = marker.encode(__salt_system_encoding__)
py_code = (
'import sys, os, itertools; '
'sys.stdout.write(\"' + marker + '\"); '
'sys.stdout.write(\"\\0\".join(itertools.chain(*os.environ.items()))); '
'sys.stdout.write(\"' + marker + '\");'
)
if use_sudo or __grains__['os'] in ['MacOS', 'Darwin']:
env_cmd = ['sudo']
# runas is optional if use_sudo is set.
if runas:
env_cmd.extend(['-u', runas])
if group:
env_cmd.extend(['-g', group])
if shell != DEFAULT_SHELL:
env_cmd.extend(['-s', '--', shell, '-c'])
else:
env_cmd.extend(['-i', '--'])
env_cmd.extend([sys.executable])
elif __grains__['os'] in ['FreeBSD']:
env_cmd = ('su', '-', runas, '-c',
"{0} -c {1}".format(shell, sys.executable))
elif __grains__['os_family'] in ['Solaris']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
elif __grains__['os_family'] in ['AIX']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
else:
env_cmd = ('su', '-s', shell, '-', runas, '-c', sys.executable)
msg = 'env command: {0}'.format(env_cmd)
log.debug(log_callback(msg))
env_bytes, env_encoded_err = subprocess.Popen(
env_cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
).communicate(salt.utils.stringutils.to_bytes(py_code))
marker_count = env_bytes.count(marker_b)
if marker_count == 0:
# Possibly PAM prevented the login
log.error(
'Environment could not be retrieved for user \'%s\': '
'stderr=%r stdout=%r',
runas, env_encoded_err, env_bytes
)
# Ensure that we get an empty env_runas dict below since we
# were not able to get the environment.
env_bytes = b''
elif marker_count != 2:
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\'',
info={'stderr': repr(env_encoded_err),
'stdout': repr(env_bytes)}
)
else:
# Strip the marker
env_bytes = env_bytes.split(marker_b)[1]
if six.PY2:
import itertools
env_runas = dict(itertools.izip(*[iter(env_bytes.split(b'\0'))]*2))
elif six.PY3:
env_runas = dict(list(zip(*[iter(env_bytes.split(b'\0'))]*2)))
env_runas = dict(
(salt.utils.stringutils.to_str(k),
salt.utils.stringutils.to_str(v))
for k, v in six.iteritems(env_runas)
)
env_runas.update(env)
# Fix platforms like Solaris that don't set a USER env var in the
# user's default environment as obtained above.
if env_runas.get('USER') != runas:
env_runas['USER'] = runas
# Fix some corner cases where shelling out to get the user's
# environment returns the wrong home directory.
runas_home = os.path.expanduser('~{0}'.format(runas))
if env_runas.get('HOME') != runas_home:
env_runas['HOME'] = runas_home
env = env_runas
except ValueError as exc:
log.exception('Error raised retrieving environment for user %s', runas)
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\': {1}'.format(
runas, exc
)
)
if reset_system_locale is True:
if not salt.utils.platform.is_windows():
# Default to C!
# Salt only knows how to parse English words
# Don't override if the user has passed LC_ALL
env.setdefault('LC_CTYPE', 'C')
env.setdefault('LC_NUMERIC', 'C')
env.setdefault('LC_TIME', 'C')
env.setdefault('LC_COLLATE', 'C')
env.setdefault('LC_MONETARY', 'C')
env.setdefault('LC_MESSAGES', 'C')
env.setdefault('LC_PAPER', 'C')
env.setdefault('LC_NAME', 'C')
env.setdefault('LC_ADDRESS', 'C')
env.setdefault('LC_TELEPHONE', 'C')
env.setdefault('LC_MEASUREMENT', 'C')
env.setdefault('LC_IDENTIFICATION', 'C')
env.setdefault('LANGUAGE', 'C')
else:
# On Windows set the codepage to US English.
if python_shell:
cmd = 'chcp 437 > nul & ' + cmd
if clean_env:
run_env = env
else:
run_env = os.environ.copy()
run_env.update(env)
if prepend_path:
run_env['PATH'] = ':'.join((prepend_path, run_env['PATH']))
if python_shell is None:
python_shell = False
new_kwargs = {'cwd': cwd,
'shell': python_shell,
'env': run_env if six.PY3 else salt.utils.data.encode(run_env),
'stdin': six.text_type(stdin) if stdin is not None else stdin,
'stdout': stdout,
'stderr': stderr,
'with_communicate': with_communicate,
'timeout': timeout,
'bg': bg,
}
if 'stdin_raw_newlines' in kwargs:
new_kwargs['stdin_raw_newlines'] = kwargs['stdin_raw_newlines']
if umask is not None:
_umask = six.text_type(umask).lstrip('0')
if _umask == '':
msg = 'Zero umask is not allowed.'
raise CommandExecutionError(msg)
try:
_umask = int(_umask, 8)
except ValueError:
raise CommandExecutionError("Invalid umask: '{0}'".format(umask))
else:
_umask = None
if runas or group or umask:
new_kwargs['preexec_fn'] = functools.partial(
salt.utils.user.chugid_and_umask,
runas,
_umask,
group)
if not salt.utils.platform.is_windows():
# close_fds is not supported on Windows platforms if you redirect
# stdin/stdout/stderr
if new_kwargs['shell'] is True:
new_kwargs['executable'] = shell
new_kwargs['close_fds'] = True
if not os.path.isabs(cwd) or not os.path.isdir(cwd):
raise CommandExecutionError(
'Specified cwd \'{0}\' either not absolute or does not exist'
.format(cwd)
)
if python_shell is not True \
and not salt.utils.platform.is_windows() \
and not isinstance(cmd, list):
cmd = salt.utils.args.shlex_split(cmd)
if success_retcodes is None:
success_retcodes = [0]
else:
try:
success_retcodes = [int(i) for i in
salt.utils.args.split_input(
success_retcodes
)]
except ValueError:
raise SaltInvocationError(
'success_retcodes must be a list of integers'
)
if success_stdout is None:
success_stdout = []
else:
try:
success_stdout = [i for i in
salt.utils.args.split_input(
success_stdout
)]
except ValueError:
raise SaltInvocationError(
'success_stdout must be a list of integers'
)
if success_stderr is None:
success_stderr = []
else:
try:
success_stderr = [i for i in
salt.utils.args.split_input(
success_stderr
)]
except ValueError:
raise SaltInvocationError(
'success_stderr must be a list of integers'
)
if not use_vt:
# This is where the magic happens
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **new_kwargs)
except (OSError, IOError) as exc:
msg = (
'Unable to run command \'{0}\' with the context \'{1}\', '
'reason: {2}'.format(
cmd if output_loglevel is not None else 'REDACTED',
new_kwargs,
exc
)
)
raise CommandExecutionError(msg)
try:
proc.run()
except TimedProcTimeoutError as exc:
ret['stdout'] = six.text_type(exc)
ret['stderr'] = ''
ret['retcode'] = None
ret['pid'] = proc.process.pid
# ok return code for timeouts?
ret['retcode'] = 1
return ret
if output_loglevel != 'quiet' and output_encoding is not None:
log.debug('Decoding output from command %s using %s encoding',
cmd, output_encoding)
try:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding)
except TypeError:
# stdout is None
out = ''
except UnicodeDecodeError:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', cmd
)
try:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding)
except TypeError:
# stderr is None
err = ''
except UnicodeDecodeError:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', cmd
)
if rstrip:
if out is not None:
out = out.rstrip()
if err is not None:
err = err.rstrip()
ret['pid'] = proc.process.pid
ret['retcode'] = proc.process.returncode
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
ret['stdout'] = out
ret['stderr'] = err
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
else:
formatted_timeout = ''
if timeout:
formatted_timeout = ' (timeout: {0}s)'.format(timeout)
if output_loglevel is not None:
msg = 'Running {0} in VT{1}'.format(cmd, formatted_timeout)
log.debug(log_callback(msg))
stdout, stderr = '', ''
now = time.time()
if timeout:
will_timeout = now + timeout
else:
will_timeout = -1
try:
proc = salt.utils.vt.Terminal(
cmd,
shell=True,
log_stdout=True,
log_stderr=True,
cwd=cwd,
preexec_fn=new_kwargs.get('preexec_fn', None),
env=run_env,
log_stdin_level=output_loglevel,
log_stdout_level=output_loglevel,
log_stderr_level=output_loglevel,
stream_stdout=True,
stream_stderr=True
)
ret['pid'] = proc.pid
while proc.has_unread_data:
try:
try:
time.sleep(0.5)
try:
cstdout, cstderr = proc.recv()
except IOError:
cstdout, cstderr = '', ''
if cstdout:
stdout += cstdout
else:
cstdout = ''
if cstderr:
stderr += cstderr
else:
cstderr = ''
if timeout and (time.time() > will_timeout):
ret['stderr'] = (
'SALT: Timeout after {0}s\n{1}').format(
timeout, stderr)
ret['retcode'] = None
break
except KeyboardInterrupt:
ret['stderr'] = 'SALT: User break\n{0}'.format(stderr)
ret['retcode'] = 1
break
except salt.utils.vt.TerminalException as exc:
log.error('VT: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
ret = {'retcode': 1, 'pid': '2'}
break
# only set stdout on success as we already mangled in other
# cases
ret['stdout'] = stdout
if not proc.isalive():
# Process terminated, i.e., not canceled by the user or by
# the timeout
ret['stderr'] = stderr
ret['retcode'] = proc.exitstatus
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
ret['pid'] = proc.pid
finally:
proc.close(terminate=True, kill=True)
try:
if ignore_retcode:
__context__['retcode'] = 0
else:
__context__['retcode'] = ret['retcode']
except NameError:
# Ignore the context error during grain generation
pass
# Log the output
if output_loglevel is not None:
if not ignore_retcode and ret['retcode'] != 0:
if output_loglevel < LOG_LEVELS['error']:
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if ret['stdout']:
log.log(output_loglevel, 'stdout: %s', log_callback(ret['stdout']))
if ret['stderr']:
log.log(output_loglevel, 'stderr: %s', log_callback(ret['stderr']))
if ret['retcode']:
log.log(output_loglevel, 'retcode: %s', ret['retcode'])
return ret
def _run_quiet(cmd,
cwd=None,
stdin=None,
output_encoding=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)['stdout']
def _run_all_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
output_encoding=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup.
Returns a dict of return data.
output_loglevel argument is ignored. This is here for when we alias
cmd.run_all directly to _run_all_quiet in certain chicken-and-egg
situations where modules need to work both before and after
the __salt__ dictionary is populated (cf dracr.py)
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)
def run(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
encoded_cmd=False,
raise_err=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
Execute the passed command and return the output as a string
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run 'echo '\''h=\"baz\"'\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If ``False``, let python handle the positional
arguments. Set to ``True`` to use shell features, such as pipes or
redirection.
:param bool bg: If ``True``, run command in background and do not await or
deliver it's results
.. versionadded:: 2016.3.0
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
:param bool raise_err: If ``True`` and the command has a nonzero exit code,
a CommandExecutionError exception will be raised.
.. warning::
This function does not process commands through a shell
unless the python_shell flag is set to True. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or
have the python_shell=True flag set here.
The use of python_shell=True means that the shell will accept _any_ input
including potentially malicious commands such as 'good_command;rm -rf /'.
Be absolutely certain that you have sanitized your input prior to using
python_shell=True
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run cmd='sed -e s/=/:/g'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
log_callback = _check_cb(log_callback)
lvl = _check_loglevel(output_loglevel)
if lvl is not None:
if not ignore_retcode and ret['retcode'] != 0:
if lvl < LOG_LEVELS['error']:
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if raise_err:
raise CommandExecutionError(
log_callback(ret['stdout'] if not hide_output else '')
)
log.log(lvl, 'output: %s', log_callback(ret['stdout']))
return ret['stdout'] if not hide_output else ''
def shell(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return the output as a string.
.. versionadded:: 2015.5.0
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.shell 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param int shell: Shell to execute under. Defaults to the system default
shell.
:param bool bg: If True, run command in background and do not await or
deliver its results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.shell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
.. warning::
This passes the cmd argument directly to the shell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.shell "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.shell template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.shell "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.shell "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.shell cmd='sed -e s/=/:/g'
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
return run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
def run_stdout(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command, and only return the standard out
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stdout 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stdout template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stdout "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stdout'] if not hide_output else ''
def run_stderr(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command and only return the standard error
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stderr 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stderr 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stderr "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stderr template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stderr "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stderr'] if not hide_output else ''
def run_all(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
redirect_stderr=False,
password=None,
encoded_cmd=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return a dict of return data
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_all 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
.. versionadded:: 2018.3.0
:param bool redirect_stderr: If set to ``True``, then stderr will be
redirected to stdout. This is helpful for cases where obtaining both
the retcode and output is desired, but it is not desired to have the
output separated into both stdout and stderr.
.. versionadded:: 2015.8.2
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param bool bg: If ``True``, run command in background and do not await or
deliver its results
.. versionadded:: 2016.3.6
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_all "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_all template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_all "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=stderr,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def retcode(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a shell command and return the command's return code.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.retcode 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.retcode 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:rtype: int
:rtype: None
:returns: Return Code as an int or None if there was an exception.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.retcode "file /bin/bash"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.retcode template=jinja "file {{grains.pythonpath[0]}}/python"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.retcode "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['retcode']
def _retcode_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Helper for running commands quietly for minion startup. Returns same as
the retcode() function.
'''
return retcode(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stderr,
success_stderr=success_stderr,
**kwargs)
def script(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
saltenv='base',
use_vt=False,
bg=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
.. code-block:: bash
salt myminion cmd.script salt://foo.sh "arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param bool bg: If True, run script in background and do not await or
deliver it's results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh
salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
def _cleanup_tempfile(path):
try:
__salt__['file.remove'](path)
except (SaltInvocationError, CommandExecutionError) as exc:
log.error(
'cmd.script: Unable to clean tempfile \'%s\': %s',
path, exc, exc_info_on_loglevel=logging.DEBUG
)
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
win_cwd = False
if salt.utils.platform.is_windows() and runas and cwd is None:
# Create a temp working directory
cwd = tempfile.mkdtemp(dir=__opts__['cachedir'])
win_cwd = True
salt.utils.win_dacl.set_permissions(obj_name=cwd,
principal=runas,
permissions='full_control')
path = salt.utils.files.mkstemp(dir=cwd, suffix=os.path.splitext(source)[1])
if template:
if 'pillarenv' in kwargs or 'pillar' in kwargs:
pillarenv = kwargs.get('pillarenv', __opts__.get('pillarenv'))
kwargs['pillar'] = _gather_pillar(pillarenv, kwargs.get('pillar'))
fn_ = __salt__['cp.get_template'](source,
path,
template,
saltenv,
**kwargs)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
else:
fn_ = __salt__['cp.cache_file'](source, saltenv)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
shutil.copyfile(fn_, path)
if not salt.utils.platform.is_windows():
os.chmod(path, 320)
os.chown(path, __salt__['file.user_to_uid'](runas), -1)
if salt.utils.platform.is_windows() and shell.lower() != 'powershell':
cmd_path = _cmd_quote(path, escape=False)
else:
cmd_path = _cmd_quote(path)
ret = _run(cmd_path + ' ' + six.text_type(args) if args else cmd_path,
cwd=cwd,
stdin=stdin,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def script_retcode(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template='jinja',
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
output_encoding=None,
output_loglevel='debug',
log_callback=None,
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
The script can also be formatted as a template, the default is jinja.
Only evaluate the script return code and do not block for terminal output
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
"arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script_retcode 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh
salt '*' cmd.script_retcode salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script_retcode salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
return script(source=source,
args=args,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)['retcode']
def which(cmd):
'''
Returns the path of an executable available on the minion, None otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.which cat
'''
return salt.utils.path.which(cmd)
def which_bin(cmds):
'''
Returns the first command found in a list of commands
CLI Example:
.. code-block:: bash
salt '*' cmd.which_bin '[pip2, pip, pip-python]'
'''
return salt.utils.path.which_bin(cmds)
def has_exec(cmd):
'''
Returns true if the executable is available on the minion, false otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.has_exec cat
'''
return which(cmd) is not None
def exec_code(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. The stdout will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code ruby 'puts "cheese"'
salt '*' cmd.exec_code ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
return exec_code_all(lang, code, cwd, args, **kwargs)['stdout']
def exec_code_all(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid)
will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code_all ruby 'puts "cheese"'
salt '*' cmd.exec_code_all ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
powershell = lang.lower().startswith("powershell")
if powershell:
codefile = salt.utils.files.mkstemp(suffix=".ps1")
else:
codefile = salt.utils.files.mkstemp()
with salt.utils.files.fopen(codefile, 'w+t', binary=False) as fp_:
fp_.write(salt.utils.stringutils.to_str(code))
if powershell:
cmd = [lang, "-File", codefile]
else:
cmd = [lang, codefile]
if isinstance(args, six.string_types):
cmd.append(args)
elif isinstance(args, list):
cmd += args
ret = run_all(cmd, cwd=cwd, python_shell=False, **kwargs)
os.remove(codefile)
return ret
def tty(device, echo=''):
'''
Echo a string to a specific tty
CLI Example:
.. code-block:: bash
salt '*' cmd.tty tty0 'This is a test'
salt '*' cmd.tty pts3 'This is a test'
'''
if device.startswith('tty'):
teletype = '/dev/{0}'.format(device)
elif device.startswith('pts'):
teletype = '/dev/{0}'.format(device.replace('pts', 'pts/'))
else:
return {'Error': 'The specified device is not a valid TTY'}
try:
with salt.utils.files.fopen(teletype, 'wb') as tty_device:
tty_device.write(salt.utils.stringutils.to_bytes(echo))
return {
'Success': 'Message was successfully echoed to {0}'.format(teletype)
}
except IOError:
return {
'Error': 'Echoing to {0} returned error'.format(teletype)
}
def run_chroot(root,
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=True,
binds=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='quiet',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
.. versionadded:: 2014.7.0
This function runs :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` wrapped
within a chroot, with dev and proc mounted in the chroot
:param str root: Path to the root of the jail to use.
:param str stdin: A string of standard input can be specified for
the command to be run using the ``stdin`` parameter. This can
be useful in cases where sensitive information must be read
from standard input.:
:param str runas: User to run script as.
:param str group: Group to run script as.
:param str shell: Shell to execute under. Defaults to the system
default shell.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:parar str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param list binds: List of directories that will be exported inside
the chroot with the bind option.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_chroot 'some command' env='{"FOO": "bar"}'
:param dict clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output
before it is returned.
:param str umask: The umask (in octal) to use when running the
command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout:
A timeout in seconds for the executed process to return.
:param bool use_vt:
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs. This is experimental.
:param success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' cmd.run_chroot /var/lib/lxc/container_name/rootfs 'sh /tmp/bootstrap.sh'
'''
__salt__['mount.mount'](
os.path.join(root, 'dev'),
'devtmpfs',
fstype='devtmpfs')
__salt__['mount.mount'](
os.path.join(root, 'proc'),
'proc',
fstype='proc')
__salt__['mount.mount'](
os.path.join(root, 'sys'),
'sysfs',
fstype='sysfs')
binds = binds if binds else []
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.mount'](
bind_exported_to,
bind_exported,
opts='default,bind')
# Execute chroot routine
sh_ = '/bin/sh'
if os.path.isfile(os.path.join(root, 'bin/bash')):
sh_ = '/bin/bash'
if isinstance(cmd, (list, tuple)):
cmd = ' '.join([six.text_type(i) for i in cmd])
cmd = 'chroot {0} {1} -c {2}'.format(root, sh_, _cmd_quote(cmd))
run_func = __context__.pop('cmd.run_chroot.func', run_all)
ret = run_func(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
pillarenv=kwargs.get('pillarenv'),
pillar=kwargs.get('pillar'),
use_vt=use_vt,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
bg=bg)
# Kill processes running in the chroot
for i in range(6):
pids = _chroot_pids(root)
if not pids:
break
for pid in pids:
# use sig 15 (TERM) for first 3 attempts, then 9 (KILL)
sig = 15 if i < 3 else 9
os.kill(pid, sig)
if _chroot_pids(root):
log.error('Processes running in chroot could not be killed, '
'filesystem will remain mounted')
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.umount'](bind_exported_to)
__salt__['mount.umount'](os.path.join(root, 'sys'))
__salt__['mount.umount'](os.path.join(root, 'proc'))
__salt__['mount.umount'](os.path.join(root, 'dev'))
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def _is_valid_shell(shell):
'''
Attempts to search for valid shells on a system and
see if a given shell is in the list
'''
if salt.utils.platform.is_windows():
return True # Don't even try this for Windows
shells = '/etc/shells'
available_shells = []
if os.path.exists(shells):
try:
with salt.utils.files.fopen(shells, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
if line.startswith('#'):
continue
else:
available_shells.append(line)
except OSError:
return True
else:
# No known method of determining available shells
return None
if shell in available_shells:
return True
else:
return False
def shells():
'''
Lists the valid shells on this system via the /etc/shells file
.. versionadded:: 2015.5.0
CLI Example::
salt '*' cmd.shells
'''
shells_fn = '/etc/shells'
ret = []
if os.path.exists(shells_fn):
try:
with salt.utils.files.fopen(shells_fn, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
line = line.strip()
if line.startswith('#'):
continue
elif not line:
continue
else:
ret.append(line)
except OSError:
log.error("File '%s' was not found", shells_fn)
return ret
def shell_info(shell, list_modules=False):
'''
.. versionadded:: 2016.11.0
Provides information about a shell or script languages which often use
``#!``. The values returned are dependent on the shell or scripting
languages all return the ``installed``, ``path``, ``version``,
``version_raw``
Args:
shell (str): Name of the shell. Support shells/script languages include
bash, cmd, perl, php, powershell, python, ruby and zsh
list_modules (bool): True to list modules available to the shell.
Currently only lists powershell modules.
Returns:
dict: A dictionary of information about the shell
.. code-block:: python
{'version': '<2 or 3 numeric components dot-separated>',
'version_raw': '<full version string>',
'path': '<full path to binary>',
'installed': <True, False or None>,
'<attribute>': '<attribute value>'}
.. note::
- ``installed`` is always returned, if ``None`` or ``False`` also
returns error and may also return ``stdout`` for diagnostics.
- ``version`` is for use in determine if a shell/script language has a
particular feature set, not for package management.
- The shell must be within the executable search path.
CLI Example:
.. code-block:: bash
salt '*' cmd.shell_info bash
salt '*' cmd.shell_info powershell
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
regex_shells = {
'bash': [r'version (\d\S*)', 'bash', '--version'],
'bash-test-error': [r'versioZ ([-\w.]+)', 'bash', '--version'], # used to test an error result
'bash-test-env': [r'(HOME=.*)', 'bash', '-c', 'declare'], # used to test an error result
'zsh': [r'^zsh (\d\S*)', 'zsh', '--version'],
'tcsh': [r'^tcsh (\d\S*)', 'tcsh', '--version'],
'cmd': [r'Version ([\d.]+)', 'cmd.exe', '/C', 'ver'],
'powershell': [r'PSVersion\s+(\d\S*)', 'powershell', '-NonInteractive', '$PSVersionTable'],
'perl': [r'^(\d\S*)', 'perl', '-e', 'printf "%vd\n", $^V;'],
'python': [r'^Python (\d\S*)', 'python', '-V'],
'ruby': [r'^ruby (\d\S*)', 'ruby', '-v'],
'php': [r'^PHP (\d\S*)', 'php', '-v']
}
# Ensure ret['installed'] always as a value of True, False or None (not sure)
ret = {'installed': False}
if salt.utils.platform.is_windows() and shell == 'powershell':
pw_keys = salt.utils.win_reg.list_keys(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell')
pw_keys.sort(key=int)
if not pw_keys:
return {
'error': 'Unable to locate \'powershell\' Reason: Cannot be '
'found in registry.',
'installed': False,
}
for reg_ver in pw_keys:
install_data = salt.utils.win_reg.read_value(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}'.format(reg_ver),
vname='Install')
if install_data.get('vtype') == 'REG_DWORD' and \
install_data.get('vdata') == 1:
details = salt.utils.win_reg.list_values(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}\\'
'PowerShellEngine'.format(reg_ver))
# reset data, want the newest version details only as powershell
# is backwards compatible
ret = {}
# if all goes well this will become True
ret['installed'] = None
ret['path'] = which('powershell.exe')
for attribute in details:
if attribute['vname'].lower() == '(default)':
continue
elif attribute['vname'].lower() == 'powershellversion':
ret['psversion'] = attribute['vdata']
ret['version_raw'] = attribute['vdata']
elif attribute['vname'].lower() == 'runtimeversion':
ret['crlversion'] = attribute['vdata']
if ret['crlversion'][0].lower() == 'v':
ret['crlversion'] = ret['crlversion'][1::]
elif attribute['vname'].lower() == 'pscompatibleversion':
# reg attribute does not end in s, the powershell
# attribute does
ret['pscompatibleversions'] = \
attribute['vdata'].replace(' ', '').split(',')
else:
# keys are lower case as python is case sensitive the
# registry is not
ret[attribute['vname'].lower()] = attribute['vdata']
else:
if shell not in regex_shells:
return {
'error': 'Salt does not know how to get the version number for '
'{0}'.format(shell),
'installed': None
}
shell_data = regex_shells[shell]
pattern = shell_data.pop(0)
# We need to make sure HOME set, so shells work correctly
# salt-call will general have home set, the salt-minion service may not
# We need to assume ports of unix shells to windows will look after
# themselves in setting HOME as they do it in many different ways
newenv = os.environ
if ('HOME' not in newenv) and (not salt.utils.platform.is_windows()):
newenv['HOME'] = os.path.expanduser('~')
log.debug('HOME environment set to %s', newenv['HOME'])
try:
proc = salt.utils.timed_subprocess.TimedProc(
shell_data,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=10,
env=newenv
)
except (OSError, IOError) as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: {1}'.format(' '.join(shell_data), exc),
'installed': False,
}
try:
proc.run()
except TimedProcTimeoutError as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: Timed out.'.format(' '.join(shell_data)),
'installed': False,
}
ret['path'] = which(shell_data[0])
pattern_result = re.search(pattern, proc.stdout, flags=re.IGNORECASE)
# only set version if we find it, so code later on can deal with it
if pattern_result:
ret['version_raw'] = pattern_result.group(1)
if 'version_raw' in ret:
version_results = re.match(r'(\d[\d.]*)', ret['version_raw'])
if version_results:
ret['installed'] = True
ver_list = version_results.group(1).split('.')[:3]
if len(ver_list) == 1:
ver_list.append('0')
ret['version'] = '.'.join(ver_list[:3])
else:
ret['installed'] = None # Have an unexpected result
# Get a list of the PowerShell modules which are potentially available
# to be imported
if shell == 'powershell' and ret['installed'] and list_modules:
ret['modules'] = salt.utils.powershell.get_modules()
if 'version' not in ret:
ret['error'] = 'The version regex pattern for shell {0}, could not ' \
'find the version string'.format(shell)
ret['stdout'] = proc.stdout # include stdout so they can see the issue
log.error(ret['error'])
return ret
def powershell(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return the output as a dictionary.
Other ``cmd.*`` functions (besides ``cmd.powershell_all``)
return the raw text output of the command. This
function appends ``| ConvertTo-JSON`` to the command and then parses the
JSON into a Python dictionary. If you want the raw textual result of your
PowerShell command you should use ``cmd.run`` with the ``shell=powershell``
option.
For example:
.. code-block:: bash
salt '*' cmd.run '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2016.3.0
.. warning::
This passes the cmd argument directly to PowerShell
without any further processing! Be absolutely sure that you
have properly sanitized the command passed to this function
and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in cases
where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
.. versionadded:: 2016.3.4
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:returns:
:dict: A dictionary of data returned by the powershell command.
CLI Example:
.. code-block:: powershell
salt '*' cmd.powershell "$PSVersionTable.CLRVersion"
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
# ConvertTo-JSON is only available on PowerShell 3.0 and later
psversion = shell_info('powershell')['psversion']
if salt.utils.versions.version_cmp(psversion, '2.0') == 1:
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Put the whole command inside a try / catch block
# Some errors in PowerShell are not "Terminating Errors" and will not be
# caught in a try/catch block. For example, the `Get-WmiObject` command will
# often return a "Non Terminating Error". To fix this, make sure
# `-ErrorAction Stop` is set in the powershell command
cmd = 'try {' + cmd + '} catch { "{}" }'
# Retrieve the response, while overriding shell with 'powershell'
response = run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
try:
return salt.utils.json.loads(response)
except Exception:
log.error("Error converting PowerShell JSON return", exc_info=True)
return {}
def powershell_all(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
quiet=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
force_list=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return a dictionary with a result
field representing the output of the command, as well as other fields
showing us what the PowerShell invocation wrote to ``stderr``, the process
id, and the exit code of the invocation.
This function appends ``| ConvertTo-JSON`` to the command before actually
invoking powershell.
An unquoted empty string is not valid JSON, but it's very normal for the
Powershell output to be exactly that. Therefore, we do not attempt to parse
empty Powershell output (which would result in an exception). Instead we
treat this as a special case and one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field of the return dictionary will be an empty list.
- If the value of the ``force_list`` parameter is ``False``, then the
return dictionary **will not have a result key added to it**. We aren't
setting ``result`` to ``None`` in this case, because ``None`` is the
Python representation of "null" in JSON. (We likewise can't use ``False``
for the equivalent reason.)
If Powershell's output is not an empty string and Python cannot parse its
content, then a ``CommandExecutionError`` exception will be raised.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is other than ``list``
then one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field will be a singleton list with the Python object as its
sole member.
- If the value of the ``force_list`` parameter is ``False``, then the value
of ``result`` will be the unmodified Python object.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is ``list``, then the
value of ``result`` will be the unmodified Python object. The
``force_list`` parameter has no effect in this case.
.. note::
An example of why the ``force_list`` parameter is useful is as
follows: The Powershell command ``dir x | Convert-ToJson`` results in
- no output when x is an empty directory.
- a dictionary object when x contains just one item.
- a list of dictionary objects when x contains multiple items.
By setting ``force_list`` to ``True`` we will always end up with a
list of dictionary items, representing files, no matter how many files
x contains. Conversely, if ``force_list`` is ``False``, we will end
up with no ``result`` key in our return dictionary when x is an empty
directory, and a dictionary object when x contains just one file.
If you want a similar function but with a raw textual result instead of a
Python dictionary, you should use ``cmd.run_all`` in combination with
``shell=powershell``.
The remaining fields in the return dictionary are described in more detail
in the ``Returns`` section.
Example:
.. code-block:: bash
salt '*' cmd.run_all '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run_all 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2018.3.0
.. warning::
This passes the cmd argument directly to PowerShell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param bool force_list: The purpose of this parameter is described in the
preamble of this function's documentation. Default value is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:return: A dictionary with the following entries:
result
For a complete description of this field, please refer to this
function's preamble. **This key will not be added to the dictionary
when force_list is False and Powershell's output is the empty
string.**
stderr
What the PowerShell invocation wrote to ``stderr``.
pid
The process id of the PowerShell invocation
retcode
This is the exit code of the invocation of PowerShell.
If the final execution status (in PowerShell) of our command
(with ``| ConvertTo-JSON`` appended) is ``False`` this should be non-0.
Likewise if PowerShell exited with ``$LASTEXITCODE`` set to some
non-0 value, then ``retcode`` will end up with this value.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "$PSVersionTable.CLRVersion"
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "dir mydirectory" force_list=True
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Retrieve the response, while overriding shell with 'powershell'
response = run_all(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
quiet=quiet,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
stdoutput = response['stdout']
# if stdoutput is the empty string and force_list is True we return an empty list
# Otherwise we return response with no result key
if not stdoutput:
response.pop('stdout')
if force_list:
response['result'] = []
return response
# If we fail to parse stdoutput we will raise an exception
try:
result = salt.utils.json.loads(stdoutput)
except Exception:
err_msg = "cmd.powershell_all " + \
"cannot parse the Powershell output."
response["cmd"] = cmd
raise CommandExecutionError(
message=err_msg,
info=response
)
response.pop("stdout")
if type(result) is not list:
if force_list:
response['result'] = [result]
else:
response['result'] = result
else:
# result type is list so the force_list param has no effect
response['result'] = result
return response
def run_bg(cmd,
cwd=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
timeout=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
.. versionadded: 2016.3.0
Execute the passed command in the background and return it's PID
.. note::
If the init system is systemd and the backgrounded task should run even
if the salt-minion process is restarted, prepend ``systemd-run
--scope`` to the command. This will reparent the process in its own
scope separate from salt-minion, and will not be affected by restarting
the minion service.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Shell to execute under. Defaults to the system default
shell.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_bg 'echo '\''h=\"baz\"'\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_bg 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param int timeout: A timeout in seconds for the executed process to return.
.. warning::
This function does not process commands through a shell unless the
``python_shell`` argument is set to ``True``. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or have the
python_shell=True flag set here.
The use of ``python_shell=True`` means that the shell will accept _any_
input including potentially malicious commands such as 'good_command;rm
-rf /'. Be absolutely certain that you have sanitized your input prior
to using ``python_shell=True``.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_bg "fstrim-all"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_bg template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run_bg "Get-ChildItem C:\\ " shell='powershell'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run_bg cmd='ls -lR / | sed -e s/=/:/g > /tmp/dontwait'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
res = _run(cmd,
stdin=None,
stderr=None,
stdout=None,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
use_vt=None,
bg=True,
with_communicate=False,
rstrip=False,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
umask=umask,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs
)
return {
'pid': res['pid']
}
|
saltstack/salt
|
salt/modules/cmdmod.py
|
_render_cmd
|
python
|
def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):
'''
If template is a valid template engine, process the cmd and cwd through
that engine.
'''
if not template:
return (cmd, cwd)
# render the path as a template using path_template_engine as the engine
if template not in salt.utils.templates.TEMPLATE_REGISTRY:
raise CommandExecutionError(
'Attempted to render file paths with unavailable engine '
'{0}'.format(template)
)
kwargs = {}
kwargs['salt'] = __salt__
if pillarenv is not None or pillar_override is not None:
pillarenv = pillarenv or __opts__['pillarenv']
kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override)
else:
kwargs['pillar'] = __pillar__
kwargs['grains'] = __grains__
kwargs['opts'] = __opts__
kwargs['saltenv'] = saltenv
def _render(contents):
# write out path to temp file
tmp_path_fn = salt.utils.files.mkstemp()
with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(contents))
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
tmp_path_fn,
to_str=True,
**kwargs
)
salt.utils.files.safe_rm(tmp_path_fn)
if not data['result']:
# Failed to render the template
raise CommandExecutionError(
'Failed to execute cmd with error: {0}'.format(
data['data']
)
)
else:
return data['data']
cmd = _render(cmd)
cwd = _render(cwd)
return (cmd, cwd)
|
If template is a valid template engine, process the cmd and cwd through
that engine.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cmdmod.py#L123-L172
| null |
# -*- coding: utf-8 -*-
'''
A module for shelling out.
Keep in mind that this module is insecure, in that it can give whomever has
access to the master root execution access to all salt minions.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import functools
import glob
import logging
import os
import shutil
import subprocess
import sys
import time
import traceback
import fnmatch
import base64
import re
import tempfile
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.powershell
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.timed_subprocess
import salt.utils.user
import salt.utils.versions
import salt.utils.vt
import salt.utils.win_dacl
import salt.utils.win_reg
import salt.grains.extra
from salt.ext import six
from salt.exceptions import CommandExecutionError, TimedProcTimeoutError, \
SaltInvocationError
from salt.log import LOG_LEVELS
from salt.ext.six.moves import range, zip, map
# Only available on POSIX systems, nonfatal on windows
try:
import pwd
import grp
except ImportError:
pass
if salt.utils.platform.is_windows():
from salt.utils.win_runas import runas as win_runas
from salt.utils.win_functions import escape_argument as _cmd_quote
HAS_WIN_RUNAS = True
else:
from salt.ext.six.moves import shlex_quote as _cmd_quote
HAS_WIN_RUNAS = False
__proxyenabled__ = ['*']
# Define the module's virtual name
__virtualname__ = 'cmd'
# Set up logging
log = logging.getLogger(__name__)
DEFAULT_SHELL = salt.grains.extra.shell()['shell']
# Overwriting the cmd python module makes debugging modules with pdb a bit
# harder so lets do it this way instead.
def __virtual__():
return __virtualname__
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns
the value passed.
'''
if cb_ is not None:
if hasattr(cb_, '__call__'):
return cb_
else:
log.error('log_callback is not callable, ignoring')
return lambda x: x
def _python_shell_default(python_shell, __pub_jid):
'''
Set python_shell default based on remote execution and __opts__['cmd_safe']
'''
try:
# Default to python_shell=True when run directly from remote execution
# system. Cross-module calls won't have a jid.
if __pub_jid and python_shell is None:
return True
elif __opts__.get('cmd_safe', True) is False and python_shell is None:
# Override-switch for python_shell
return True
except NameError:
pass
return python_shell
def _chroot_pids(chroot):
pids = []
for root in glob.glob('/proc/[0-9]*/root'):
try:
link = os.path.realpath(root)
if link.startswith(chroot):
pids.append(int(os.path.basename(
os.path.dirname(root)
)))
except OSError:
pass
return pids
def _check_loglevel(level='info'):
'''
Retrieve the level code for use in logging.Logger.log().
'''
try:
level = level.lower()
if level == 'quiet':
return None
else:
return LOG_LEVELS[level]
except (AttributeError, KeyError):
log.error(
'Invalid output_loglevel \'%s\'. Valid levels are: %s. Falling '
'back to \'info\'.',
level, ', '.join(sorted(LOG_LEVELS, reverse=True))
)
return LOG_LEVELS['info']
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
return env
def _gather_pillar(pillarenv, pillar_override):
'''
Whenever a state run starts, gather the pillar data fresh
'''
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
pillar_override=pillar_override,
pillarenv=pillarenv
)
ret = pillar.compile_pillar()
if pillar_override and isinstance(pillar_override, dict):
ret.update(pillar_override)
return ret
def _check_avail(cmd):
'''
Check to see if the given command can be run
'''
if isinstance(cmd, list):
cmd = ' '.join([six.text_type(x) if not isinstance(x, six.string_types) else x
for x in cmd])
bret = True
wret = False
if __salt__['config.get']('cmd_blacklist_glob'):
blist = __salt__['config.get']('cmd_blacklist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# BAD! you are blacklisted
bret = False
if __salt__['config.get']('cmd_whitelist_glob', []):
blist = __salt__['config.get']('cmd_whitelist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# GOOD! You are whitelisted
wret = True
break
else:
# If no whitelist set then alls good!
wret = True
return bret and wret
def _run(cmd,
cwd=None,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
prepend_path=None,
rstrip=True,
template=None,
umask=None,
timeout=None,
with_communicate=True,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
pillarenv=None,
pillar_override=None,
use_vt=False,
password=None,
bg=False,
encoded_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Do the DRY thing and only call subprocess.Popen() once
'''
if 'pillar' in kwargs and not pillar_override:
pillar_override = kwargs['pillar']
if output_loglevel != 'quiet' and _is_valid_shell(shell) is False:
log.warning(
'Attempt to run a shell command with what may be an invalid shell! '
'Check to ensure that the shell <%s> is valid for this user.',
shell
)
output_loglevel = _check_loglevel(output_loglevel)
log_callback = _check_cb(log_callback)
use_sudo = False
if runas is None and '__context__' in globals():
runas = __context__.get('runas')
if password is None and '__context__' in globals():
password = __context__.get('runas_password')
# Set the default working directory to the home directory of the user
# salt-minion is running as. Defaults to home directory of user under which
# the minion is running.
if not cwd:
cwd = os.path.expanduser('~{0}'.format('' if not runas else runas))
# make sure we can access the cwd
# when run from sudo or another environment where the euid is
# changed ~ will expand to the home of the original uid and
# the euid might not have access to it. See issue #1844
if not os.access(cwd, os.R_OK):
cwd = '/'
if salt.utils.platform.is_windows():
cwd = os.path.abspath(os.sep)
else:
# Handle edge cases where numeric/other input is entered, and would be
# yaml-ified into non-string types
cwd = six.text_type(cwd)
if bg:
ignore_retcode = True
use_vt = False
if not salt.utils.platform.is_windows():
if not os.path.isfile(shell) or not os.access(shell, os.X_OK):
msg = 'The shell {0} is not available'.format(shell)
raise CommandExecutionError(msg)
if salt.utils.platform.is_windows() and use_vt: # Memozation so not much overhead
raise CommandExecutionError('VT not available on windows')
if shell.lower().strip() == 'powershell':
# Strip whitespace
if isinstance(cmd, six.string_types):
cmd = cmd.strip()
# If we were called by script(), then fakeout the Windows
# shell to run a Powershell script.
# Else just run a Powershell command.
stack = traceback.extract_stack(limit=2)
# extract_stack() returns a list of tuples.
# The last item in the list [-1] is the current method.
# The third item[2] in each tuple is the name of that method.
if stack[-2][2] == 'script':
cmd = 'Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -File ' + cmd
elif encoded_cmd:
cmd = 'Powershell -NonInteractive -EncodedCommand {0}'.format(cmd)
else:
cmd = 'Powershell -NonInteractive -NoProfile "{0}"'.format(cmd.replace('"', '\\"'))
# munge the cmd and cwd through the template
(cmd, cwd) = _render_cmd(cmd, cwd, template, saltenv, pillarenv, pillar_override)
ret = {}
# If the pub jid is here then this is a remote ex or salt call command and needs to be
# checked if blacklisted
if '__pub_jid' in kwargs:
if not _check_avail(cmd):
raise CommandExecutionError(
'The shell command "{0}" is not permitted'.format(cmd)
)
env = _parse_env(env)
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, six.string_types) else x for x in cmd]
elif isinstance(cmd, six.string_types):
return cmd.strip()
else:
return cmd
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' parameter.
msg = (
'Executing command {0}{1}{0} {2}{3}in directory \'{4}\'{5}'.format(
'\'' if not isinstance(cmd, list) else '',
_get_stripped(cmd),
'as user \'{0}\' '.format(runas) if runas else '',
'in group \'{0}\' '.format(group) if group else '',
cwd,
'. Executing command in the background, no output will be '
'logged.' if bg else ''
)
)
log.info(log_callback(msg))
if runas and salt.utils.platform.is_windows():
if not HAS_WIN_RUNAS:
msg = 'missing salt/utils/win_runas.py'
raise CommandExecutionError(msg)
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(cmd)
return win_runas(cmd, runas, password, cwd)
if runas and salt.utils.platform.is_darwin():
# we need to insert the user simulation into the command itself and not
# just run it from the environment on macOS as that
# method doesn't work properly when run as root for certain commands.
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(map(_cmd_quote, cmd))
cmd = 'su -l {0} -c "cd {1}; {2}"'.format(runas, cwd, cmd)
# set runas to None, because if you try to run `su -l` as well as
# simulate the environment macOS will prompt for the password of the
# user and will cause salt to hang.
runas = None
if runas:
# Save the original command before munging it
try:
pwd.getpwnam(runas)
except KeyError:
raise CommandExecutionError(
'User \'{0}\' is not available'.format(runas)
)
if group:
if salt.utils.platform.is_windows():
msg = 'group is not currently available on Windows'
raise SaltInvocationError(msg)
if not which_bin(['sudo']):
msg = 'group argument requires sudo but not found'
raise CommandExecutionError(msg)
try:
grp.getgrnam(group)
except KeyError:
raise CommandExecutionError(
'Group \'{0}\' is not available'.format(runas)
)
else:
use_sudo = True
if runas or group:
try:
# Getting the environment for the runas user
# Use markers to thwart any stdout noise
# There must be a better way to do this.
import uuid
marker = '<<<' + str(uuid.uuid4()) + '>>>'
marker_b = marker.encode(__salt_system_encoding__)
py_code = (
'import sys, os, itertools; '
'sys.stdout.write(\"' + marker + '\"); '
'sys.stdout.write(\"\\0\".join(itertools.chain(*os.environ.items()))); '
'sys.stdout.write(\"' + marker + '\");'
)
if use_sudo or __grains__['os'] in ['MacOS', 'Darwin']:
env_cmd = ['sudo']
# runas is optional if use_sudo is set.
if runas:
env_cmd.extend(['-u', runas])
if group:
env_cmd.extend(['-g', group])
if shell != DEFAULT_SHELL:
env_cmd.extend(['-s', '--', shell, '-c'])
else:
env_cmd.extend(['-i', '--'])
env_cmd.extend([sys.executable])
elif __grains__['os'] in ['FreeBSD']:
env_cmd = ('su', '-', runas, '-c',
"{0} -c {1}".format(shell, sys.executable))
elif __grains__['os_family'] in ['Solaris']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
elif __grains__['os_family'] in ['AIX']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
else:
env_cmd = ('su', '-s', shell, '-', runas, '-c', sys.executable)
msg = 'env command: {0}'.format(env_cmd)
log.debug(log_callback(msg))
env_bytes, env_encoded_err = subprocess.Popen(
env_cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
).communicate(salt.utils.stringutils.to_bytes(py_code))
marker_count = env_bytes.count(marker_b)
if marker_count == 0:
# Possibly PAM prevented the login
log.error(
'Environment could not be retrieved for user \'%s\': '
'stderr=%r stdout=%r',
runas, env_encoded_err, env_bytes
)
# Ensure that we get an empty env_runas dict below since we
# were not able to get the environment.
env_bytes = b''
elif marker_count != 2:
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\'',
info={'stderr': repr(env_encoded_err),
'stdout': repr(env_bytes)}
)
else:
# Strip the marker
env_bytes = env_bytes.split(marker_b)[1]
if six.PY2:
import itertools
env_runas = dict(itertools.izip(*[iter(env_bytes.split(b'\0'))]*2))
elif six.PY3:
env_runas = dict(list(zip(*[iter(env_bytes.split(b'\0'))]*2)))
env_runas = dict(
(salt.utils.stringutils.to_str(k),
salt.utils.stringutils.to_str(v))
for k, v in six.iteritems(env_runas)
)
env_runas.update(env)
# Fix platforms like Solaris that don't set a USER env var in the
# user's default environment as obtained above.
if env_runas.get('USER') != runas:
env_runas['USER'] = runas
# Fix some corner cases where shelling out to get the user's
# environment returns the wrong home directory.
runas_home = os.path.expanduser('~{0}'.format(runas))
if env_runas.get('HOME') != runas_home:
env_runas['HOME'] = runas_home
env = env_runas
except ValueError as exc:
log.exception('Error raised retrieving environment for user %s', runas)
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\': {1}'.format(
runas, exc
)
)
if reset_system_locale is True:
if not salt.utils.platform.is_windows():
# Default to C!
# Salt only knows how to parse English words
# Don't override if the user has passed LC_ALL
env.setdefault('LC_CTYPE', 'C')
env.setdefault('LC_NUMERIC', 'C')
env.setdefault('LC_TIME', 'C')
env.setdefault('LC_COLLATE', 'C')
env.setdefault('LC_MONETARY', 'C')
env.setdefault('LC_MESSAGES', 'C')
env.setdefault('LC_PAPER', 'C')
env.setdefault('LC_NAME', 'C')
env.setdefault('LC_ADDRESS', 'C')
env.setdefault('LC_TELEPHONE', 'C')
env.setdefault('LC_MEASUREMENT', 'C')
env.setdefault('LC_IDENTIFICATION', 'C')
env.setdefault('LANGUAGE', 'C')
else:
# On Windows set the codepage to US English.
if python_shell:
cmd = 'chcp 437 > nul & ' + cmd
if clean_env:
run_env = env
else:
run_env = os.environ.copy()
run_env.update(env)
if prepend_path:
run_env['PATH'] = ':'.join((prepend_path, run_env['PATH']))
if python_shell is None:
python_shell = False
new_kwargs = {'cwd': cwd,
'shell': python_shell,
'env': run_env if six.PY3 else salt.utils.data.encode(run_env),
'stdin': six.text_type(stdin) if stdin is not None else stdin,
'stdout': stdout,
'stderr': stderr,
'with_communicate': with_communicate,
'timeout': timeout,
'bg': bg,
}
if 'stdin_raw_newlines' in kwargs:
new_kwargs['stdin_raw_newlines'] = kwargs['stdin_raw_newlines']
if umask is not None:
_umask = six.text_type(umask).lstrip('0')
if _umask == '':
msg = 'Zero umask is not allowed.'
raise CommandExecutionError(msg)
try:
_umask = int(_umask, 8)
except ValueError:
raise CommandExecutionError("Invalid umask: '{0}'".format(umask))
else:
_umask = None
if runas or group or umask:
new_kwargs['preexec_fn'] = functools.partial(
salt.utils.user.chugid_and_umask,
runas,
_umask,
group)
if not salt.utils.platform.is_windows():
# close_fds is not supported on Windows platforms if you redirect
# stdin/stdout/stderr
if new_kwargs['shell'] is True:
new_kwargs['executable'] = shell
new_kwargs['close_fds'] = True
if not os.path.isabs(cwd) or not os.path.isdir(cwd):
raise CommandExecutionError(
'Specified cwd \'{0}\' either not absolute or does not exist'
.format(cwd)
)
if python_shell is not True \
and not salt.utils.platform.is_windows() \
and not isinstance(cmd, list):
cmd = salt.utils.args.shlex_split(cmd)
if success_retcodes is None:
success_retcodes = [0]
else:
try:
success_retcodes = [int(i) for i in
salt.utils.args.split_input(
success_retcodes
)]
except ValueError:
raise SaltInvocationError(
'success_retcodes must be a list of integers'
)
if success_stdout is None:
success_stdout = []
else:
try:
success_stdout = [i for i in
salt.utils.args.split_input(
success_stdout
)]
except ValueError:
raise SaltInvocationError(
'success_stdout must be a list of integers'
)
if success_stderr is None:
success_stderr = []
else:
try:
success_stderr = [i for i in
salt.utils.args.split_input(
success_stderr
)]
except ValueError:
raise SaltInvocationError(
'success_stderr must be a list of integers'
)
if not use_vt:
# This is where the magic happens
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **new_kwargs)
except (OSError, IOError) as exc:
msg = (
'Unable to run command \'{0}\' with the context \'{1}\', '
'reason: {2}'.format(
cmd if output_loglevel is not None else 'REDACTED',
new_kwargs,
exc
)
)
raise CommandExecutionError(msg)
try:
proc.run()
except TimedProcTimeoutError as exc:
ret['stdout'] = six.text_type(exc)
ret['stderr'] = ''
ret['retcode'] = None
ret['pid'] = proc.process.pid
# ok return code for timeouts?
ret['retcode'] = 1
return ret
if output_loglevel != 'quiet' and output_encoding is not None:
log.debug('Decoding output from command %s using %s encoding',
cmd, output_encoding)
try:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding)
except TypeError:
# stdout is None
out = ''
except UnicodeDecodeError:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', cmd
)
try:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding)
except TypeError:
# stderr is None
err = ''
except UnicodeDecodeError:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', cmd
)
if rstrip:
if out is not None:
out = out.rstrip()
if err is not None:
err = err.rstrip()
ret['pid'] = proc.process.pid
ret['retcode'] = proc.process.returncode
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
ret['stdout'] = out
ret['stderr'] = err
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
else:
formatted_timeout = ''
if timeout:
formatted_timeout = ' (timeout: {0}s)'.format(timeout)
if output_loglevel is not None:
msg = 'Running {0} in VT{1}'.format(cmd, formatted_timeout)
log.debug(log_callback(msg))
stdout, stderr = '', ''
now = time.time()
if timeout:
will_timeout = now + timeout
else:
will_timeout = -1
try:
proc = salt.utils.vt.Terminal(
cmd,
shell=True,
log_stdout=True,
log_stderr=True,
cwd=cwd,
preexec_fn=new_kwargs.get('preexec_fn', None),
env=run_env,
log_stdin_level=output_loglevel,
log_stdout_level=output_loglevel,
log_stderr_level=output_loglevel,
stream_stdout=True,
stream_stderr=True
)
ret['pid'] = proc.pid
while proc.has_unread_data:
try:
try:
time.sleep(0.5)
try:
cstdout, cstderr = proc.recv()
except IOError:
cstdout, cstderr = '', ''
if cstdout:
stdout += cstdout
else:
cstdout = ''
if cstderr:
stderr += cstderr
else:
cstderr = ''
if timeout and (time.time() > will_timeout):
ret['stderr'] = (
'SALT: Timeout after {0}s\n{1}').format(
timeout, stderr)
ret['retcode'] = None
break
except KeyboardInterrupt:
ret['stderr'] = 'SALT: User break\n{0}'.format(stderr)
ret['retcode'] = 1
break
except salt.utils.vt.TerminalException as exc:
log.error('VT: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
ret = {'retcode': 1, 'pid': '2'}
break
# only set stdout on success as we already mangled in other
# cases
ret['stdout'] = stdout
if not proc.isalive():
# Process terminated, i.e., not canceled by the user or by
# the timeout
ret['stderr'] = stderr
ret['retcode'] = proc.exitstatus
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
ret['pid'] = proc.pid
finally:
proc.close(terminate=True, kill=True)
try:
if ignore_retcode:
__context__['retcode'] = 0
else:
__context__['retcode'] = ret['retcode']
except NameError:
# Ignore the context error during grain generation
pass
# Log the output
if output_loglevel is not None:
if not ignore_retcode and ret['retcode'] != 0:
if output_loglevel < LOG_LEVELS['error']:
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if ret['stdout']:
log.log(output_loglevel, 'stdout: %s', log_callback(ret['stdout']))
if ret['stderr']:
log.log(output_loglevel, 'stderr: %s', log_callback(ret['stderr']))
if ret['retcode']:
log.log(output_loglevel, 'retcode: %s', ret['retcode'])
return ret
def _run_quiet(cmd,
cwd=None,
stdin=None,
output_encoding=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)['stdout']
def _run_all_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
output_encoding=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup.
Returns a dict of return data.
output_loglevel argument is ignored. This is here for when we alias
cmd.run_all directly to _run_all_quiet in certain chicken-and-egg
situations where modules need to work both before and after
the __salt__ dictionary is populated (cf dracr.py)
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)
def run(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
encoded_cmd=False,
raise_err=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
Execute the passed command and return the output as a string
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run 'echo '\''h=\"baz\"'\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If ``False``, let python handle the positional
arguments. Set to ``True`` to use shell features, such as pipes or
redirection.
:param bool bg: If ``True``, run command in background and do not await or
deliver it's results
.. versionadded:: 2016.3.0
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
:param bool raise_err: If ``True`` and the command has a nonzero exit code,
a CommandExecutionError exception will be raised.
.. warning::
This function does not process commands through a shell
unless the python_shell flag is set to True. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or
have the python_shell=True flag set here.
The use of python_shell=True means that the shell will accept _any_ input
including potentially malicious commands such as 'good_command;rm -rf /'.
Be absolutely certain that you have sanitized your input prior to using
python_shell=True
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run cmd='sed -e s/=/:/g'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
log_callback = _check_cb(log_callback)
lvl = _check_loglevel(output_loglevel)
if lvl is not None:
if not ignore_retcode and ret['retcode'] != 0:
if lvl < LOG_LEVELS['error']:
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if raise_err:
raise CommandExecutionError(
log_callback(ret['stdout'] if not hide_output else '')
)
log.log(lvl, 'output: %s', log_callback(ret['stdout']))
return ret['stdout'] if not hide_output else ''
def shell(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return the output as a string.
.. versionadded:: 2015.5.0
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.shell 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param int shell: Shell to execute under. Defaults to the system default
shell.
:param bool bg: If True, run command in background and do not await or
deliver its results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.shell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
.. warning::
This passes the cmd argument directly to the shell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.shell "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.shell template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.shell "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.shell "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.shell cmd='sed -e s/=/:/g'
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
return run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
def run_stdout(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command, and only return the standard out
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stdout 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stdout template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stdout "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stdout'] if not hide_output else ''
def run_stderr(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command and only return the standard error
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stderr 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stderr 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stderr "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stderr template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stderr "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stderr'] if not hide_output else ''
def run_all(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
redirect_stderr=False,
password=None,
encoded_cmd=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return a dict of return data
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_all 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
.. versionadded:: 2018.3.0
:param bool redirect_stderr: If set to ``True``, then stderr will be
redirected to stdout. This is helpful for cases where obtaining both
the retcode and output is desired, but it is not desired to have the
output separated into both stdout and stderr.
.. versionadded:: 2015.8.2
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param bool bg: If ``True``, run command in background and do not await or
deliver its results
.. versionadded:: 2016.3.6
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_all "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_all template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_all "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=stderr,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def retcode(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a shell command and return the command's return code.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.retcode 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.retcode 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:rtype: int
:rtype: None
:returns: Return Code as an int or None if there was an exception.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.retcode "file /bin/bash"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.retcode template=jinja "file {{grains.pythonpath[0]}}/python"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.retcode "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['retcode']
def _retcode_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Helper for running commands quietly for minion startup. Returns same as
the retcode() function.
'''
return retcode(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stderr,
success_stderr=success_stderr,
**kwargs)
def script(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
saltenv='base',
use_vt=False,
bg=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
.. code-block:: bash
salt myminion cmd.script salt://foo.sh "arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param bool bg: If True, run script in background and do not await or
deliver it's results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh
salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
def _cleanup_tempfile(path):
try:
__salt__['file.remove'](path)
except (SaltInvocationError, CommandExecutionError) as exc:
log.error(
'cmd.script: Unable to clean tempfile \'%s\': %s',
path, exc, exc_info_on_loglevel=logging.DEBUG
)
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
win_cwd = False
if salt.utils.platform.is_windows() and runas and cwd is None:
# Create a temp working directory
cwd = tempfile.mkdtemp(dir=__opts__['cachedir'])
win_cwd = True
salt.utils.win_dacl.set_permissions(obj_name=cwd,
principal=runas,
permissions='full_control')
path = salt.utils.files.mkstemp(dir=cwd, suffix=os.path.splitext(source)[1])
if template:
if 'pillarenv' in kwargs or 'pillar' in kwargs:
pillarenv = kwargs.get('pillarenv', __opts__.get('pillarenv'))
kwargs['pillar'] = _gather_pillar(pillarenv, kwargs.get('pillar'))
fn_ = __salt__['cp.get_template'](source,
path,
template,
saltenv,
**kwargs)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
else:
fn_ = __salt__['cp.cache_file'](source, saltenv)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
shutil.copyfile(fn_, path)
if not salt.utils.platform.is_windows():
os.chmod(path, 320)
os.chown(path, __salt__['file.user_to_uid'](runas), -1)
if salt.utils.platform.is_windows() and shell.lower() != 'powershell':
cmd_path = _cmd_quote(path, escape=False)
else:
cmd_path = _cmd_quote(path)
ret = _run(cmd_path + ' ' + six.text_type(args) if args else cmd_path,
cwd=cwd,
stdin=stdin,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def script_retcode(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template='jinja',
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
output_encoding=None,
output_loglevel='debug',
log_callback=None,
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
The script can also be formatted as a template, the default is jinja.
Only evaluate the script return code and do not block for terminal output
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
"arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script_retcode 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh
salt '*' cmd.script_retcode salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script_retcode salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
return script(source=source,
args=args,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)['retcode']
def which(cmd):
'''
Returns the path of an executable available on the minion, None otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.which cat
'''
return salt.utils.path.which(cmd)
def which_bin(cmds):
'''
Returns the first command found in a list of commands
CLI Example:
.. code-block:: bash
salt '*' cmd.which_bin '[pip2, pip, pip-python]'
'''
return salt.utils.path.which_bin(cmds)
def has_exec(cmd):
'''
Returns true if the executable is available on the minion, false otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.has_exec cat
'''
return which(cmd) is not None
def exec_code(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. The stdout will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code ruby 'puts "cheese"'
salt '*' cmd.exec_code ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
return exec_code_all(lang, code, cwd, args, **kwargs)['stdout']
def exec_code_all(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid)
will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code_all ruby 'puts "cheese"'
salt '*' cmd.exec_code_all ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
powershell = lang.lower().startswith("powershell")
if powershell:
codefile = salt.utils.files.mkstemp(suffix=".ps1")
else:
codefile = salt.utils.files.mkstemp()
with salt.utils.files.fopen(codefile, 'w+t', binary=False) as fp_:
fp_.write(salt.utils.stringutils.to_str(code))
if powershell:
cmd = [lang, "-File", codefile]
else:
cmd = [lang, codefile]
if isinstance(args, six.string_types):
cmd.append(args)
elif isinstance(args, list):
cmd += args
ret = run_all(cmd, cwd=cwd, python_shell=False, **kwargs)
os.remove(codefile)
return ret
def tty(device, echo=''):
'''
Echo a string to a specific tty
CLI Example:
.. code-block:: bash
salt '*' cmd.tty tty0 'This is a test'
salt '*' cmd.tty pts3 'This is a test'
'''
if device.startswith('tty'):
teletype = '/dev/{0}'.format(device)
elif device.startswith('pts'):
teletype = '/dev/{0}'.format(device.replace('pts', 'pts/'))
else:
return {'Error': 'The specified device is not a valid TTY'}
try:
with salt.utils.files.fopen(teletype, 'wb') as tty_device:
tty_device.write(salt.utils.stringutils.to_bytes(echo))
return {
'Success': 'Message was successfully echoed to {0}'.format(teletype)
}
except IOError:
return {
'Error': 'Echoing to {0} returned error'.format(teletype)
}
def run_chroot(root,
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=True,
binds=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='quiet',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
.. versionadded:: 2014.7.0
This function runs :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` wrapped
within a chroot, with dev and proc mounted in the chroot
:param str root: Path to the root of the jail to use.
:param str stdin: A string of standard input can be specified for
the command to be run using the ``stdin`` parameter. This can
be useful in cases where sensitive information must be read
from standard input.:
:param str runas: User to run script as.
:param str group: Group to run script as.
:param str shell: Shell to execute under. Defaults to the system
default shell.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:parar str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param list binds: List of directories that will be exported inside
the chroot with the bind option.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_chroot 'some command' env='{"FOO": "bar"}'
:param dict clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output
before it is returned.
:param str umask: The umask (in octal) to use when running the
command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout:
A timeout in seconds for the executed process to return.
:param bool use_vt:
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs. This is experimental.
:param success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' cmd.run_chroot /var/lib/lxc/container_name/rootfs 'sh /tmp/bootstrap.sh'
'''
__salt__['mount.mount'](
os.path.join(root, 'dev'),
'devtmpfs',
fstype='devtmpfs')
__salt__['mount.mount'](
os.path.join(root, 'proc'),
'proc',
fstype='proc')
__salt__['mount.mount'](
os.path.join(root, 'sys'),
'sysfs',
fstype='sysfs')
binds = binds if binds else []
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.mount'](
bind_exported_to,
bind_exported,
opts='default,bind')
# Execute chroot routine
sh_ = '/bin/sh'
if os.path.isfile(os.path.join(root, 'bin/bash')):
sh_ = '/bin/bash'
if isinstance(cmd, (list, tuple)):
cmd = ' '.join([six.text_type(i) for i in cmd])
cmd = 'chroot {0} {1} -c {2}'.format(root, sh_, _cmd_quote(cmd))
run_func = __context__.pop('cmd.run_chroot.func', run_all)
ret = run_func(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
pillarenv=kwargs.get('pillarenv'),
pillar=kwargs.get('pillar'),
use_vt=use_vt,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
bg=bg)
# Kill processes running in the chroot
for i in range(6):
pids = _chroot_pids(root)
if not pids:
break
for pid in pids:
# use sig 15 (TERM) for first 3 attempts, then 9 (KILL)
sig = 15 if i < 3 else 9
os.kill(pid, sig)
if _chroot_pids(root):
log.error('Processes running in chroot could not be killed, '
'filesystem will remain mounted')
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.umount'](bind_exported_to)
__salt__['mount.umount'](os.path.join(root, 'sys'))
__salt__['mount.umount'](os.path.join(root, 'proc'))
__salt__['mount.umount'](os.path.join(root, 'dev'))
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def _is_valid_shell(shell):
'''
Attempts to search for valid shells on a system and
see if a given shell is in the list
'''
if salt.utils.platform.is_windows():
return True # Don't even try this for Windows
shells = '/etc/shells'
available_shells = []
if os.path.exists(shells):
try:
with salt.utils.files.fopen(shells, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
if line.startswith('#'):
continue
else:
available_shells.append(line)
except OSError:
return True
else:
# No known method of determining available shells
return None
if shell in available_shells:
return True
else:
return False
def shells():
'''
Lists the valid shells on this system via the /etc/shells file
.. versionadded:: 2015.5.0
CLI Example::
salt '*' cmd.shells
'''
shells_fn = '/etc/shells'
ret = []
if os.path.exists(shells_fn):
try:
with salt.utils.files.fopen(shells_fn, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
line = line.strip()
if line.startswith('#'):
continue
elif not line:
continue
else:
ret.append(line)
except OSError:
log.error("File '%s' was not found", shells_fn)
return ret
def shell_info(shell, list_modules=False):
'''
.. versionadded:: 2016.11.0
Provides information about a shell or script languages which often use
``#!``. The values returned are dependent on the shell or scripting
languages all return the ``installed``, ``path``, ``version``,
``version_raw``
Args:
shell (str): Name of the shell. Support shells/script languages include
bash, cmd, perl, php, powershell, python, ruby and zsh
list_modules (bool): True to list modules available to the shell.
Currently only lists powershell modules.
Returns:
dict: A dictionary of information about the shell
.. code-block:: python
{'version': '<2 or 3 numeric components dot-separated>',
'version_raw': '<full version string>',
'path': '<full path to binary>',
'installed': <True, False or None>,
'<attribute>': '<attribute value>'}
.. note::
- ``installed`` is always returned, if ``None`` or ``False`` also
returns error and may also return ``stdout`` for diagnostics.
- ``version`` is for use in determine if a shell/script language has a
particular feature set, not for package management.
- The shell must be within the executable search path.
CLI Example:
.. code-block:: bash
salt '*' cmd.shell_info bash
salt '*' cmd.shell_info powershell
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
regex_shells = {
'bash': [r'version (\d\S*)', 'bash', '--version'],
'bash-test-error': [r'versioZ ([-\w.]+)', 'bash', '--version'], # used to test an error result
'bash-test-env': [r'(HOME=.*)', 'bash', '-c', 'declare'], # used to test an error result
'zsh': [r'^zsh (\d\S*)', 'zsh', '--version'],
'tcsh': [r'^tcsh (\d\S*)', 'tcsh', '--version'],
'cmd': [r'Version ([\d.]+)', 'cmd.exe', '/C', 'ver'],
'powershell': [r'PSVersion\s+(\d\S*)', 'powershell', '-NonInteractive', '$PSVersionTable'],
'perl': [r'^(\d\S*)', 'perl', '-e', 'printf "%vd\n", $^V;'],
'python': [r'^Python (\d\S*)', 'python', '-V'],
'ruby': [r'^ruby (\d\S*)', 'ruby', '-v'],
'php': [r'^PHP (\d\S*)', 'php', '-v']
}
# Ensure ret['installed'] always as a value of True, False or None (not sure)
ret = {'installed': False}
if salt.utils.platform.is_windows() and shell == 'powershell':
pw_keys = salt.utils.win_reg.list_keys(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell')
pw_keys.sort(key=int)
if not pw_keys:
return {
'error': 'Unable to locate \'powershell\' Reason: Cannot be '
'found in registry.',
'installed': False,
}
for reg_ver in pw_keys:
install_data = salt.utils.win_reg.read_value(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}'.format(reg_ver),
vname='Install')
if install_data.get('vtype') == 'REG_DWORD' and \
install_data.get('vdata') == 1:
details = salt.utils.win_reg.list_values(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}\\'
'PowerShellEngine'.format(reg_ver))
# reset data, want the newest version details only as powershell
# is backwards compatible
ret = {}
# if all goes well this will become True
ret['installed'] = None
ret['path'] = which('powershell.exe')
for attribute in details:
if attribute['vname'].lower() == '(default)':
continue
elif attribute['vname'].lower() == 'powershellversion':
ret['psversion'] = attribute['vdata']
ret['version_raw'] = attribute['vdata']
elif attribute['vname'].lower() == 'runtimeversion':
ret['crlversion'] = attribute['vdata']
if ret['crlversion'][0].lower() == 'v':
ret['crlversion'] = ret['crlversion'][1::]
elif attribute['vname'].lower() == 'pscompatibleversion':
# reg attribute does not end in s, the powershell
# attribute does
ret['pscompatibleversions'] = \
attribute['vdata'].replace(' ', '').split(',')
else:
# keys are lower case as python is case sensitive the
# registry is not
ret[attribute['vname'].lower()] = attribute['vdata']
else:
if shell not in regex_shells:
return {
'error': 'Salt does not know how to get the version number for '
'{0}'.format(shell),
'installed': None
}
shell_data = regex_shells[shell]
pattern = shell_data.pop(0)
# We need to make sure HOME set, so shells work correctly
# salt-call will general have home set, the salt-minion service may not
# We need to assume ports of unix shells to windows will look after
# themselves in setting HOME as they do it in many different ways
newenv = os.environ
if ('HOME' not in newenv) and (not salt.utils.platform.is_windows()):
newenv['HOME'] = os.path.expanduser('~')
log.debug('HOME environment set to %s', newenv['HOME'])
try:
proc = salt.utils.timed_subprocess.TimedProc(
shell_data,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=10,
env=newenv
)
except (OSError, IOError) as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: {1}'.format(' '.join(shell_data), exc),
'installed': False,
}
try:
proc.run()
except TimedProcTimeoutError as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: Timed out.'.format(' '.join(shell_data)),
'installed': False,
}
ret['path'] = which(shell_data[0])
pattern_result = re.search(pattern, proc.stdout, flags=re.IGNORECASE)
# only set version if we find it, so code later on can deal with it
if pattern_result:
ret['version_raw'] = pattern_result.group(1)
if 'version_raw' in ret:
version_results = re.match(r'(\d[\d.]*)', ret['version_raw'])
if version_results:
ret['installed'] = True
ver_list = version_results.group(1).split('.')[:3]
if len(ver_list) == 1:
ver_list.append('0')
ret['version'] = '.'.join(ver_list[:3])
else:
ret['installed'] = None # Have an unexpected result
# Get a list of the PowerShell modules which are potentially available
# to be imported
if shell == 'powershell' and ret['installed'] and list_modules:
ret['modules'] = salt.utils.powershell.get_modules()
if 'version' not in ret:
ret['error'] = 'The version regex pattern for shell {0}, could not ' \
'find the version string'.format(shell)
ret['stdout'] = proc.stdout # include stdout so they can see the issue
log.error(ret['error'])
return ret
def powershell(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return the output as a dictionary.
Other ``cmd.*`` functions (besides ``cmd.powershell_all``)
return the raw text output of the command. This
function appends ``| ConvertTo-JSON`` to the command and then parses the
JSON into a Python dictionary. If you want the raw textual result of your
PowerShell command you should use ``cmd.run`` with the ``shell=powershell``
option.
For example:
.. code-block:: bash
salt '*' cmd.run '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2016.3.0
.. warning::
This passes the cmd argument directly to PowerShell
without any further processing! Be absolutely sure that you
have properly sanitized the command passed to this function
and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in cases
where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
.. versionadded:: 2016.3.4
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:returns:
:dict: A dictionary of data returned by the powershell command.
CLI Example:
.. code-block:: powershell
salt '*' cmd.powershell "$PSVersionTable.CLRVersion"
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
# ConvertTo-JSON is only available on PowerShell 3.0 and later
psversion = shell_info('powershell')['psversion']
if salt.utils.versions.version_cmp(psversion, '2.0') == 1:
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Put the whole command inside a try / catch block
# Some errors in PowerShell are not "Terminating Errors" and will not be
# caught in a try/catch block. For example, the `Get-WmiObject` command will
# often return a "Non Terminating Error". To fix this, make sure
# `-ErrorAction Stop` is set in the powershell command
cmd = 'try {' + cmd + '} catch { "{}" }'
# Retrieve the response, while overriding shell with 'powershell'
response = run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
try:
return salt.utils.json.loads(response)
except Exception:
log.error("Error converting PowerShell JSON return", exc_info=True)
return {}
def powershell_all(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
quiet=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
force_list=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return a dictionary with a result
field representing the output of the command, as well as other fields
showing us what the PowerShell invocation wrote to ``stderr``, the process
id, and the exit code of the invocation.
This function appends ``| ConvertTo-JSON`` to the command before actually
invoking powershell.
An unquoted empty string is not valid JSON, but it's very normal for the
Powershell output to be exactly that. Therefore, we do not attempt to parse
empty Powershell output (which would result in an exception). Instead we
treat this as a special case and one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field of the return dictionary will be an empty list.
- If the value of the ``force_list`` parameter is ``False``, then the
return dictionary **will not have a result key added to it**. We aren't
setting ``result`` to ``None`` in this case, because ``None`` is the
Python representation of "null" in JSON. (We likewise can't use ``False``
for the equivalent reason.)
If Powershell's output is not an empty string and Python cannot parse its
content, then a ``CommandExecutionError`` exception will be raised.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is other than ``list``
then one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field will be a singleton list with the Python object as its
sole member.
- If the value of the ``force_list`` parameter is ``False``, then the value
of ``result`` will be the unmodified Python object.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is ``list``, then the
value of ``result`` will be the unmodified Python object. The
``force_list`` parameter has no effect in this case.
.. note::
An example of why the ``force_list`` parameter is useful is as
follows: The Powershell command ``dir x | Convert-ToJson`` results in
- no output when x is an empty directory.
- a dictionary object when x contains just one item.
- a list of dictionary objects when x contains multiple items.
By setting ``force_list`` to ``True`` we will always end up with a
list of dictionary items, representing files, no matter how many files
x contains. Conversely, if ``force_list`` is ``False``, we will end
up with no ``result`` key in our return dictionary when x is an empty
directory, and a dictionary object when x contains just one file.
If you want a similar function but with a raw textual result instead of a
Python dictionary, you should use ``cmd.run_all`` in combination with
``shell=powershell``.
The remaining fields in the return dictionary are described in more detail
in the ``Returns`` section.
Example:
.. code-block:: bash
salt '*' cmd.run_all '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run_all 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2018.3.0
.. warning::
This passes the cmd argument directly to PowerShell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param bool force_list: The purpose of this parameter is described in the
preamble of this function's documentation. Default value is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:return: A dictionary with the following entries:
result
For a complete description of this field, please refer to this
function's preamble. **This key will not be added to the dictionary
when force_list is False and Powershell's output is the empty
string.**
stderr
What the PowerShell invocation wrote to ``stderr``.
pid
The process id of the PowerShell invocation
retcode
This is the exit code of the invocation of PowerShell.
If the final execution status (in PowerShell) of our command
(with ``| ConvertTo-JSON`` appended) is ``False`` this should be non-0.
Likewise if PowerShell exited with ``$LASTEXITCODE`` set to some
non-0 value, then ``retcode`` will end up with this value.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "$PSVersionTable.CLRVersion"
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "dir mydirectory" force_list=True
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Retrieve the response, while overriding shell with 'powershell'
response = run_all(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
quiet=quiet,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
stdoutput = response['stdout']
# if stdoutput is the empty string and force_list is True we return an empty list
# Otherwise we return response with no result key
if not stdoutput:
response.pop('stdout')
if force_list:
response['result'] = []
return response
# If we fail to parse stdoutput we will raise an exception
try:
result = salt.utils.json.loads(stdoutput)
except Exception:
err_msg = "cmd.powershell_all " + \
"cannot parse the Powershell output."
response["cmd"] = cmd
raise CommandExecutionError(
message=err_msg,
info=response
)
response.pop("stdout")
if type(result) is not list:
if force_list:
response['result'] = [result]
else:
response['result'] = result
else:
# result type is list so the force_list param has no effect
response['result'] = result
return response
def run_bg(cmd,
cwd=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
timeout=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
.. versionadded: 2016.3.0
Execute the passed command in the background and return it's PID
.. note::
If the init system is systemd and the backgrounded task should run even
if the salt-minion process is restarted, prepend ``systemd-run
--scope`` to the command. This will reparent the process in its own
scope separate from salt-minion, and will not be affected by restarting
the minion service.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Shell to execute under. Defaults to the system default
shell.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_bg 'echo '\''h=\"baz\"'\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_bg 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param int timeout: A timeout in seconds for the executed process to return.
.. warning::
This function does not process commands through a shell unless the
``python_shell`` argument is set to ``True``. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or have the
python_shell=True flag set here.
The use of ``python_shell=True`` means that the shell will accept _any_
input including potentially malicious commands such as 'good_command;rm
-rf /'. Be absolutely certain that you have sanitized your input prior
to using ``python_shell=True``.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_bg "fstrim-all"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_bg template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run_bg "Get-ChildItem C:\\ " shell='powershell'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run_bg cmd='ls -lR / | sed -e s/=/:/g > /tmp/dontwait'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
res = _run(cmd,
stdin=None,
stderr=None,
stdout=None,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
use_vt=None,
bg=True,
with_communicate=False,
rstrip=False,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
umask=umask,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs
)
return {
'pid': res['pid']
}
|
saltstack/salt
|
salt/modules/cmdmod.py
|
_check_loglevel
|
python
|
def _check_loglevel(level='info'):
'''
Retrieve the level code for use in logging.Logger.log().
'''
try:
level = level.lower()
if level == 'quiet':
return None
else:
return LOG_LEVELS[level]
except (AttributeError, KeyError):
log.error(
'Invalid output_loglevel \'%s\'. Valid levels are: %s. Falling '
'back to \'info\'.',
level, ', '.join(sorted(LOG_LEVELS, reverse=True))
)
return LOG_LEVELS['info']
|
Retrieve the level code for use in logging.Logger.log().
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cmdmod.py#L175-L191
| null |
# -*- coding: utf-8 -*-
'''
A module for shelling out.
Keep in mind that this module is insecure, in that it can give whomever has
access to the master root execution access to all salt minions.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import functools
import glob
import logging
import os
import shutil
import subprocess
import sys
import time
import traceback
import fnmatch
import base64
import re
import tempfile
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.powershell
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.timed_subprocess
import salt.utils.user
import salt.utils.versions
import salt.utils.vt
import salt.utils.win_dacl
import salt.utils.win_reg
import salt.grains.extra
from salt.ext import six
from salt.exceptions import CommandExecutionError, TimedProcTimeoutError, \
SaltInvocationError
from salt.log import LOG_LEVELS
from salt.ext.six.moves import range, zip, map
# Only available on POSIX systems, nonfatal on windows
try:
import pwd
import grp
except ImportError:
pass
if salt.utils.platform.is_windows():
from salt.utils.win_runas import runas as win_runas
from salt.utils.win_functions import escape_argument as _cmd_quote
HAS_WIN_RUNAS = True
else:
from salt.ext.six.moves import shlex_quote as _cmd_quote
HAS_WIN_RUNAS = False
__proxyenabled__ = ['*']
# Define the module's virtual name
__virtualname__ = 'cmd'
# Set up logging
log = logging.getLogger(__name__)
DEFAULT_SHELL = salt.grains.extra.shell()['shell']
# Overwriting the cmd python module makes debugging modules with pdb a bit
# harder so lets do it this way instead.
def __virtual__():
return __virtualname__
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns
the value passed.
'''
if cb_ is not None:
if hasattr(cb_, '__call__'):
return cb_
else:
log.error('log_callback is not callable, ignoring')
return lambda x: x
def _python_shell_default(python_shell, __pub_jid):
'''
Set python_shell default based on remote execution and __opts__['cmd_safe']
'''
try:
# Default to python_shell=True when run directly from remote execution
# system. Cross-module calls won't have a jid.
if __pub_jid and python_shell is None:
return True
elif __opts__.get('cmd_safe', True) is False and python_shell is None:
# Override-switch for python_shell
return True
except NameError:
pass
return python_shell
def _chroot_pids(chroot):
pids = []
for root in glob.glob('/proc/[0-9]*/root'):
try:
link = os.path.realpath(root)
if link.startswith(chroot):
pids.append(int(os.path.basename(
os.path.dirname(root)
)))
except OSError:
pass
return pids
def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):
'''
If template is a valid template engine, process the cmd and cwd through
that engine.
'''
if not template:
return (cmd, cwd)
# render the path as a template using path_template_engine as the engine
if template not in salt.utils.templates.TEMPLATE_REGISTRY:
raise CommandExecutionError(
'Attempted to render file paths with unavailable engine '
'{0}'.format(template)
)
kwargs = {}
kwargs['salt'] = __salt__
if pillarenv is not None or pillar_override is not None:
pillarenv = pillarenv or __opts__['pillarenv']
kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override)
else:
kwargs['pillar'] = __pillar__
kwargs['grains'] = __grains__
kwargs['opts'] = __opts__
kwargs['saltenv'] = saltenv
def _render(contents):
# write out path to temp file
tmp_path_fn = salt.utils.files.mkstemp()
with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(contents))
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
tmp_path_fn,
to_str=True,
**kwargs
)
salt.utils.files.safe_rm(tmp_path_fn)
if not data['result']:
# Failed to render the template
raise CommandExecutionError(
'Failed to execute cmd with error: {0}'.format(
data['data']
)
)
else:
return data['data']
cmd = _render(cmd)
cwd = _render(cwd)
return (cmd, cwd)
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
return env
def _gather_pillar(pillarenv, pillar_override):
'''
Whenever a state run starts, gather the pillar data fresh
'''
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
pillar_override=pillar_override,
pillarenv=pillarenv
)
ret = pillar.compile_pillar()
if pillar_override and isinstance(pillar_override, dict):
ret.update(pillar_override)
return ret
def _check_avail(cmd):
'''
Check to see if the given command can be run
'''
if isinstance(cmd, list):
cmd = ' '.join([six.text_type(x) if not isinstance(x, six.string_types) else x
for x in cmd])
bret = True
wret = False
if __salt__['config.get']('cmd_blacklist_glob'):
blist = __salt__['config.get']('cmd_blacklist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# BAD! you are blacklisted
bret = False
if __salt__['config.get']('cmd_whitelist_glob', []):
blist = __salt__['config.get']('cmd_whitelist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# GOOD! You are whitelisted
wret = True
break
else:
# If no whitelist set then alls good!
wret = True
return bret and wret
def _run(cmd,
cwd=None,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
prepend_path=None,
rstrip=True,
template=None,
umask=None,
timeout=None,
with_communicate=True,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
pillarenv=None,
pillar_override=None,
use_vt=False,
password=None,
bg=False,
encoded_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Do the DRY thing and only call subprocess.Popen() once
'''
if 'pillar' in kwargs and not pillar_override:
pillar_override = kwargs['pillar']
if output_loglevel != 'quiet' and _is_valid_shell(shell) is False:
log.warning(
'Attempt to run a shell command with what may be an invalid shell! '
'Check to ensure that the shell <%s> is valid for this user.',
shell
)
output_loglevel = _check_loglevel(output_loglevel)
log_callback = _check_cb(log_callback)
use_sudo = False
if runas is None and '__context__' in globals():
runas = __context__.get('runas')
if password is None and '__context__' in globals():
password = __context__.get('runas_password')
# Set the default working directory to the home directory of the user
# salt-minion is running as. Defaults to home directory of user under which
# the minion is running.
if not cwd:
cwd = os.path.expanduser('~{0}'.format('' if not runas else runas))
# make sure we can access the cwd
# when run from sudo or another environment where the euid is
# changed ~ will expand to the home of the original uid and
# the euid might not have access to it. See issue #1844
if not os.access(cwd, os.R_OK):
cwd = '/'
if salt.utils.platform.is_windows():
cwd = os.path.abspath(os.sep)
else:
# Handle edge cases where numeric/other input is entered, and would be
# yaml-ified into non-string types
cwd = six.text_type(cwd)
if bg:
ignore_retcode = True
use_vt = False
if not salt.utils.platform.is_windows():
if not os.path.isfile(shell) or not os.access(shell, os.X_OK):
msg = 'The shell {0} is not available'.format(shell)
raise CommandExecutionError(msg)
if salt.utils.platform.is_windows() and use_vt: # Memozation so not much overhead
raise CommandExecutionError('VT not available on windows')
if shell.lower().strip() == 'powershell':
# Strip whitespace
if isinstance(cmd, six.string_types):
cmd = cmd.strip()
# If we were called by script(), then fakeout the Windows
# shell to run a Powershell script.
# Else just run a Powershell command.
stack = traceback.extract_stack(limit=2)
# extract_stack() returns a list of tuples.
# The last item in the list [-1] is the current method.
# The third item[2] in each tuple is the name of that method.
if stack[-2][2] == 'script':
cmd = 'Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -File ' + cmd
elif encoded_cmd:
cmd = 'Powershell -NonInteractive -EncodedCommand {0}'.format(cmd)
else:
cmd = 'Powershell -NonInteractive -NoProfile "{0}"'.format(cmd.replace('"', '\\"'))
# munge the cmd and cwd through the template
(cmd, cwd) = _render_cmd(cmd, cwd, template, saltenv, pillarenv, pillar_override)
ret = {}
# If the pub jid is here then this is a remote ex or salt call command and needs to be
# checked if blacklisted
if '__pub_jid' in kwargs:
if not _check_avail(cmd):
raise CommandExecutionError(
'The shell command "{0}" is not permitted'.format(cmd)
)
env = _parse_env(env)
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, six.string_types) else x for x in cmd]
elif isinstance(cmd, six.string_types):
return cmd.strip()
else:
return cmd
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' parameter.
msg = (
'Executing command {0}{1}{0} {2}{3}in directory \'{4}\'{5}'.format(
'\'' if not isinstance(cmd, list) else '',
_get_stripped(cmd),
'as user \'{0}\' '.format(runas) if runas else '',
'in group \'{0}\' '.format(group) if group else '',
cwd,
'. Executing command in the background, no output will be '
'logged.' if bg else ''
)
)
log.info(log_callback(msg))
if runas and salt.utils.platform.is_windows():
if not HAS_WIN_RUNAS:
msg = 'missing salt/utils/win_runas.py'
raise CommandExecutionError(msg)
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(cmd)
return win_runas(cmd, runas, password, cwd)
if runas and salt.utils.platform.is_darwin():
# we need to insert the user simulation into the command itself and not
# just run it from the environment on macOS as that
# method doesn't work properly when run as root for certain commands.
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(map(_cmd_quote, cmd))
cmd = 'su -l {0} -c "cd {1}; {2}"'.format(runas, cwd, cmd)
# set runas to None, because if you try to run `su -l` as well as
# simulate the environment macOS will prompt for the password of the
# user and will cause salt to hang.
runas = None
if runas:
# Save the original command before munging it
try:
pwd.getpwnam(runas)
except KeyError:
raise CommandExecutionError(
'User \'{0}\' is not available'.format(runas)
)
if group:
if salt.utils.platform.is_windows():
msg = 'group is not currently available on Windows'
raise SaltInvocationError(msg)
if not which_bin(['sudo']):
msg = 'group argument requires sudo but not found'
raise CommandExecutionError(msg)
try:
grp.getgrnam(group)
except KeyError:
raise CommandExecutionError(
'Group \'{0}\' is not available'.format(runas)
)
else:
use_sudo = True
if runas or group:
try:
# Getting the environment for the runas user
# Use markers to thwart any stdout noise
# There must be a better way to do this.
import uuid
marker = '<<<' + str(uuid.uuid4()) + '>>>'
marker_b = marker.encode(__salt_system_encoding__)
py_code = (
'import sys, os, itertools; '
'sys.stdout.write(\"' + marker + '\"); '
'sys.stdout.write(\"\\0\".join(itertools.chain(*os.environ.items()))); '
'sys.stdout.write(\"' + marker + '\");'
)
if use_sudo or __grains__['os'] in ['MacOS', 'Darwin']:
env_cmd = ['sudo']
# runas is optional if use_sudo is set.
if runas:
env_cmd.extend(['-u', runas])
if group:
env_cmd.extend(['-g', group])
if shell != DEFAULT_SHELL:
env_cmd.extend(['-s', '--', shell, '-c'])
else:
env_cmd.extend(['-i', '--'])
env_cmd.extend([sys.executable])
elif __grains__['os'] in ['FreeBSD']:
env_cmd = ('su', '-', runas, '-c',
"{0} -c {1}".format(shell, sys.executable))
elif __grains__['os_family'] in ['Solaris']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
elif __grains__['os_family'] in ['AIX']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
else:
env_cmd = ('su', '-s', shell, '-', runas, '-c', sys.executable)
msg = 'env command: {0}'.format(env_cmd)
log.debug(log_callback(msg))
env_bytes, env_encoded_err = subprocess.Popen(
env_cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
).communicate(salt.utils.stringutils.to_bytes(py_code))
marker_count = env_bytes.count(marker_b)
if marker_count == 0:
# Possibly PAM prevented the login
log.error(
'Environment could not be retrieved for user \'%s\': '
'stderr=%r stdout=%r',
runas, env_encoded_err, env_bytes
)
# Ensure that we get an empty env_runas dict below since we
# were not able to get the environment.
env_bytes = b''
elif marker_count != 2:
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\'',
info={'stderr': repr(env_encoded_err),
'stdout': repr(env_bytes)}
)
else:
# Strip the marker
env_bytes = env_bytes.split(marker_b)[1]
if six.PY2:
import itertools
env_runas = dict(itertools.izip(*[iter(env_bytes.split(b'\0'))]*2))
elif six.PY3:
env_runas = dict(list(zip(*[iter(env_bytes.split(b'\0'))]*2)))
env_runas = dict(
(salt.utils.stringutils.to_str(k),
salt.utils.stringutils.to_str(v))
for k, v in six.iteritems(env_runas)
)
env_runas.update(env)
# Fix platforms like Solaris that don't set a USER env var in the
# user's default environment as obtained above.
if env_runas.get('USER') != runas:
env_runas['USER'] = runas
# Fix some corner cases where shelling out to get the user's
# environment returns the wrong home directory.
runas_home = os.path.expanduser('~{0}'.format(runas))
if env_runas.get('HOME') != runas_home:
env_runas['HOME'] = runas_home
env = env_runas
except ValueError as exc:
log.exception('Error raised retrieving environment for user %s', runas)
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\': {1}'.format(
runas, exc
)
)
if reset_system_locale is True:
if not salt.utils.platform.is_windows():
# Default to C!
# Salt only knows how to parse English words
# Don't override if the user has passed LC_ALL
env.setdefault('LC_CTYPE', 'C')
env.setdefault('LC_NUMERIC', 'C')
env.setdefault('LC_TIME', 'C')
env.setdefault('LC_COLLATE', 'C')
env.setdefault('LC_MONETARY', 'C')
env.setdefault('LC_MESSAGES', 'C')
env.setdefault('LC_PAPER', 'C')
env.setdefault('LC_NAME', 'C')
env.setdefault('LC_ADDRESS', 'C')
env.setdefault('LC_TELEPHONE', 'C')
env.setdefault('LC_MEASUREMENT', 'C')
env.setdefault('LC_IDENTIFICATION', 'C')
env.setdefault('LANGUAGE', 'C')
else:
# On Windows set the codepage to US English.
if python_shell:
cmd = 'chcp 437 > nul & ' + cmd
if clean_env:
run_env = env
else:
run_env = os.environ.copy()
run_env.update(env)
if prepend_path:
run_env['PATH'] = ':'.join((prepend_path, run_env['PATH']))
if python_shell is None:
python_shell = False
new_kwargs = {'cwd': cwd,
'shell': python_shell,
'env': run_env if six.PY3 else salt.utils.data.encode(run_env),
'stdin': six.text_type(stdin) if stdin is not None else stdin,
'stdout': stdout,
'stderr': stderr,
'with_communicate': with_communicate,
'timeout': timeout,
'bg': bg,
}
if 'stdin_raw_newlines' in kwargs:
new_kwargs['stdin_raw_newlines'] = kwargs['stdin_raw_newlines']
if umask is not None:
_umask = six.text_type(umask).lstrip('0')
if _umask == '':
msg = 'Zero umask is not allowed.'
raise CommandExecutionError(msg)
try:
_umask = int(_umask, 8)
except ValueError:
raise CommandExecutionError("Invalid umask: '{0}'".format(umask))
else:
_umask = None
if runas or group or umask:
new_kwargs['preexec_fn'] = functools.partial(
salt.utils.user.chugid_and_umask,
runas,
_umask,
group)
if not salt.utils.platform.is_windows():
# close_fds is not supported on Windows platforms if you redirect
# stdin/stdout/stderr
if new_kwargs['shell'] is True:
new_kwargs['executable'] = shell
new_kwargs['close_fds'] = True
if not os.path.isabs(cwd) or not os.path.isdir(cwd):
raise CommandExecutionError(
'Specified cwd \'{0}\' either not absolute or does not exist'
.format(cwd)
)
if python_shell is not True \
and not salt.utils.platform.is_windows() \
and not isinstance(cmd, list):
cmd = salt.utils.args.shlex_split(cmd)
if success_retcodes is None:
success_retcodes = [0]
else:
try:
success_retcodes = [int(i) for i in
salt.utils.args.split_input(
success_retcodes
)]
except ValueError:
raise SaltInvocationError(
'success_retcodes must be a list of integers'
)
if success_stdout is None:
success_stdout = []
else:
try:
success_stdout = [i for i in
salt.utils.args.split_input(
success_stdout
)]
except ValueError:
raise SaltInvocationError(
'success_stdout must be a list of integers'
)
if success_stderr is None:
success_stderr = []
else:
try:
success_stderr = [i for i in
salt.utils.args.split_input(
success_stderr
)]
except ValueError:
raise SaltInvocationError(
'success_stderr must be a list of integers'
)
if not use_vt:
# This is where the magic happens
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **new_kwargs)
except (OSError, IOError) as exc:
msg = (
'Unable to run command \'{0}\' with the context \'{1}\', '
'reason: {2}'.format(
cmd if output_loglevel is not None else 'REDACTED',
new_kwargs,
exc
)
)
raise CommandExecutionError(msg)
try:
proc.run()
except TimedProcTimeoutError as exc:
ret['stdout'] = six.text_type(exc)
ret['stderr'] = ''
ret['retcode'] = None
ret['pid'] = proc.process.pid
# ok return code for timeouts?
ret['retcode'] = 1
return ret
if output_loglevel != 'quiet' and output_encoding is not None:
log.debug('Decoding output from command %s using %s encoding',
cmd, output_encoding)
try:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding)
except TypeError:
# stdout is None
out = ''
except UnicodeDecodeError:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', cmd
)
try:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding)
except TypeError:
# stderr is None
err = ''
except UnicodeDecodeError:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', cmd
)
if rstrip:
if out is not None:
out = out.rstrip()
if err is not None:
err = err.rstrip()
ret['pid'] = proc.process.pid
ret['retcode'] = proc.process.returncode
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
ret['stdout'] = out
ret['stderr'] = err
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
else:
formatted_timeout = ''
if timeout:
formatted_timeout = ' (timeout: {0}s)'.format(timeout)
if output_loglevel is not None:
msg = 'Running {0} in VT{1}'.format(cmd, formatted_timeout)
log.debug(log_callback(msg))
stdout, stderr = '', ''
now = time.time()
if timeout:
will_timeout = now + timeout
else:
will_timeout = -1
try:
proc = salt.utils.vt.Terminal(
cmd,
shell=True,
log_stdout=True,
log_stderr=True,
cwd=cwd,
preexec_fn=new_kwargs.get('preexec_fn', None),
env=run_env,
log_stdin_level=output_loglevel,
log_stdout_level=output_loglevel,
log_stderr_level=output_loglevel,
stream_stdout=True,
stream_stderr=True
)
ret['pid'] = proc.pid
while proc.has_unread_data:
try:
try:
time.sleep(0.5)
try:
cstdout, cstderr = proc.recv()
except IOError:
cstdout, cstderr = '', ''
if cstdout:
stdout += cstdout
else:
cstdout = ''
if cstderr:
stderr += cstderr
else:
cstderr = ''
if timeout and (time.time() > will_timeout):
ret['stderr'] = (
'SALT: Timeout after {0}s\n{1}').format(
timeout, stderr)
ret['retcode'] = None
break
except KeyboardInterrupt:
ret['stderr'] = 'SALT: User break\n{0}'.format(stderr)
ret['retcode'] = 1
break
except salt.utils.vt.TerminalException as exc:
log.error('VT: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
ret = {'retcode': 1, 'pid': '2'}
break
# only set stdout on success as we already mangled in other
# cases
ret['stdout'] = stdout
if not proc.isalive():
# Process terminated, i.e., not canceled by the user or by
# the timeout
ret['stderr'] = stderr
ret['retcode'] = proc.exitstatus
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
ret['pid'] = proc.pid
finally:
proc.close(terminate=True, kill=True)
try:
if ignore_retcode:
__context__['retcode'] = 0
else:
__context__['retcode'] = ret['retcode']
except NameError:
# Ignore the context error during grain generation
pass
# Log the output
if output_loglevel is not None:
if not ignore_retcode and ret['retcode'] != 0:
if output_loglevel < LOG_LEVELS['error']:
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if ret['stdout']:
log.log(output_loglevel, 'stdout: %s', log_callback(ret['stdout']))
if ret['stderr']:
log.log(output_loglevel, 'stderr: %s', log_callback(ret['stderr']))
if ret['retcode']:
log.log(output_loglevel, 'retcode: %s', ret['retcode'])
return ret
def _run_quiet(cmd,
cwd=None,
stdin=None,
output_encoding=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)['stdout']
def _run_all_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
output_encoding=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup.
Returns a dict of return data.
output_loglevel argument is ignored. This is here for when we alias
cmd.run_all directly to _run_all_quiet in certain chicken-and-egg
situations where modules need to work both before and after
the __salt__ dictionary is populated (cf dracr.py)
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)
def run(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
encoded_cmd=False,
raise_err=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
Execute the passed command and return the output as a string
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run 'echo '\''h=\"baz\"'\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If ``False``, let python handle the positional
arguments. Set to ``True`` to use shell features, such as pipes or
redirection.
:param bool bg: If ``True``, run command in background and do not await or
deliver it's results
.. versionadded:: 2016.3.0
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
:param bool raise_err: If ``True`` and the command has a nonzero exit code,
a CommandExecutionError exception will be raised.
.. warning::
This function does not process commands through a shell
unless the python_shell flag is set to True. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or
have the python_shell=True flag set here.
The use of python_shell=True means that the shell will accept _any_ input
including potentially malicious commands such as 'good_command;rm -rf /'.
Be absolutely certain that you have sanitized your input prior to using
python_shell=True
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run cmd='sed -e s/=/:/g'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
log_callback = _check_cb(log_callback)
lvl = _check_loglevel(output_loglevel)
if lvl is not None:
if not ignore_retcode and ret['retcode'] != 0:
if lvl < LOG_LEVELS['error']:
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if raise_err:
raise CommandExecutionError(
log_callback(ret['stdout'] if not hide_output else '')
)
log.log(lvl, 'output: %s', log_callback(ret['stdout']))
return ret['stdout'] if not hide_output else ''
def shell(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return the output as a string.
.. versionadded:: 2015.5.0
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.shell 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param int shell: Shell to execute under. Defaults to the system default
shell.
:param bool bg: If True, run command in background and do not await or
deliver its results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.shell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
.. warning::
This passes the cmd argument directly to the shell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.shell "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.shell template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.shell "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.shell "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.shell cmd='sed -e s/=/:/g'
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
return run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
def run_stdout(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command, and only return the standard out
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stdout 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stdout template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stdout "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stdout'] if not hide_output else ''
def run_stderr(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command and only return the standard error
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stderr 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stderr 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stderr "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stderr template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stderr "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stderr'] if not hide_output else ''
def run_all(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
redirect_stderr=False,
password=None,
encoded_cmd=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return a dict of return data
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_all 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
.. versionadded:: 2018.3.0
:param bool redirect_stderr: If set to ``True``, then stderr will be
redirected to stdout. This is helpful for cases where obtaining both
the retcode and output is desired, but it is not desired to have the
output separated into both stdout and stderr.
.. versionadded:: 2015.8.2
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param bool bg: If ``True``, run command in background and do not await or
deliver its results
.. versionadded:: 2016.3.6
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_all "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_all template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_all "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=stderr,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def retcode(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a shell command and return the command's return code.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.retcode 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.retcode 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:rtype: int
:rtype: None
:returns: Return Code as an int or None if there was an exception.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.retcode "file /bin/bash"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.retcode template=jinja "file {{grains.pythonpath[0]}}/python"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.retcode "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['retcode']
def _retcode_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Helper for running commands quietly for minion startup. Returns same as
the retcode() function.
'''
return retcode(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stderr,
success_stderr=success_stderr,
**kwargs)
def script(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
saltenv='base',
use_vt=False,
bg=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
.. code-block:: bash
salt myminion cmd.script salt://foo.sh "arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param bool bg: If True, run script in background and do not await or
deliver it's results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh
salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
def _cleanup_tempfile(path):
try:
__salt__['file.remove'](path)
except (SaltInvocationError, CommandExecutionError) as exc:
log.error(
'cmd.script: Unable to clean tempfile \'%s\': %s',
path, exc, exc_info_on_loglevel=logging.DEBUG
)
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
win_cwd = False
if salt.utils.platform.is_windows() and runas and cwd is None:
# Create a temp working directory
cwd = tempfile.mkdtemp(dir=__opts__['cachedir'])
win_cwd = True
salt.utils.win_dacl.set_permissions(obj_name=cwd,
principal=runas,
permissions='full_control')
path = salt.utils.files.mkstemp(dir=cwd, suffix=os.path.splitext(source)[1])
if template:
if 'pillarenv' in kwargs or 'pillar' in kwargs:
pillarenv = kwargs.get('pillarenv', __opts__.get('pillarenv'))
kwargs['pillar'] = _gather_pillar(pillarenv, kwargs.get('pillar'))
fn_ = __salt__['cp.get_template'](source,
path,
template,
saltenv,
**kwargs)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
else:
fn_ = __salt__['cp.cache_file'](source, saltenv)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
shutil.copyfile(fn_, path)
if not salt.utils.platform.is_windows():
os.chmod(path, 320)
os.chown(path, __salt__['file.user_to_uid'](runas), -1)
if salt.utils.platform.is_windows() and shell.lower() != 'powershell':
cmd_path = _cmd_quote(path, escape=False)
else:
cmd_path = _cmd_quote(path)
ret = _run(cmd_path + ' ' + six.text_type(args) if args else cmd_path,
cwd=cwd,
stdin=stdin,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def script_retcode(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template='jinja',
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
output_encoding=None,
output_loglevel='debug',
log_callback=None,
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
The script can also be formatted as a template, the default is jinja.
Only evaluate the script return code and do not block for terminal output
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
"arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script_retcode 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh
salt '*' cmd.script_retcode salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script_retcode salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
return script(source=source,
args=args,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)['retcode']
def which(cmd):
'''
Returns the path of an executable available on the minion, None otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.which cat
'''
return salt.utils.path.which(cmd)
def which_bin(cmds):
'''
Returns the first command found in a list of commands
CLI Example:
.. code-block:: bash
salt '*' cmd.which_bin '[pip2, pip, pip-python]'
'''
return salt.utils.path.which_bin(cmds)
def has_exec(cmd):
'''
Returns true if the executable is available on the minion, false otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.has_exec cat
'''
return which(cmd) is not None
def exec_code(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. The stdout will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code ruby 'puts "cheese"'
salt '*' cmd.exec_code ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
return exec_code_all(lang, code, cwd, args, **kwargs)['stdout']
def exec_code_all(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid)
will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code_all ruby 'puts "cheese"'
salt '*' cmd.exec_code_all ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
powershell = lang.lower().startswith("powershell")
if powershell:
codefile = salt.utils.files.mkstemp(suffix=".ps1")
else:
codefile = salt.utils.files.mkstemp()
with salt.utils.files.fopen(codefile, 'w+t', binary=False) as fp_:
fp_.write(salt.utils.stringutils.to_str(code))
if powershell:
cmd = [lang, "-File", codefile]
else:
cmd = [lang, codefile]
if isinstance(args, six.string_types):
cmd.append(args)
elif isinstance(args, list):
cmd += args
ret = run_all(cmd, cwd=cwd, python_shell=False, **kwargs)
os.remove(codefile)
return ret
def tty(device, echo=''):
'''
Echo a string to a specific tty
CLI Example:
.. code-block:: bash
salt '*' cmd.tty tty0 'This is a test'
salt '*' cmd.tty pts3 'This is a test'
'''
if device.startswith('tty'):
teletype = '/dev/{0}'.format(device)
elif device.startswith('pts'):
teletype = '/dev/{0}'.format(device.replace('pts', 'pts/'))
else:
return {'Error': 'The specified device is not a valid TTY'}
try:
with salt.utils.files.fopen(teletype, 'wb') as tty_device:
tty_device.write(salt.utils.stringutils.to_bytes(echo))
return {
'Success': 'Message was successfully echoed to {0}'.format(teletype)
}
except IOError:
return {
'Error': 'Echoing to {0} returned error'.format(teletype)
}
def run_chroot(root,
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=True,
binds=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='quiet',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
.. versionadded:: 2014.7.0
This function runs :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` wrapped
within a chroot, with dev and proc mounted in the chroot
:param str root: Path to the root of the jail to use.
:param str stdin: A string of standard input can be specified for
the command to be run using the ``stdin`` parameter. This can
be useful in cases where sensitive information must be read
from standard input.:
:param str runas: User to run script as.
:param str group: Group to run script as.
:param str shell: Shell to execute under. Defaults to the system
default shell.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:parar str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param list binds: List of directories that will be exported inside
the chroot with the bind option.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_chroot 'some command' env='{"FOO": "bar"}'
:param dict clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output
before it is returned.
:param str umask: The umask (in octal) to use when running the
command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout:
A timeout in seconds for the executed process to return.
:param bool use_vt:
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs. This is experimental.
:param success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' cmd.run_chroot /var/lib/lxc/container_name/rootfs 'sh /tmp/bootstrap.sh'
'''
__salt__['mount.mount'](
os.path.join(root, 'dev'),
'devtmpfs',
fstype='devtmpfs')
__salt__['mount.mount'](
os.path.join(root, 'proc'),
'proc',
fstype='proc')
__salt__['mount.mount'](
os.path.join(root, 'sys'),
'sysfs',
fstype='sysfs')
binds = binds if binds else []
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.mount'](
bind_exported_to,
bind_exported,
opts='default,bind')
# Execute chroot routine
sh_ = '/bin/sh'
if os.path.isfile(os.path.join(root, 'bin/bash')):
sh_ = '/bin/bash'
if isinstance(cmd, (list, tuple)):
cmd = ' '.join([six.text_type(i) for i in cmd])
cmd = 'chroot {0} {1} -c {2}'.format(root, sh_, _cmd_quote(cmd))
run_func = __context__.pop('cmd.run_chroot.func', run_all)
ret = run_func(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
pillarenv=kwargs.get('pillarenv'),
pillar=kwargs.get('pillar'),
use_vt=use_vt,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
bg=bg)
# Kill processes running in the chroot
for i in range(6):
pids = _chroot_pids(root)
if not pids:
break
for pid in pids:
# use sig 15 (TERM) for first 3 attempts, then 9 (KILL)
sig = 15 if i < 3 else 9
os.kill(pid, sig)
if _chroot_pids(root):
log.error('Processes running in chroot could not be killed, '
'filesystem will remain mounted')
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.umount'](bind_exported_to)
__salt__['mount.umount'](os.path.join(root, 'sys'))
__salt__['mount.umount'](os.path.join(root, 'proc'))
__salt__['mount.umount'](os.path.join(root, 'dev'))
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def _is_valid_shell(shell):
'''
Attempts to search for valid shells on a system and
see if a given shell is in the list
'''
if salt.utils.platform.is_windows():
return True # Don't even try this for Windows
shells = '/etc/shells'
available_shells = []
if os.path.exists(shells):
try:
with salt.utils.files.fopen(shells, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
if line.startswith('#'):
continue
else:
available_shells.append(line)
except OSError:
return True
else:
# No known method of determining available shells
return None
if shell in available_shells:
return True
else:
return False
def shells():
'''
Lists the valid shells on this system via the /etc/shells file
.. versionadded:: 2015.5.0
CLI Example::
salt '*' cmd.shells
'''
shells_fn = '/etc/shells'
ret = []
if os.path.exists(shells_fn):
try:
with salt.utils.files.fopen(shells_fn, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
line = line.strip()
if line.startswith('#'):
continue
elif not line:
continue
else:
ret.append(line)
except OSError:
log.error("File '%s' was not found", shells_fn)
return ret
def shell_info(shell, list_modules=False):
'''
.. versionadded:: 2016.11.0
Provides information about a shell or script languages which often use
``#!``. The values returned are dependent on the shell or scripting
languages all return the ``installed``, ``path``, ``version``,
``version_raw``
Args:
shell (str): Name of the shell. Support shells/script languages include
bash, cmd, perl, php, powershell, python, ruby and zsh
list_modules (bool): True to list modules available to the shell.
Currently only lists powershell modules.
Returns:
dict: A dictionary of information about the shell
.. code-block:: python
{'version': '<2 or 3 numeric components dot-separated>',
'version_raw': '<full version string>',
'path': '<full path to binary>',
'installed': <True, False or None>,
'<attribute>': '<attribute value>'}
.. note::
- ``installed`` is always returned, if ``None`` or ``False`` also
returns error and may also return ``stdout`` for diagnostics.
- ``version`` is for use in determine if a shell/script language has a
particular feature set, not for package management.
- The shell must be within the executable search path.
CLI Example:
.. code-block:: bash
salt '*' cmd.shell_info bash
salt '*' cmd.shell_info powershell
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
regex_shells = {
'bash': [r'version (\d\S*)', 'bash', '--version'],
'bash-test-error': [r'versioZ ([-\w.]+)', 'bash', '--version'], # used to test an error result
'bash-test-env': [r'(HOME=.*)', 'bash', '-c', 'declare'], # used to test an error result
'zsh': [r'^zsh (\d\S*)', 'zsh', '--version'],
'tcsh': [r'^tcsh (\d\S*)', 'tcsh', '--version'],
'cmd': [r'Version ([\d.]+)', 'cmd.exe', '/C', 'ver'],
'powershell': [r'PSVersion\s+(\d\S*)', 'powershell', '-NonInteractive', '$PSVersionTable'],
'perl': [r'^(\d\S*)', 'perl', '-e', 'printf "%vd\n", $^V;'],
'python': [r'^Python (\d\S*)', 'python', '-V'],
'ruby': [r'^ruby (\d\S*)', 'ruby', '-v'],
'php': [r'^PHP (\d\S*)', 'php', '-v']
}
# Ensure ret['installed'] always as a value of True, False or None (not sure)
ret = {'installed': False}
if salt.utils.platform.is_windows() and shell == 'powershell':
pw_keys = salt.utils.win_reg.list_keys(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell')
pw_keys.sort(key=int)
if not pw_keys:
return {
'error': 'Unable to locate \'powershell\' Reason: Cannot be '
'found in registry.',
'installed': False,
}
for reg_ver in pw_keys:
install_data = salt.utils.win_reg.read_value(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}'.format(reg_ver),
vname='Install')
if install_data.get('vtype') == 'REG_DWORD' and \
install_data.get('vdata') == 1:
details = salt.utils.win_reg.list_values(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}\\'
'PowerShellEngine'.format(reg_ver))
# reset data, want the newest version details only as powershell
# is backwards compatible
ret = {}
# if all goes well this will become True
ret['installed'] = None
ret['path'] = which('powershell.exe')
for attribute in details:
if attribute['vname'].lower() == '(default)':
continue
elif attribute['vname'].lower() == 'powershellversion':
ret['psversion'] = attribute['vdata']
ret['version_raw'] = attribute['vdata']
elif attribute['vname'].lower() == 'runtimeversion':
ret['crlversion'] = attribute['vdata']
if ret['crlversion'][0].lower() == 'v':
ret['crlversion'] = ret['crlversion'][1::]
elif attribute['vname'].lower() == 'pscompatibleversion':
# reg attribute does not end in s, the powershell
# attribute does
ret['pscompatibleversions'] = \
attribute['vdata'].replace(' ', '').split(',')
else:
# keys are lower case as python is case sensitive the
# registry is not
ret[attribute['vname'].lower()] = attribute['vdata']
else:
if shell not in regex_shells:
return {
'error': 'Salt does not know how to get the version number for '
'{0}'.format(shell),
'installed': None
}
shell_data = regex_shells[shell]
pattern = shell_data.pop(0)
# We need to make sure HOME set, so shells work correctly
# salt-call will general have home set, the salt-minion service may not
# We need to assume ports of unix shells to windows will look after
# themselves in setting HOME as they do it in many different ways
newenv = os.environ
if ('HOME' not in newenv) and (not salt.utils.platform.is_windows()):
newenv['HOME'] = os.path.expanduser('~')
log.debug('HOME environment set to %s', newenv['HOME'])
try:
proc = salt.utils.timed_subprocess.TimedProc(
shell_data,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=10,
env=newenv
)
except (OSError, IOError) as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: {1}'.format(' '.join(shell_data), exc),
'installed': False,
}
try:
proc.run()
except TimedProcTimeoutError as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: Timed out.'.format(' '.join(shell_data)),
'installed': False,
}
ret['path'] = which(shell_data[0])
pattern_result = re.search(pattern, proc.stdout, flags=re.IGNORECASE)
# only set version if we find it, so code later on can deal with it
if pattern_result:
ret['version_raw'] = pattern_result.group(1)
if 'version_raw' in ret:
version_results = re.match(r'(\d[\d.]*)', ret['version_raw'])
if version_results:
ret['installed'] = True
ver_list = version_results.group(1).split('.')[:3]
if len(ver_list) == 1:
ver_list.append('0')
ret['version'] = '.'.join(ver_list[:3])
else:
ret['installed'] = None # Have an unexpected result
# Get a list of the PowerShell modules which are potentially available
# to be imported
if shell == 'powershell' and ret['installed'] and list_modules:
ret['modules'] = salt.utils.powershell.get_modules()
if 'version' not in ret:
ret['error'] = 'The version regex pattern for shell {0}, could not ' \
'find the version string'.format(shell)
ret['stdout'] = proc.stdout # include stdout so they can see the issue
log.error(ret['error'])
return ret
def powershell(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return the output as a dictionary.
Other ``cmd.*`` functions (besides ``cmd.powershell_all``)
return the raw text output of the command. This
function appends ``| ConvertTo-JSON`` to the command and then parses the
JSON into a Python dictionary. If you want the raw textual result of your
PowerShell command you should use ``cmd.run`` with the ``shell=powershell``
option.
For example:
.. code-block:: bash
salt '*' cmd.run '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2016.3.0
.. warning::
This passes the cmd argument directly to PowerShell
without any further processing! Be absolutely sure that you
have properly sanitized the command passed to this function
and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in cases
where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
.. versionadded:: 2016.3.4
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:returns:
:dict: A dictionary of data returned by the powershell command.
CLI Example:
.. code-block:: powershell
salt '*' cmd.powershell "$PSVersionTable.CLRVersion"
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
# ConvertTo-JSON is only available on PowerShell 3.0 and later
psversion = shell_info('powershell')['psversion']
if salt.utils.versions.version_cmp(psversion, '2.0') == 1:
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Put the whole command inside a try / catch block
# Some errors in PowerShell are not "Terminating Errors" and will not be
# caught in a try/catch block. For example, the `Get-WmiObject` command will
# often return a "Non Terminating Error". To fix this, make sure
# `-ErrorAction Stop` is set in the powershell command
cmd = 'try {' + cmd + '} catch { "{}" }'
# Retrieve the response, while overriding shell with 'powershell'
response = run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
try:
return salt.utils.json.loads(response)
except Exception:
log.error("Error converting PowerShell JSON return", exc_info=True)
return {}
def powershell_all(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
quiet=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
force_list=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return a dictionary with a result
field representing the output of the command, as well as other fields
showing us what the PowerShell invocation wrote to ``stderr``, the process
id, and the exit code of the invocation.
This function appends ``| ConvertTo-JSON`` to the command before actually
invoking powershell.
An unquoted empty string is not valid JSON, but it's very normal for the
Powershell output to be exactly that. Therefore, we do not attempt to parse
empty Powershell output (which would result in an exception). Instead we
treat this as a special case and one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field of the return dictionary will be an empty list.
- If the value of the ``force_list`` parameter is ``False``, then the
return dictionary **will not have a result key added to it**. We aren't
setting ``result`` to ``None`` in this case, because ``None`` is the
Python representation of "null" in JSON. (We likewise can't use ``False``
for the equivalent reason.)
If Powershell's output is not an empty string and Python cannot parse its
content, then a ``CommandExecutionError`` exception will be raised.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is other than ``list``
then one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field will be a singleton list with the Python object as its
sole member.
- If the value of the ``force_list`` parameter is ``False``, then the value
of ``result`` will be the unmodified Python object.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is ``list``, then the
value of ``result`` will be the unmodified Python object. The
``force_list`` parameter has no effect in this case.
.. note::
An example of why the ``force_list`` parameter is useful is as
follows: The Powershell command ``dir x | Convert-ToJson`` results in
- no output when x is an empty directory.
- a dictionary object when x contains just one item.
- a list of dictionary objects when x contains multiple items.
By setting ``force_list`` to ``True`` we will always end up with a
list of dictionary items, representing files, no matter how many files
x contains. Conversely, if ``force_list`` is ``False``, we will end
up with no ``result`` key in our return dictionary when x is an empty
directory, and a dictionary object when x contains just one file.
If you want a similar function but with a raw textual result instead of a
Python dictionary, you should use ``cmd.run_all`` in combination with
``shell=powershell``.
The remaining fields in the return dictionary are described in more detail
in the ``Returns`` section.
Example:
.. code-block:: bash
salt '*' cmd.run_all '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run_all 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2018.3.0
.. warning::
This passes the cmd argument directly to PowerShell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param bool force_list: The purpose of this parameter is described in the
preamble of this function's documentation. Default value is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:return: A dictionary with the following entries:
result
For a complete description of this field, please refer to this
function's preamble. **This key will not be added to the dictionary
when force_list is False and Powershell's output is the empty
string.**
stderr
What the PowerShell invocation wrote to ``stderr``.
pid
The process id of the PowerShell invocation
retcode
This is the exit code of the invocation of PowerShell.
If the final execution status (in PowerShell) of our command
(with ``| ConvertTo-JSON`` appended) is ``False`` this should be non-0.
Likewise if PowerShell exited with ``$LASTEXITCODE`` set to some
non-0 value, then ``retcode`` will end up with this value.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "$PSVersionTable.CLRVersion"
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "dir mydirectory" force_list=True
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Retrieve the response, while overriding shell with 'powershell'
response = run_all(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
quiet=quiet,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
stdoutput = response['stdout']
# if stdoutput is the empty string and force_list is True we return an empty list
# Otherwise we return response with no result key
if not stdoutput:
response.pop('stdout')
if force_list:
response['result'] = []
return response
# If we fail to parse stdoutput we will raise an exception
try:
result = salt.utils.json.loads(stdoutput)
except Exception:
err_msg = "cmd.powershell_all " + \
"cannot parse the Powershell output."
response["cmd"] = cmd
raise CommandExecutionError(
message=err_msg,
info=response
)
response.pop("stdout")
if type(result) is not list:
if force_list:
response['result'] = [result]
else:
response['result'] = result
else:
# result type is list so the force_list param has no effect
response['result'] = result
return response
def run_bg(cmd,
cwd=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
timeout=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
.. versionadded: 2016.3.0
Execute the passed command in the background and return it's PID
.. note::
If the init system is systemd and the backgrounded task should run even
if the salt-minion process is restarted, prepend ``systemd-run
--scope`` to the command. This will reparent the process in its own
scope separate from salt-minion, and will not be affected by restarting
the minion service.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Shell to execute under. Defaults to the system default
shell.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_bg 'echo '\''h=\"baz\"'\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_bg 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param int timeout: A timeout in seconds for the executed process to return.
.. warning::
This function does not process commands through a shell unless the
``python_shell`` argument is set to ``True``. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or have the
python_shell=True flag set here.
The use of ``python_shell=True`` means that the shell will accept _any_
input including potentially malicious commands such as 'good_command;rm
-rf /'. Be absolutely certain that you have sanitized your input prior
to using ``python_shell=True``.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_bg "fstrim-all"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_bg template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run_bg "Get-ChildItem C:\\ " shell='powershell'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run_bg cmd='ls -lR / | sed -e s/=/:/g > /tmp/dontwait'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
res = _run(cmd,
stdin=None,
stderr=None,
stdout=None,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
use_vt=None,
bg=True,
with_communicate=False,
rstrip=False,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
umask=umask,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs
)
return {
'pid': res['pid']
}
|
saltstack/salt
|
salt/modules/cmdmod.py
|
_gather_pillar
|
python
|
def _gather_pillar(pillarenv, pillar_override):
'''
Whenever a state run starts, gather the pillar data fresh
'''
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
pillar_override=pillar_override,
pillarenv=pillarenv
)
ret = pillar.compile_pillar()
if pillar_override and isinstance(pillar_override, dict):
ret.update(pillar_override)
return ret
|
Whenever a state run starts, gather the pillar data fresh
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cmdmod.py#L204-L219
| null |
# -*- coding: utf-8 -*-
'''
A module for shelling out.
Keep in mind that this module is insecure, in that it can give whomever has
access to the master root execution access to all salt minions.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import functools
import glob
import logging
import os
import shutil
import subprocess
import sys
import time
import traceback
import fnmatch
import base64
import re
import tempfile
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.powershell
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.timed_subprocess
import salt.utils.user
import salt.utils.versions
import salt.utils.vt
import salt.utils.win_dacl
import salt.utils.win_reg
import salt.grains.extra
from salt.ext import six
from salt.exceptions import CommandExecutionError, TimedProcTimeoutError, \
SaltInvocationError
from salt.log import LOG_LEVELS
from salt.ext.six.moves import range, zip, map
# Only available on POSIX systems, nonfatal on windows
try:
import pwd
import grp
except ImportError:
pass
if salt.utils.platform.is_windows():
from salt.utils.win_runas import runas as win_runas
from salt.utils.win_functions import escape_argument as _cmd_quote
HAS_WIN_RUNAS = True
else:
from salt.ext.six.moves import shlex_quote as _cmd_quote
HAS_WIN_RUNAS = False
__proxyenabled__ = ['*']
# Define the module's virtual name
__virtualname__ = 'cmd'
# Set up logging
log = logging.getLogger(__name__)
DEFAULT_SHELL = salt.grains.extra.shell()['shell']
# Overwriting the cmd python module makes debugging modules with pdb a bit
# harder so lets do it this way instead.
def __virtual__():
return __virtualname__
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns
the value passed.
'''
if cb_ is not None:
if hasattr(cb_, '__call__'):
return cb_
else:
log.error('log_callback is not callable, ignoring')
return lambda x: x
def _python_shell_default(python_shell, __pub_jid):
'''
Set python_shell default based on remote execution and __opts__['cmd_safe']
'''
try:
# Default to python_shell=True when run directly from remote execution
# system. Cross-module calls won't have a jid.
if __pub_jid and python_shell is None:
return True
elif __opts__.get('cmd_safe', True) is False and python_shell is None:
# Override-switch for python_shell
return True
except NameError:
pass
return python_shell
def _chroot_pids(chroot):
pids = []
for root in glob.glob('/proc/[0-9]*/root'):
try:
link = os.path.realpath(root)
if link.startswith(chroot):
pids.append(int(os.path.basename(
os.path.dirname(root)
)))
except OSError:
pass
return pids
def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):
'''
If template is a valid template engine, process the cmd and cwd through
that engine.
'''
if not template:
return (cmd, cwd)
# render the path as a template using path_template_engine as the engine
if template not in salt.utils.templates.TEMPLATE_REGISTRY:
raise CommandExecutionError(
'Attempted to render file paths with unavailable engine '
'{0}'.format(template)
)
kwargs = {}
kwargs['salt'] = __salt__
if pillarenv is not None or pillar_override is not None:
pillarenv = pillarenv or __opts__['pillarenv']
kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override)
else:
kwargs['pillar'] = __pillar__
kwargs['grains'] = __grains__
kwargs['opts'] = __opts__
kwargs['saltenv'] = saltenv
def _render(contents):
# write out path to temp file
tmp_path_fn = salt.utils.files.mkstemp()
with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(contents))
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
tmp_path_fn,
to_str=True,
**kwargs
)
salt.utils.files.safe_rm(tmp_path_fn)
if not data['result']:
# Failed to render the template
raise CommandExecutionError(
'Failed to execute cmd with error: {0}'.format(
data['data']
)
)
else:
return data['data']
cmd = _render(cmd)
cwd = _render(cwd)
return (cmd, cwd)
def _check_loglevel(level='info'):
'''
Retrieve the level code for use in logging.Logger.log().
'''
try:
level = level.lower()
if level == 'quiet':
return None
else:
return LOG_LEVELS[level]
except (AttributeError, KeyError):
log.error(
'Invalid output_loglevel \'%s\'. Valid levels are: %s. Falling '
'back to \'info\'.',
level, ', '.join(sorted(LOG_LEVELS, reverse=True))
)
return LOG_LEVELS['info']
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
return env
def _check_avail(cmd):
'''
Check to see if the given command can be run
'''
if isinstance(cmd, list):
cmd = ' '.join([six.text_type(x) if not isinstance(x, six.string_types) else x
for x in cmd])
bret = True
wret = False
if __salt__['config.get']('cmd_blacklist_glob'):
blist = __salt__['config.get']('cmd_blacklist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# BAD! you are blacklisted
bret = False
if __salt__['config.get']('cmd_whitelist_glob', []):
blist = __salt__['config.get']('cmd_whitelist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# GOOD! You are whitelisted
wret = True
break
else:
# If no whitelist set then alls good!
wret = True
return bret and wret
def _run(cmd,
cwd=None,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
prepend_path=None,
rstrip=True,
template=None,
umask=None,
timeout=None,
with_communicate=True,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
pillarenv=None,
pillar_override=None,
use_vt=False,
password=None,
bg=False,
encoded_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Do the DRY thing and only call subprocess.Popen() once
'''
if 'pillar' in kwargs and not pillar_override:
pillar_override = kwargs['pillar']
if output_loglevel != 'quiet' and _is_valid_shell(shell) is False:
log.warning(
'Attempt to run a shell command with what may be an invalid shell! '
'Check to ensure that the shell <%s> is valid for this user.',
shell
)
output_loglevel = _check_loglevel(output_loglevel)
log_callback = _check_cb(log_callback)
use_sudo = False
if runas is None and '__context__' in globals():
runas = __context__.get('runas')
if password is None and '__context__' in globals():
password = __context__.get('runas_password')
# Set the default working directory to the home directory of the user
# salt-minion is running as. Defaults to home directory of user under which
# the minion is running.
if not cwd:
cwd = os.path.expanduser('~{0}'.format('' if not runas else runas))
# make sure we can access the cwd
# when run from sudo or another environment where the euid is
# changed ~ will expand to the home of the original uid and
# the euid might not have access to it. See issue #1844
if not os.access(cwd, os.R_OK):
cwd = '/'
if salt.utils.platform.is_windows():
cwd = os.path.abspath(os.sep)
else:
# Handle edge cases where numeric/other input is entered, and would be
# yaml-ified into non-string types
cwd = six.text_type(cwd)
if bg:
ignore_retcode = True
use_vt = False
if not salt.utils.platform.is_windows():
if not os.path.isfile(shell) or not os.access(shell, os.X_OK):
msg = 'The shell {0} is not available'.format(shell)
raise CommandExecutionError(msg)
if salt.utils.platform.is_windows() and use_vt: # Memozation so not much overhead
raise CommandExecutionError('VT not available on windows')
if shell.lower().strip() == 'powershell':
# Strip whitespace
if isinstance(cmd, six.string_types):
cmd = cmd.strip()
# If we were called by script(), then fakeout the Windows
# shell to run a Powershell script.
# Else just run a Powershell command.
stack = traceback.extract_stack(limit=2)
# extract_stack() returns a list of tuples.
# The last item in the list [-1] is the current method.
# The third item[2] in each tuple is the name of that method.
if stack[-2][2] == 'script':
cmd = 'Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -File ' + cmd
elif encoded_cmd:
cmd = 'Powershell -NonInteractive -EncodedCommand {0}'.format(cmd)
else:
cmd = 'Powershell -NonInteractive -NoProfile "{0}"'.format(cmd.replace('"', '\\"'))
# munge the cmd and cwd through the template
(cmd, cwd) = _render_cmd(cmd, cwd, template, saltenv, pillarenv, pillar_override)
ret = {}
# If the pub jid is here then this is a remote ex or salt call command and needs to be
# checked if blacklisted
if '__pub_jid' in kwargs:
if not _check_avail(cmd):
raise CommandExecutionError(
'The shell command "{0}" is not permitted'.format(cmd)
)
env = _parse_env(env)
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, six.string_types) else x for x in cmd]
elif isinstance(cmd, six.string_types):
return cmd.strip()
else:
return cmd
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' parameter.
msg = (
'Executing command {0}{1}{0} {2}{3}in directory \'{4}\'{5}'.format(
'\'' if not isinstance(cmd, list) else '',
_get_stripped(cmd),
'as user \'{0}\' '.format(runas) if runas else '',
'in group \'{0}\' '.format(group) if group else '',
cwd,
'. Executing command in the background, no output will be '
'logged.' if bg else ''
)
)
log.info(log_callback(msg))
if runas and salt.utils.platform.is_windows():
if not HAS_WIN_RUNAS:
msg = 'missing salt/utils/win_runas.py'
raise CommandExecutionError(msg)
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(cmd)
return win_runas(cmd, runas, password, cwd)
if runas and salt.utils.platform.is_darwin():
# we need to insert the user simulation into the command itself and not
# just run it from the environment on macOS as that
# method doesn't work properly when run as root for certain commands.
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(map(_cmd_quote, cmd))
cmd = 'su -l {0} -c "cd {1}; {2}"'.format(runas, cwd, cmd)
# set runas to None, because if you try to run `su -l` as well as
# simulate the environment macOS will prompt for the password of the
# user and will cause salt to hang.
runas = None
if runas:
# Save the original command before munging it
try:
pwd.getpwnam(runas)
except KeyError:
raise CommandExecutionError(
'User \'{0}\' is not available'.format(runas)
)
if group:
if salt.utils.platform.is_windows():
msg = 'group is not currently available on Windows'
raise SaltInvocationError(msg)
if not which_bin(['sudo']):
msg = 'group argument requires sudo but not found'
raise CommandExecutionError(msg)
try:
grp.getgrnam(group)
except KeyError:
raise CommandExecutionError(
'Group \'{0}\' is not available'.format(runas)
)
else:
use_sudo = True
if runas or group:
try:
# Getting the environment for the runas user
# Use markers to thwart any stdout noise
# There must be a better way to do this.
import uuid
marker = '<<<' + str(uuid.uuid4()) + '>>>'
marker_b = marker.encode(__salt_system_encoding__)
py_code = (
'import sys, os, itertools; '
'sys.stdout.write(\"' + marker + '\"); '
'sys.stdout.write(\"\\0\".join(itertools.chain(*os.environ.items()))); '
'sys.stdout.write(\"' + marker + '\");'
)
if use_sudo or __grains__['os'] in ['MacOS', 'Darwin']:
env_cmd = ['sudo']
# runas is optional if use_sudo is set.
if runas:
env_cmd.extend(['-u', runas])
if group:
env_cmd.extend(['-g', group])
if shell != DEFAULT_SHELL:
env_cmd.extend(['-s', '--', shell, '-c'])
else:
env_cmd.extend(['-i', '--'])
env_cmd.extend([sys.executable])
elif __grains__['os'] in ['FreeBSD']:
env_cmd = ('su', '-', runas, '-c',
"{0} -c {1}".format(shell, sys.executable))
elif __grains__['os_family'] in ['Solaris']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
elif __grains__['os_family'] in ['AIX']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
else:
env_cmd = ('su', '-s', shell, '-', runas, '-c', sys.executable)
msg = 'env command: {0}'.format(env_cmd)
log.debug(log_callback(msg))
env_bytes, env_encoded_err = subprocess.Popen(
env_cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
).communicate(salt.utils.stringutils.to_bytes(py_code))
marker_count = env_bytes.count(marker_b)
if marker_count == 0:
# Possibly PAM prevented the login
log.error(
'Environment could not be retrieved for user \'%s\': '
'stderr=%r stdout=%r',
runas, env_encoded_err, env_bytes
)
# Ensure that we get an empty env_runas dict below since we
# were not able to get the environment.
env_bytes = b''
elif marker_count != 2:
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\'',
info={'stderr': repr(env_encoded_err),
'stdout': repr(env_bytes)}
)
else:
# Strip the marker
env_bytes = env_bytes.split(marker_b)[1]
if six.PY2:
import itertools
env_runas = dict(itertools.izip(*[iter(env_bytes.split(b'\0'))]*2))
elif six.PY3:
env_runas = dict(list(zip(*[iter(env_bytes.split(b'\0'))]*2)))
env_runas = dict(
(salt.utils.stringutils.to_str(k),
salt.utils.stringutils.to_str(v))
for k, v in six.iteritems(env_runas)
)
env_runas.update(env)
# Fix platforms like Solaris that don't set a USER env var in the
# user's default environment as obtained above.
if env_runas.get('USER') != runas:
env_runas['USER'] = runas
# Fix some corner cases where shelling out to get the user's
# environment returns the wrong home directory.
runas_home = os.path.expanduser('~{0}'.format(runas))
if env_runas.get('HOME') != runas_home:
env_runas['HOME'] = runas_home
env = env_runas
except ValueError as exc:
log.exception('Error raised retrieving environment for user %s', runas)
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\': {1}'.format(
runas, exc
)
)
if reset_system_locale is True:
if not salt.utils.platform.is_windows():
# Default to C!
# Salt only knows how to parse English words
# Don't override if the user has passed LC_ALL
env.setdefault('LC_CTYPE', 'C')
env.setdefault('LC_NUMERIC', 'C')
env.setdefault('LC_TIME', 'C')
env.setdefault('LC_COLLATE', 'C')
env.setdefault('LC_MONETARY', 'C')
env.setdefault('LC_MESSAGES', 'C')
env.setdefault('LC_PAPER', 'C')
env.setdefault('LC_NAME', 'C')
env.setdefault('LC_ADDRESS', 'C')
env.setdefault('LC_TELEPHONE', 'C')
env.setdefault('LC_MEASUREMENT', 'C')
env.setdefault('LC_IDENTIFICATION', 'C')
env.setdefault('LANGUAGE', 'C')
else:
# On Windows set the codepage to US English.
if python_shell:
cmd = 'chcp 437 > nul & ' + cmd
if clean_env:
run_env = env
else:
run_env = os.environ.copy()
run_env.update(env)
if prepend_path:
run_env['PATH'] = ':'.join((prepend_path, run_env['PATH']))
if python_shell is None:
python_shell = False
new_kwargs = {'cwd': cwd,
'shell': python_shell,
'env': run_env if six.PY3 else salt.utils.data.encode(run_env),
'stdin': six.text_type(stdin) if stdin is not None else stdin,
'stdout': stdout,
'stderr': stderr,
'with_communicate': with_communicate,
'timeout': timeout,
'bg': bg,
}
if 'stdin_raw_newlines' in kwargs:
new_kwargs['stdin_raw_newlines'] = kwargs['stdin_raw_newlines']
if umask is not None:
_umask = six.text_type(umask).lstrip('0')
if _umask == '':
msg = 'Zero umask is not allowed.'
raise CommandExecutionError(msg)
try:
_umask = int(_umask, 8)
except ValueError:
raise CommandExecutionError("Invalid umask: '{0}'".format(umask))
else:
_umask = None
if runas or group or umask:
new_kwargs['preexec_fn'] = functools.partial(
salt.utils.user.chugid_and_umask,
runas,
_umask,
group)
if not salt.utils.platform.is_windows():
# close_fds is not supported on Windows platforms if you redirect
# stdin/stdout/stderr
if new_kwargs['shell'] is True:
new_kwargs['executable'] = shell
new_kwargs['close_fds'] = True
if not os.path.isabs(cwd) or not os.path.isdir(cwd):
raise CommandExecutionError(
'Specified cwd \'{0}\' either not absolute or does not exist'
.format(cwd)
)
if python_shell is not True \
and not salt.utils.platform.is_windows() \
and not isinstance(cmd, list):
cmd = salt.utils.args.shlex_split(cmd)
if success_retcodes is None:
success_retcodes = [0]
else:
try:
success_retcodes = [int(i) for i in
salt.utils.args.split_input(
success_retcodes
)]
except ValueError:
raise SaltInvocationError(
'success_retcodes must be a list of integers'
)
if success_stdout is None:
success_stdout = []
else:
try:
success_stdout = [i for i in
salt.utils.args.split_input(
success_stdout
)]
except ValueError:
raise SaltInvocationError(
'success_stdout must be a list of integers'
)
if success_stderr is None:
success_stderr = []
else:
try:
success_stderr = [i for i in
salt.utils.args.split_input(
success_stderr
)]
except ValueError:
raise SaltInvocationError(
'success_stderr must be a list of integers'
)
if not use_vt:
# This is where the magic happens
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **new_kwargs)
except (OSError, IOError) as exc:
msg = (
'Unable to run command \'{0}\' with the context \'{1}\', '
'reason: {2}'.format(
cmd if output_loglevel is not None else 'REDACTED',
new_kwargs,
exc
)
)
raise CommandExecutionError(msg)
try:
proc.run()
except TimedProcTimeoutError as exc:
ret['stdout'] = six.text_type(exc)
ret['stderr'] = ''
ret['retcode'] = None
ret['pid'] = proc.process.pid
# ok return code for timeouts?
ret['retcode'] = 1
return ret
if output_loglevel != 'quiet' and output_encoding is not None:
log.debug('Decoding output from command %s using %s encoding',
cmd, output_encoding)
try:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding)
except TypeError:
# stdout is None
out = ''
except UnicodeDecodeError:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', cmd
)
try:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding)
except TypeError:
# stderr is None
err = ''
except UnicodeDecodeError:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', cmd
)
if rstrip:
if out is not None:
out = out.rstrip()
if err is not None:
err = err.rstrip()
ret['pid'] = proc.process.pid
ret['retcode'] = proc.process.returncode
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
ret['stdout'] = out
ret['stderr'] = err
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
else:
formatted_timeout = ''
if timeout:
formatted_timeout = ' (timeout: {0}s)'.format(timeout)
if output_loglevel is not None:
msg = 'Running {0} in VT{1}'.format(cmd, formatted_timeout)
log.debug(log_callback(msg))
stdout, stderr = '', ''
now = time.time()
if timeout:
will_timeout = now + timeout
else:
will_timeout = -1
try:
proc = salt.utils.vt.Terminal(
cmd,
shell=True,
log_stdout=True,
log_stderr=True,
cwd=cwd,
preexec_fn=new_kwargs.get('preexec_fn', None),
env=run_env,
log_stdin_level=output_loglevel,
log_stdout_level=output_loglevel,
log_stderr_level=output_loglevel,
stream_stdout=True,
stream_stderr=True
)
ret['pid'] = proc.pid
while proc.has_unread_data:
try:
try:
time.sleep(0.5)
try:
cstdout, cstderr = proc.recv()
except IOError:
cstdout, cstderr = '', ''
if cstdout:
stdout += cstdout
else:
cstdout = ''
if cstderr:
stderr += cstderr
else:
cstderr = ''
if timeout and (time.time() > will_timeout):
ret['stderr'] = (
'SALT: Timeout after {0}s\n{1}').format(
timeout, stderr)
ret['retcode'] = None
break
except KeyboardInterrupt:
ret['stderr'] = 'SALT: User break\n{0}'.format(stderr)
ret['retcode'] = 1
break
except salt.utils.vt.TerminalException as exc:
log.error('VT: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
ret = {'retcode': 1, 'pid': '2'}
break
# only set stdout on success as we already mangled in other
# cases
ret['stdout'] = stdout
if not proc.isalive():
# Process terminated, i.e., not canceled by the user or by
# the timeout
ret['stderr'] = stderr
ret['retcode'] = proc.exitstatus
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
ret['pid'] = proc.pid
finally:
proc.close(terminate=True, kill=True)
try:
if ignore_retcode:
__context__['retcode'] = 0
else:
__context__['retcode'] = ret['retcode']
except NameError:
# Ignore the context error during grain generation
pass
# Log the output
if output_loglevel is not None:
if not ignore_retcode and ret['retcode'] != 0:
if output_loglevel < LOG_LEVELS['error']:
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if ret['stdout']:
log.log(output_loglevel, 'stdout: %s', log_callback(ret['stdout']))
if ret['stderr']:
log.log(output_loglevel, 'stderr: %s', log_callback(ret['stderr']))
if ret['retcode']:
log.log(output_loglevel, 'retcode: %s', ret['retcode'])
return ret
def _run_quiet(cmd,
cwd=None,
stdin=None,
output_encoding=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)['stdout']
def _run_all_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
output_encoding=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup.
Returns a dict of return data.
output_loglevel argument is ignored. This is here for when we alias
cmd.run_all directly to _run_all_quiet in certain chicken-and-egg
situations where modules need to work both before and after
the __salt__ dictionary is populated (cf dracr.py)
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)
def run(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
encoded_cmd=False,
raise_err=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
Execute the passed command and return the output as a string
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run 'echo '\''h=\"baz\"'\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If ``False``, let python handle the positional
arguments. Set to ``True`` to use shell features, such as pipes or
redirection.
:param bool bg: If ``True``, run command in background and do not await or
deliver it's results
.. versionadded:: 2016.3.0
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
:param bool raise_err: If ``True`` and the command has a nonzero exit code,
a CommandExecutionError exception will be raised.
.. warning::
This function does not process commands through a shell
unless the python_shell flag is set to True. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or
have the python_shell=True flag set here.
The use of python_shell=True means that the shell will accept _any_ input
including potentially malicious commands such as 'good_command;rm -rf /'.
Be absolutely certain that you have sanitized your input prior to using
python_shell=True
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run cmd='sed -e s/=/:/g'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
log_callback = _check_cb(log_callback)
lvl = _check_loglevel(output_loglevel)
if lvl is not None:
if not ignore_retcode and ret['retcode'] != 0:
if lvl < LOG_LEVELS['error']:
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if raise_err:
raise CommandExecutionError(
log_callback(ret['stdout'] if not hide_output else '')
)
log.log(lvl, 'output: %s', log_callback(ret['stdout']))
return ret['stdout'] if not hide_output else ''
def shell(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return the output as a string.
.. versionadded:: 2015.5.0
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.shell 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param int shell: Shell to execute under. Defaults to the system default
shell.
:param bool bg: If True, run command in background and do not await or
deliver its results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.shell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
.. warning::
This passes the cmd argument directly to the shell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.shell "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.shell template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.shell "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.shell "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.shell cmd='sed -e s/=/:/g'
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
return run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
def run_stdout(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command, and only return the standard out
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stdout 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stdout template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stdout "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stdout'] if not hide_output else ''
def run_stderr(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command and only return the standard error
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stderr 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stderr 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stderr "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stderr template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stderr "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stderr'] if not hide_output else ''
def run_all(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
redirect_stderr=False,
password=None,
encoded_cmd=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return a dict of return data
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_all 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
.. versionadded:: 2018.3.0
:param bool redirect_stderr: If set to ``True``, then stderr will be
redirected to stdout. This is helpful for cases where obtaining both
the retcode and output is desired, but it is not desired to have the
output separated into both stdout and stderr.
.. versionadded:: 2015.8.2
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param bool bg: If ``True``, run command in background and do not await or
deliver its results
.. versionadded:: 2016.3.6
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_all "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_all template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_all "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=stderr,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def retcode(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a shell command and return the command's return code.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.retcode 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.retcode 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:rtype: int
:rtype: None
:returns: Return Code as an int or None if there was an exception.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.retcode "file /bin/bash"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.retcode template=jinja "file {{grains.pythonpath[0]}}/python"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.retcode "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['retcode']
def _retcode_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Helper for running commands quietly for minion startup. Returns same as
the retcode() function.
'''
return retcode(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stderr,
success_stderr=success_stderr,
**kwargs)
def script(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
saltenv='base',
use_vt=False,
bg=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
.. code-block:: bash
salt myminion cmd.script salt://foo.sh "arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param bool bg: If True, run script in background and do not await or
deliver it's results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh
salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
def _cleanup_tempfile(path):
try:
__salt__['file.remove'](path)
except (SaltInvocationError, CommandExecutionError) as exc:
log.error(
'cmd.script: Unable to clean tempfile \'%s\': %s',
path, exc, exc_info_on_loglevel=logging.DEBUG
)
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
win_cwd = False
if salt.utils.platform.is_windows() and runas and cwd is None:
# Create a temp working directory
cwd = tempfile.mkdtemp(dir=__opts__['cachedir'])
win_cwd = True
salt.utils.win_dacl.set_permissions(obj_name=cwd,
principal=runas,
permissions='full_control')
path = salt.utils.files.mkstemp(dir=cwd, suffix=os.path.splitext(source)[1])
if template:
if 'pillarenv' in kwargs or 'pillar' in kwargs:
pillarenv = kwargs.get('pillarenv', __opts__.get('pillarenv'))
kwargs['pillar'] = _gather_pillar(pillarenv, kwargs.get('pillar'))
fn_ = __salt__['cp.get_template'](source,
path,
template,
saltenv,
**kwargs)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
else:
fn_ = __salt__['cp.cache_file'](source, saltenv)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
shutil.copyfile(fn_, path)
if not salt.utils.platform.is_windows():
os.chmod(path, 320)
os.chown(path, __salt__['file.user_to_uid'](runas), -1)
if salt.utils.platform.is_windows() and shell.lower() != 'powershell':
cmd_path = _cmd_quote(path, escape=False)
else:
cmd_path = _cmd_quote(path)
ret = _run(cmd_path + ' ' + six.text_type(args) if args else cmd_path,
cwd=cwd,
stdin=stdin,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def script_retcode(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template='jinja',
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
output_encoding=None,
output_loglevel='debug',
log_callback=None,
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
The script can also be formatted as a template, the default is jinja.
Only evaluate the script return code and do not block for terminal output
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
"arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script_retcode 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh
salt '*' cmd.script_retcode salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script_retcode salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
return script(source=source,
args=args,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)['retcode']
def which(cmd):
'''
Returns the path of an executable available on the minion, None otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.which cat
'''
return salt.utils.path.which(cmd)
def which_bin(cmds):
'''
Returns the first command found in a list of commands
CLI Example:
.. code-block:: bash
salt '*' cmd.which_bin '[pip2, pip, pip-python]'
'''
return salt.utils.path.which_bin(cmds)
def has_exec(cmd):
'''
Returns true if the executable is available on the minion, false otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.has_exec cat
'''
return which(cmd) is not None
def exec_code(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. The stdout will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code ruby 'puts "cheese"'
salt '*' cmd.exec_code ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
return exec_code_all(lang, code, cwd, args, **kwargs)['stdout']
def exec_code_all(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid)
will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code_all ruby 'puts "cheese"'
salt '*' cmd.exec_code_all ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
powershell = lang.lower().startswith("powershell")
if powershell:
codefile = salt.utils.files.mkstemp(suffix=".ps1")
else:
codefile = salt.utils.files.mkstemp()
with salt.utils.files.fopen(codefile, 'w+t', binary=False) as fp_:
fp_.write(salt.utils.stringutils.to_str(code))
if powershell:
cmd = [lang, "-File", codefile]
else:
cmd = [lang, codefile]
if isinstance(args, six.string_types):
cmd.append(args)
elif isinstance(args, list):
cmd += args
ret = run_all(cmd, cwd=cwd, python_shell=False, **kwargs)
os.remove(codefile)
return ret
def tty(device, echo=''):
'''
Echo a string to a specific tty
CLI Example:
.. code-block:: bash
salt '*' cmd.tty tty0 'This is a test'
salt '*' cmd.tty pts3 'This is a test'
'''
if device.startswith('tty'):
teletype = '/dev/{0}'.format(device)
elif device.startswith('pts'):
teletype = '/dev/{0}'.format(device.replace('pts', 'pts/'))
else:
return {'Error': 'The specified device is not a valid TTY'}
try:
with salt.utils.files.fopen(teletype, 'wb') as tty_device:
tty_device.write(salt.utils.stringutils.to_bytes(echo))
return {
'Success': 'Message was successfully echoed to {0}'.format(teletype)
}
except IOError:
return {
'Error': 'Echoing to {0} returned error'.format(teletype)
}
def run_chroot(root,
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=True,
binds=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='quiet',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
.. versionadded:: 2014.7.0
This function runs :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` wrapped
within a chroot, with dev and proc mounted in the chroot
:param str root: Path to the root of the jail to use.
:param str stdin: A string of standard input can be specified for
the command to be run using the ``stdin`` parameter. This can
be useful in cases where sensitive information must be read
from standard input.:
:param str runas: User to run script as.
:param str group: Group to run script as.
:param str shell: Shell to execute under. Defaults to the system
default shell.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:parar str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param list binds: List of directories that will be exported inside
the chroot with the bind option.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_chroot 'some command' env='{"FOO": "bar"}'
:param dict clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output
before it is returned.
:param str umask: The umask (in octal) to use when running the
command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout:
A timeout in seconds for the executed process to return.
:param bool use_vt:
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs. This is experimental.
:param success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' cmd.run_chroot /var/lib/lxc/container_name/rootfs 'sh /tmp/bootstrap.sh'
'''
__salt__['mount.mount'](
os.path.join(root, 'dev'),
'devtmpfs',
fstype='devtmpfs')
__salt__['mount.mount'](
os.path.join(root, 'proc'),
'proc',
fstype='proc')
__salt__['mount.mount'](
os.path.join(root, 'sys'),
'sysfs',
fstype='sysfs')
binds = binds if binds else []
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.mount'](
bind_exported_to,
bind_exported,
opts='default,bind')
# Execute chroot routine
sh_ = '/bin/sh'
if os.path.isfile(os.path.join(root, 'bin/bash')):
sh_ = '/bin/bash'
if isinstance(cmd, (list, tuple)):
cmd = ' '.join([six.text_type(i) for i in cmd])
cmd = 'chroot {0} {1} -c {2}'.format(root, sh_, _cmd_quote(cmd))
run_func = __context__.pop('cmd.run_chroot.func', run_all)
ret = run_func(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
pillarenv=kwargs.get('pillarenv'),
pillar=kwargs.get('pillar'),
use_vt=use_vt,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
bg=bg)
# Kill processes running in the chroot
for i in range(6):
pids = _chroot_pids(root)
if not pids:
break
for pid in pids:
# use sig 15 (TERM) for first 3 attempts, then 9 (KILL)
sig = 15 if i < 3 else 9
os.kill(pid, sig)
if _chroot_pids(root):
log.error('Processes running in chroot could not be killed, '
'filesystem will remain mounted')
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.umount'](bind_exported_to)
__salt__['mount.umount'](os.path.join(root, 'sys'))
__salt__['mount.umount'](os.path.join(root, 'proc'))
__salt__['mount.umount'](os.path.join(root, 'dev'))
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def _is_valid_shell(shell):
'''
Attempts to search for valid shells on a system and
see if a given shell is in the list
'''
if salt.utils.platform.is_windows():
return True # Don't even try this for Windows
shells = '/etc/shells'
available_shells = []
if os.path.exists(shells):
try:
with salt.utils.files.fopen(shells, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
if line.startswith('#'):
continue
else:
available_shells.append(line)
except OSError:
return True
else:
# No known method of determining available shells
return None
if shell in available_shells:
return True
else:
return False
def shells():
'''
Lists the valid shells on this system via the /etc/shells file
.. versionadded:: 2015.5.0
CLI Example::
salt '*' cmd.shells
'''
shells_fn = '/etc/shells'
ret = []
if os.path.exists(shells_fn):
try:
with salt.utils.files.fopen(shells_fn, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
line = line.strip()
if line.startswith('#'):
continue
elif not line:
continue
else:
ret.append(line)
except OSError:
log.error("File '%s' was not found", shells_fn)
return ret
def shell_info(shell, list_modules=False):
'''
.. versionadded:: 2016.11.0
Provides information about a shell or script languages which often use
``#!``. The values returned are dependent on the shell or scripting
languages all return the ``installed``, ``path``, ``version``,
``version_raw``
Args:
shell (str): Name of the shell. Support shells/script languages include
bash, cmd, perl, php, powershell, python, ruby and zsh
list_modules (bool): True to list modules available to the shell.
Currently only lists powershell modules.
Returns:
dict: A dictionary of information about the shell
.. code-block:: python
{'version': '<2 or 3 numeric components dot-separated>',
'version_raw': '<full version string>',
'path': '<full path to binary>',
'installed': <True, False or None>,
'<attribute>': '<attribute value>'}
.. note::
- ``installed`` is always returned, if ``None`` or ``False`` also
returns error and may also return ``stdout`` for diagnostics.
- ``version`` is for use in determine if a shell/script language has a
particular feature set, not for package management.
- The shell must be within the executable search path.
CLI Example:
.. code-block:: bash
salt '*' cmd.shell_info bash
salt '*' cmd.shell_info powershell
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
regex_shells = {
'bash': [r'version (\d\S*)', 'bash', '--version'],
'bash-test-error': [r'versioZ ([-\w.]+)', 'bash', '--version'], # used to test an error result
'bash-test-env': [r'(HOME=.*)', 'bash', '-c', 'declare'], # used to test an error result
'zsh': [r'^zsh (\d\S*)', 'zsh', '--version'],
'tcsh': [r'^tcsh (\d\S*)', 'tcsh', '--version'],
'cmd': [r'Version ([\d.]+)', 'cmd.exe', '/C', 'ver'],
'powershell': [r'PSVersion\s+(\d\S*)', 'powershell', '-NonInteractive', '$PSVersionTable'],
'perl': [r'^(\d\S*)', 'perl', '-e', 'printf "%vd\n", $^V;'],
'python': [r'^Python (\d\S*)', 'python', '-V'],
'ruby': [r'^ruby (\d\S*)', 'ruby', '-v'],
'php': [r'^PHP (\d\S*)', 'php', '-v']
}
# Ensure ret['installed'] always as a value of True, False or None (not sure)
ret = {'installed': False}
if salt.utils.platform.is_windows() and shell == 'powershell':
pw_keys = salt.utils.win_reg.list_keys(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell')
pw_keys.sort(key=int)
if not pw_keys:
return {
'error': 'Unable to locate \'powershell\' Reason: Cannot be '
'found in registry.',
'installed': False,
}
for reg_ver in pw_keys:
install_data = salt.utils.win_reg.read_value(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}'.format(reg_ver),
vname='Install')
if install_data.get('vtype') == 'REG_DWORD' and \
install_data.get('vdata') == 1:
details = salt.utils.win_reg.list_values(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}\\'
'PowerShellEngine'.format(reg_ver))
# reset data, want the newest version details only as powershell
# is backwards compatible
ret = {}
# if all goes well this will become True
ret['installed'] = None
ret['path'] = which('powershell.exe')
for attribute in details:
if attribute['vname'].lower() == '(default)':
continue
elif attribute['vname'].lower() == 'powershellversion':
ret['psversion'] = attribute['vdata']
ret['version_raw'] = attribute['vdata']
elif attribute['vname'].lower() == 'runtimeversion':
ret['crlversion'] = attribute['vdata']
if ret['crlversion'][0].lower() == 'v':
ret['crlversion'] = ret['crlversion'][1::]
elif attribute['vname'].lower() == 'pscompatibleversion':
# reg attribute does not end in s, the powershell
# attribute does
ret['pscompatibleversions'] = \
attribute['vdata'].replace(' ', '').split(',')
else:
# keys are lower case as python is case sensitive the
# registry is not
ret[attribute['vname'].lower()] = attribute['vdata']
else:
if shell not in regex_shells:
return {
'error': 'Salt does not know how to get the version number for '
'{0}'.format(shell),
'installed': None
}
shell_data = regex_shells[shell]
pattern = shell_data.pop(0)
# We need to make sure HOME set, so shells work correctly
# salt-call will general have home set, the salt-minion service may not
# We need to assume ports of unix shells to windows will look after
# themselves in setting HOME as they do it in many different ways
newenv = os.environ
if ('HOME' not in newenv) and (not salt.utils.platform.is_windows()):
newenv['HOME'] = os.path.expanduser('~')
log.debug('HOME environment set to %s', newenv['HOME'])
try:
proc = salt.utils.timed_subprocess.TimedProc(
shell_data,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=10,
env=newenv
)
except (OSError, IOError) as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: {1}'.format(' '.join(shell_data), exc),
'installed': False,
}
try:
proc.run()
except TimedProcTimeoutError as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: Timed out.'.format(' '.join(shell_data)),
'installed': False,
}
ret['path'] = which(shell_data[0])
pattern_result = re.search(pattern, proc.stdout, flags=re.IGNORECASE)
# only set version if we find it, so code later on can deal with it
if pattern_result:
ret['version_raw'] = pattern_result.group(1)
if 'version_raw' in ret:
version_results = re.match(r'(\d[\d.]*)', ret['version_raw'])
if version_results:
ret['installed'] = True
ver_list = version_results.group(1).split('.')[:3]
if len(ver_list) == 1:
ver_list.append('0')
ret['version'] = '.'.join(ver_list[:3])
else:
ret['installed'] = None # Have an unexpected result
# Get a list of the PowerShell modules which are potentially available
# to be imported
if shell == 'powershell' and ret['installed'] and list_modules:
ret['modules'] = salt.utils.powershell.get_modules()
if 'version' not in ret:
ret['error'] = 'The version regex pattern for shell {0}, could not ' \
'find the version string'.format(shell)
ret['stdout'] = proc.stdout # include stdout so they can see the issue
log.error(ret['error'])
return ret
def powershell(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return the output as a dictionary.
Other ``cmd.*`` functions (besides ``cmd.powershell_all``)
return the raw text output of the command. This
function appends ``| ConvertTo-JSON`` to the command and then parses the
JSON into a Python dictionary. If you want the raw textual result of your
PowerShell command you should use ``cmd.run`` with the ``shell=powershell``
option.
For example:
.. code-block:: bash
salt '*' cmd.run '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2016.3.0
.. warning::
This passes the cmd argument directly to PowerShell
without any further processing! Be absolutely sure that you
have properly sanitized the command passed to this function
and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in cases
where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
.. versionadded:: 2016.3.4
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:returns:
:dict: A dictionary of data returned by the powershell command.
CLI Example:
.. code-block:: powershell
salt '*' cmd.powershell "$PSVersionTable.CLRVersion"
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
# ConvertTo-JSON is only available on PowerShell 3.0 and later
psversion = shell_info('powershell')['psversion']
if salt.utils.versions.version_cmp(psversion, '2.0') == 1:
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Put the whole command inside a try / catch block
# Some errors in PowerShell are not "Terminating Errors" and will not be
# caught in a try/catch block. For example, the `Get-WmiObject` command will
# often return a "Non Terminating Error". To fix this, make sure
# `-ErrorAction Stop` is set in the powershell command
cmd = 'try {' + cmd + '} catch { "{}" }'
# Retrieve the response, while overriding shell with 'powershell'
response = run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
try:
return salt.utils.json.loads(response)
except Exception:
log.error("Error converting PowerShell JSON return", exc_info=True)
return {}
def powershell_all(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
quiet=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
force_list=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return a dictionary with a result
field representing the output of the command, as well as other fields
showing us what the PowerShell invocation wrote to ``stderr``, the process
id, and the exit code of the invocation.
This function appends ``| ConvertTo-JSON`` to the command before actually
invoking powershell.
An unquoted empty string is not valid JSON, but it's very normal for the
Powershell output to be exactly that. Therefore, we do not attempt to parse
empty Powershell output (which would result in an exception). Instead we
treat this as a special case and one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field of the return dictionary will be an empty list.
- If the value of the ``force_list`` parameter is ``False``, then the
return dictionary **will not have a result key added to it**. We aren't
setting ``result`` to ``None`` in this case, because ``None`` is the
Python representation of "null" in JSON. (We likewise can't use ``False``
for the equivalent reason.)
If Powershell's output is not an empty string and Python cannot parse its
content, then a ``CommandExecutionError`` exception will be raised.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is other than ``list``
then one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field will be a singleton list with the Python object as its
sole member.
- If the value of the ``force_list`` parameter is ``False``, then the value
of ``result`` will be the unmodified Python object.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is ``list``, then the
value of ``result`` will be the unmodified Python object. The
``force_list`` parameter has no effect in this case.
.. note::
An example of why the ``force_list`` parameter is useful is as
follows: The Powershell command ``dir x | Convert-ToJson`` results in
- no output when x is an empty directory.
- a dictionary object when x contains just one item.
- a list of dictionary objects when x contains multiple items.
By setting ``force_list`` to ``True`` we will always end up with a
list of dictionary items, representing files, no matter how many files
x contains. Conversely, if ``force_list`` is ``False``, we will end
up with no ``result`` key in our return dictionary when x is an empty
directory, and a dictionary object when x contains just one file.
If you want a similar function but with a raw textual result instead of a
Python dictionary, you should use ``cmd.run_all`` in combination with
``shell=powershell``.
The remaining fields in the return dictionary are described in more detail
in the ``Returns`` section.
Example:
.. code-block:: bash
salt '*' cmd.run_all '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run_all 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2018.3.0
.. warning::
This passes the cmd argument directly to PowerShell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param bool force_list: The purpose of this parameter is described in the
preamble of this function's documentation. Default value is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:return: A dictionary with the following entries:
result
For a complete description of this field, please refer to this
function's preamble. **This key will not be added to the dictionary
when force_list is False and Powershell's output is the empty
string.**
stderr
What the PowerShell invocation wrote to ``stderr``.
pid
The process id of the PowerShell invocation
retcode
This is the exit code of the invocation of PowerShell.
If the final execution status (in PowerShell) of our command
(with ``| ConvertTo-JSON`` appended) is ``False`` this should be non-0.
Likewise if PowerShell exited with ``$LASTEXITCODE`` set to some
non-0 value, then ``retcode`` will end up with this value.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "$PSVersionTable.CLRVersion"
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "dir mydirectory" force_list=True
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Retrieve the response, while overriding shell with 'powershell'
response = run_all(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
quiet=quiet,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
stdoutput = response['stdout']
# if stdoutput is the empty string and force_list is True we return an empty list
# Otherwise we return response with no result key
if not stdoutput:
response.pop('stdout')
if force_list:
response['result'] = []
return response
# If we fail to parse stdoutput we will raise an exception
try:
result = salt.utils.json.loads(stdoutput)
except Exception:
err_msg = "cmd.powershell_all " + \
"cannot parse the Powershell output."
response["cmd"] = cmd
raise CommandExecutionError(
message=err_msg,
info=response
)
response.pop("stdout")
if type(result) is not list:
if force_list:
response['result'] = [result]
else:
response['result'] = result
else:
# result type is list so the force_list param has no effect
response['result'] = result
return response
def run_bg(cmd,
cwd=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
timeout=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
.. versionadded: 2016.3.0
Execute the passed command in the background and return it's PID
.. note::
If the init system is systemd and the backgrounded task should run even
if the salt-minion process is restarted, prepend ``systemd-run
--scope`` to the command. This will reparent the process in its own
scope separate from salt-minion, and will not be affected by restarting
the minion service.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Shell to execute under. Defaults to the system default
shell.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_bg 'echo '\''h=\"baz\"'\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_bg 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param int timeout: A timeout in seconds for the executed process to return.
.. warning::
This function does not process commands through a shell unless the
``python_shell`` argument is set to ``True``. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or have the
python_shell=True flag set here.
The use of ``python_shell=True`` means that the shell will accept _any_
input including potentially malicious commands such as 'good_command;rm
-rf /'. Be absolutely certain that you have sanitized your input prior
to using ``python_shell=True``.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_bg "fstrim-all"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_bg template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run_bg "Get-ChildItem C:\\ " shell='powershell'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run_bg cmd='ls -lR / | sed -e s/=/:/g > /tmp/dontwait'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
res = _run(cmd,
stdin=None,
stderr=None,
stdout=None,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
use_vt=None,
bg=True,
with_communicate=False,
rstrip=False,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
umask=umask,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs
)
return {
'pid': res['pid']
}
|
saltstack/salt
|
salt/modules/cmdmod.py
|
_check_avail
|
python
|
def _check_avail(cmd):
'''
Check to see if the given command can be run
'''
if isinstance(cmd, list):
cmd = ' '.join([six.text_type(x) if not isinstance(x, six.string_types) else x
for x in cmd])
bret = True
wret = False
if __salt__['config.get']('cmd_blacklist_glob'):
blist = __salt__['config.get']('cmd_blacklist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# BAD! you are blacklisted
bret = False
if __salt__['config.get']('cmd_whitelist_glob', []):
blist = __salt__['config.get']('cmd_whitelist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# GOOD! You are whitelisted
wret = True
break
else:
# If no whitelist set then alls good!
wret = True
return bret and wret
|
Check to see if the given command can be run
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cmdmod.py#L222-L247
| null |
# -*- coding: utf-8 -*-
'''
A module for shelling out.
Keep in mind that this module is insecure, in that it can give whomever has
access to the master root execution access to all salt minions.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import functools
import glob
import logging
import os
import shutil
import subprocess
import sys
import time
import traceback
import fnmatch
import base64
import re
import tempfile
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.powershell
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.timed_subprocess
import salt.utils.user
import salt.utils.versions
import salt.utils.vt
import salt.utils.win_dacl
import salt.utils.win_reg
import salt.grains.extra
from salt.ext import six
from salt.exceptions import CommandExecutionError, TimedProcTimeoutError, \
SaltInvocationError
from salt.log import LOG_LEVELS
from salt.ext.six.moves import range, zip, map
# Only available on POSIX systems, nonfatal on windows
try:
import pwd
import grp
except ImportError:
pass
if salt.utils.platform.is_windows():
from salt.utils.win_runas import runas as win_runas
from salt.utils.win_functions import escape_argument as _cmd_quote
HAS_WIN_RUNAS = True
else:
from salt.ext.six.moves import shlex_quote as _cmd_quote
HAS_WIN_RUNAS = False
__proxyenabled__ = ['*']
# Define the module's virtual name
__virtualname__ = 'cmd'
# Set up logging
log = logging.getLogger(__name__)
DEFAULT_SHELL = salt.grains.extra.shell()['shell']
# Overwriting the cmd python module makes debugging modules with pdb a bit
# harder so lets do it this way instead.
def __virtual__():
return __virtualname__
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns
the value passed.
'''
if cb_ is not None:
if hasattr(cb_, '__call__'):
return cb_
else:
log.error('log_callback is not callable, ignoring')
return lambda x: x
def _python_shell_default(python_shell, __pub_jid):
'''
Set python_shell default based on remote execution and __opts__['cmd_safe']
'''
try:
# Default to python_shell=True when run directly from remote execution
# system. Cross-module calls won't have a jid.
if __pub_jid and python_shell is None:
return True
elif __opts__.get('cmd_safe', True) is False and python_shell is None:
# Override-switch for python_shell
return True
except NameError:
pass
return python_shell
def _chroot_pids(chroot):
pids = []
for root in glob.glob('/proc/[0-9]*/root'):
try:
link = os.path.realpath(root)
if link.startswith(chroot):
pids.append(int(os.path.basename(
os.path.dirname(root)
)))
except OSError:
pass
return pids
def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):
'''
If template is a valid template engine, process the cmd and cwd through
that engine.
'''
if not template:
return (cmd, cwd)
# render the path as a template using path_template_engine as the engine
if template not in salt.utils.templates.TEMPLATE_REGISTRY:
raise CommandExecutionError(
'Attempted to render file paths with unavailable engine '
'{0}'.format(template)
)
kwargs = {}
kwargs['salt'] = __salt__
if pillarenv is not None or pillar_override is not None:
pillarenv = pillarenv or __opts__['pillarenv']
kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override)
else:
kwargs['pillar'] = __pillar__
kwargs['grains'] = __grains__
kwargs['opts'] = __opts__
kwargs['saltenv'] = saltenv
def _render(contents):
# write out path to temp file
tmp_path_fn = salt.utils.files.mkstemp()
with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(contents))
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
tmp_path_fn,
to_str=True,
**kwargs
)
salt.utils.files.safe_rm(tmp_path_fn)
if not data['result']:
# Failed to render the template
raise CommandExecutionError(
'Failed to execute cmd with error: {0}'.format(
data['data']
)
)
else:
return data['data']
cmd = _render(cmd)
cwd = _render(cwd)
return (cmd, cwd)
def _check_loglevel(level='info'):
'''
Retrieve the level code for use in logging.Logger.log().
'''
try:
level = level.lower()
if level == 'quiet':
return None
else:
return LOG_LEVELS[level]
except (AttributeError, KeyError):
log.error(
'Invalid output_loglevel \'%s\'. Valid levels are: %s. Falling '
'back to \'info\'.',
level, ', '.join(sorted(LOG_LEVELS, reverse=True))
)
return LOG_LEVELS['info']
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
return env
def _gather_pillar(pillarenv, pillar_override):
'''
Whenever a state run starts, gather the pillar data fresh
'''
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
pillar_override=pillar_override,
pillarenv=pillarenv
)
ret = pillar.compile_pillar()
if pillar_override and isinstance(pillar_override, dict):
ret.update(pillar_override)
return ret
def _run(cmd,
cwd=None,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
prepend_path=None,
rstrip=True,
template=None,
umask=None,
timeout=None,
with_communicate=True,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
pillarenv=None,
pillar_override=None,
use_vt=False,
password=None,
bg=False,
encoded_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Do the DRY thing and only call subprocess.Popen() once
'''
if 'pillar' in kwargs and not pillar_override:
pillar_override = kwargs['pillar']
if output_loglevel != 'quiet' and _is_valid_shell(shell) is False:
log.warning(
'Attempt to run a shell command with what may be an invalid shell! '
'Check to ensure that the shell <%s> is valid for this user.',
shell
)
output_loglevel = _check_loglevel(output_loglevel)
log_callback = _check_cb(log_callback)
use_sudo = False
if runas is None and '__context__' in globals():
runas = __context__.get('runas')
if password is None and '__context__' in globals():
password = __context__.get('runas_password')
# Set the default working directory to the home directory of the user
# salt-minion is running as. Defaults to home directory of user under which
# the minion is running.
if not cwd:
cwd = os.path.expanduser('~{0}'.format('' if not runas else runas))
# make sure we can access the cwd
# when run from sudo or another environment where the euid is
# changed ~ will expand to the home of the original uid and
# the euid might not have access to it. See issue #1844
if not os.access(cwd, os.R_OK):
cwd = '/'
if salt.utils.platform.is_windows():
cwd = os.path.abspath(os.sep)
else:
# Handle edge cases where numeric/other input is entered, and would be
# yaml-ified into non-string types
cwd = six.text_type(cwd)
if bg:
ignore_retcode = True
use_vt = False
if not salt.utils.platform.is_windows():
if not os.path.isfile(shell) or not os.access(shell, os.X_OK):
msg = 'The shell {0} is not available'.format(shell)
raise CommandExecutionError(msg)
if salt.utils.platform.is_windows() and use_vt: # Memozation so not much overhead
raise CommandExecutionError('VT not available on windows')
if shell.lower().strip() == 'powershell':
# Strip whitespace
if isinstance(cmd, six.string_types):
cmd = cmd.strip()
# If we were called by script(), then fakeout the Windows
# shell to run a Powershell script.
# Else just run a Powershell command.
stack = traceback.extract_stack(limit=2)
# extract_stack() returns a list of tuples.
# The last item in the list [-1] is the current method.
# The third item[2] in each tuple is the name of that method.
if stack[-2][2] == 'script':
cmd = 'Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -File ' + cmd
elif encoded_cmd:
cmd = 'Powershell -NonInteractive -EncodedCommand {0}'.format(cmd)
else:
cmd = 'Powershell -NonInteractive -NoProfile "{0}"'.format(cmd.replace('"', '\\"'))
# munge the cmd and cwd through the template
(cmd, cwd) = _render_cmd(cmd, cwd, template, saltenv, pillarenv, pillar_override)
ret = {}
# If the pub jid is here then this is a remote ex or salt call command and needs to be
# checked if blacklisted
if '__pub_jid' in kwargs:
if not _check_avail(cmd):
raise CommandExecutionError(
'The shell command "{0}" is not permitted'.format(cmd)
)
env = _parse_env(env)
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, six.string_types) else x for x in cmd]
elif isinstance(cmd, six.string_types):
return cmd.strip()
else:
return cmd
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' parameter.
msg = (
'Executing command {0}{1}{0} {2}{3}in directory \'{4}\'{5}'.format(
'\'' if not isinstance(cmd, list) else '',
_get_stripped(cmd),
'as user \'{0}\' '.format(runas) if runas else '',
'in group \'{0}\' '.format(group) if group else '',
cwd,
'. Executing command in the background, no output will be '
'logged.' if bg else ''
)
)
log.info(log_callback(msg))
if runas and salt.utils.platform.is_windows():
if not HAS_WIN_RUNAS:
msg = 'missing salt/utils/win_runas.py'
raise CommandExecutionError(msg)
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(cmd)
return win_runas(cmd, runas, password, cwd)
if runas and salt.utils.platform.is_darwin():
# we need to insert the user simulation into the command itself and not
# just run it from the environment on macOS as that
# method doesn't work properly when run as root for certain commands.
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(map(_cmd_quote, cmd))
cmd = 'su -l {0} -c "cd {1}; {2}"'.format(runas, cwd, cmd)
# set runas to None, because if you try to run `su -l` as well as
# simulate the environment macOS will prompt for the password of the
# user and will cause salt to hang.
runas = None
if runas:
# Save the original command before munging it
try:
pwd.getpwnam(runas)
except KeyError:
raise CommandExecutionError(
'User \'{0}\' is not available'.format(runas)
)
if group:
if salt.utils.platform.is_windows():
msg = 'group is not currently available on Windows'
raise SaltInvocationError(msg)
if not which_bin(['sudo']):
msg = 'group argument requires sudo but not found'
raise CommandExecutionError(msg)
try:
grp.getgrnam(group)
except KeyError:
raise CommandExecutionError(
'Group \'{0}\' is not available'.format(runas)
)
else:
use_sudo = True
if runas or group:
try:
# Getting the environment for the runas user
# Use markers to thwart any stdout noise
# There must be a better way to do this.
import uuid
marker = '<<<' + str(uuid.uuid4()) + '>>>'
marker_b = marker.encode(__salt_system_encoding__)
py_code = (
'import sys, os, itertools; '
'sys.stdout.write(\"' + marker + '\"); '
'sys.stdout.write(\"\\0\".join(itertools.chain(*os.environ.items()))); '
'sys.stdout.write(\"' + marker + '\");'
)
if use_sudo or __grains__['os'] in ['MacOS', 'Darwin']:
env_cmd = ['sudo']
# runas is optional if use_sudo is set.
if runas:
env_cmd.extend(['-u', runas])
if group:
env_cmd.extend(['-g', group])
if shell != DEFAULT_SHELL:
env_cmd.extend(['-s', '--', shell, '-c'])
else:
env_cmd.extend(['-i', '--'])
env_cmd.extend([sys.executable])
elif __grains__['os'] in ['FreeBSD']:
env_cmd = ('su', '-', runas, '-c',
"{0} -c {1}".format(shell, sys.executable))
elif __grains__['os_family'] in ['Solaris']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
elif __grains__['os_family'] in ['AIX']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
else:
env_cmd = ('su', '-s', shell, '-', runas, '-c', sys.executable)
msg = 'env command: {0}'.format(env_cmd)
log.debug(log_callback(msg))
env_bytes, env_encoded_err = subprocess.Popen(
env_cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
).communicate(salt.utils.stringutils.to_bytes(py_code))
marker_count = env_bytes.count(marker_b)
if marker_count == 0:
# Possibly PAM prevented the login
log.error(
'Environment could not be retrieved for user \'%s\': '
'stderr=%r stdout=%r',
runas, env_encoded_err, env_bytes
)
# Ensure that we get an empty env_runas dict below since we
# were not able to get the environment.
env_bytes = b''
elif marker_count != 2:
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\'',
info={'stderr': repr(env_encoded_err),
'stdout': repr(env_bytes)}
)
else:
# Strip the marker
env_bytes = env_bytes.split(marker_b)[1]
if six.PY2:
import itertools
env_runas = dict(itertools.izip(*[iter(env_bytes.split(b'\0'))]*2))
elif six.PY3:
env_runas = dict(list(zip(*[iter(env_bytes.split(b'\0'))]*2)))
env_runas = dict(
(salt.utils.stringutils.to_str(k),
salt.utils.stringutils.to_str(v))
for k, v in six.iteritems(env_runas)
)
env_runas.update(env)
# Fix platforms like Solaris that don't set a USER env var in the
# user's default environment as obtained above.
if env_runas.get('USER') != runas:
env_runas['USER'] = runas
# Fix some corner cases where shelling out to get the user's
# environment returns the wrong home directory.
runas_home = os.path.expanduser('~{0}'.format(runas))
if env_runas.get('HOME') != runas_home:
env_runas['HOME'] = runas_home
env = env_runas
except ValueError as exc:
log.exception('Error raised retrieving environment for user %s', runas)
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\': {1}'.format(
runas, exc
)
)
if reset_system_locale is True:
if not salt.utils.platform.is_windows():
# Default to C!
# Salt only knows how to parse English words
# Don't override if the user has passed LC_ALL
env.setdefault('LC_CTYPE', 'C')
env.setdefault('LC_NUMERIC', 'C')
env.setdefault('LC_TIME', 'C')
env.setdefault('LC_COLLATE', 'C')
env.setdefault('LC_MONETARY', 'C')
env.setdefault('LC_MESSAGES', 'C')
env.setdefault('LC_PAPER', 'C')
env.setdefault('LC_NAME', 'C')
env.setdefault('LC_ADDRESS', 'C')
env.setdefault('LC_TELEPHONE', 'C')
env.setdefault('LC_MEASUREMENT', 'C')
env.setdefault('LC_IDENTIFICATION', 'C')
env.setdefault('LANGUAGE', 'C')
else:
# On Windows set the codepage to US English.
if python_shell:
cmd = 'chcp 437 > nul & ' + cmd
if clean_env:
run_env = env
else:
run_env = os.environ.copy()
run_env.update(env)
if prepend_path:
run_env['PATH'] = ':'.join((prepend_path, run_env['PATH']))
if python_shell is None:
python_shell = False
new_kwargs = {'cwd': cwd,
'shell': python_shell,
'env': run_env if six.PY3 else salt.utils.data.encode(run_env),
'stdin': six.text_type(stdin) if stdin is not None else stdin,
'stdout': stdout,
'stderr': stderr,
'with_communicate': with_communicate,
'timeout': timeout,
'bg': bg,
}
if 'stdin_raw_newlines' in kwargs:
new_kwargs['stdin_raw_newlines'] = kwargs['stdin_raw_newlines']
if umask is not None:
_umask = six.text_type(umask).lstrip('0')
if _umask == '':
msg = 'Zero umask is not allowed.'
raise CommandExecutionError(msg)
try:
_umask = int(_umask, 8)
except ValueError:
raise CommandExecutionError("Invalid umask: '{0}'".format(umask))
else:
_umask = None
if runas or group or umask:
new_kwargs['preexec_fn'] = functools.partial(
salt.utils.user.chugid_and_umask,
runas,
_umask,
group)
if not salt.utils.platform.is_windows():
# close_fds is not supported on Windows platforms if you redirect
# stdin/stdout/stderr
if new_kwargs['shell'] is True:
new_kwargs['executable'] = shell
new_kwargs['close_fds'] = True
if not os.path.isabs(cwd) or not os.path.isdir(cwd):
raise CommandExecutionError(
'Specified cwd \'{0}\' either not absolute or does not exist'
.format(cwd)
)
if python_shell is not True \
and not salt.utils.platform.is_windows() \
and not isinstance(cmd, list):
cmd = salt.utils.args.shlex_split(cmd)
if success_retcodes is None:
success_retcodes = [0]
else:
try:
success_retcodes = [int(i) for i in
salt.utils.args.split_input(
success_retcodes
)]
except ValueError:
raise SaltInvocationError(
'success_retcodes must be a list of integers'
)
if success_stdout is None:
success_stdout = []
else:
try:
success_stdout = [i for i in
salt.utils.args.split_input(
success_stdout
)]
except ValueError:
raise SaltInvocationError(
'success_stdout must be a list of integers'
)
if success_stderr is None:
success_stderr = []
else:
try:
success_stderr = [i for i in
salt.utils.args.split_input(
success_stderr
)]
except ValueError:
raise SaltInvocationError(
'success_stderr must be a list of integers'
)
if not use_vt:
# This is where the magic happens
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **new_kwargs)
except (OSError, IOError) as exc:
msg = (
'Unable to run command \'{0}\' with the context \'{1}\', '
'reason: {2}'.format(
cmd if output_loglevel is not None else 'REDACTED',
new_kwargs,
exc
)
)
raise CommandExecutionError(msg)
try:
proc.run()
except TimedProcTimeoutError as exc:
ret['stdout'] = six.text_type(exc)
ret['stderr'] = ''
ret['retcode'] = None
ret['pid'] = proc.process.pid
# ok return code for timeouts?
ret['retcode'] = 1
return ret
if output_loglevel != 'quiet' and output_encoding is not None:
log.debug('Decoding output from command %s using %s encoding',
cmd, output_encoding)
try:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding)
except TypeError:
# stdout is None
out = ''
except UnicodeDecodeError:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', cmd
)
try:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding)
except TypeError:
# stderr is None
err = ''
except UnicodeDecodeError:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', cmd
)
if rstrip:
if out is not None:
out = out.rstrip()
if err is not None:
err = err.rstrip()
ret['pid'] = proc.process.pid
ret['retcode'] = proc.process.returncode
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
ret['stdout'] = out
ret['stderr'] = err
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
else:
formatted_timeout = ''
if timeout:
formatted_timeout = ' (timeout: {0}s)'.format(timeout)
if output_loglevel is not None:
msg = 'Running {0} in VT{1}'.format(cmd, formatted_timeout)
log.debug(log_callback(msg))
stdout, stderr = '', ''
now = time.time()
if timeout:
will_timeout = now + timeout
else:
will_timeout = -1
try:
proc = salt.utils.vt.Terminal(
cmd,
shell=True,
log_stdout=True,
log_stderr=True,
cwd=cwd,
preexec_fn=new_kwargs.get('preexec_fn', None),
env=run_env,
log_stdin_level=output_loglevel,
log_stdout_level=output_loglevel,
log_stderr_level=output_loglevel,
stream_stdout=True,
stream_stderr=True
)
ret['pid'] = proc.pid
while proc.has_unread_data:
try:
try:
time.sleep(0.5)
try:
cstdout, cstderr = proc.recv()
except IOError:
cstdout, cstderr = '', ''
if cstdout:
stdout += cstdout
else:
cstdout = ''
if cstderr:
stderr += cstderr
else:
cstderr = ''
if timeout and (time.time() > will_timeout):
ret['stderr'] = (
'SALT: Timeout after {0}s\n{1}').format(
timeout, stderr)
ret['retcode'] = None
break
except KeyboardInterrupt:
ret['stderr'] = 'SALT: User break\n{0}'.format(stderr)
ret['retcode'] = 1
break
except salt.utils.vt.TerminalException as exc:
log.error('VT: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
ret = {'retcode': 1, 'pid': '2'}
break
# only set stdout on success as we already mangled in other
# cases
ret['stdout'] = stdout
if not proc.isalive():
# Process terminated, i.e., not canceled by the user or by
# the timeout
ret['stderr'] = stderr
ret['retcode'] = proc.exitstatus
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
ret['pid'] = proc.pid
finally:
proc.close(terminate=True, kill=True)
try:
if ignore_retcode:
__context__['retcode'] = 0
else:
__context__['retcode'] = ret['retcode']
except NameError:
# Ignore the context error during grain generation
pass
# Log the output
if output_loglevel is not None:
if not ignore_retcode and ret['retcode'] != 0:
if output_loglevel < LOG_LEVELS['error']:
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if ret['stdout']:
log.log(output_loglevel, 'stdout: %s', log_callback(ret['stdout']))
if ret['stderr']:
log.log(output_loglevel, 'stderr: %s', log_callback(ret['stderr']))
if ret['retcode']:
log.log(output_loglevel, 'retcode: %s', ret['retcode'])
return ret
def _run_quiet(cmd,
cwd=None,
stdin=None,
output_encoding=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)['stdout']
def _run_all_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
output_encoding=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup.
Returns a dict of return data.
output_loglevel argument is ignored. This is here for when we alias
cmd.run_all directly to _run_all_quiet in certain chicken-and-egg
situations where modules need to work both before and after
the __salt__ dictionary is populated (cf dracr.py)
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)
def run(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
encoded_cmd=False,
raise_err=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
Execute the passed command and return the output as a string
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run 'echo '\''h=\"baz\"'\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If ``False``, let python handle the positional
arguments. Set to ``True`` to use shell features, such as pipes or
redirection.
:param bool bg: If ``True``, run command in background and do not await or
deliver it's results
.. versionadded:: 2016.3.0
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
:param bool raise_err: If ``True`` and the command has a nonzero exit code,
a CommandExecutionError exception will be raised.
.. warning::
This function does not process commands through a shell
unless the python_shell flag is set to True. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or
have the python_shell=True flag set here.
The use of python_shell=True means that the shell will accept _any_ input
including potentially malicious commands such as 'good_command;rm -rf /'.
Be absolutely certain that you have sanitized your input prior to using
python_shell=True
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run cmd='sed -e s/=/:/g'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
log_callback = _check_cb(log_callback)
lvl = _check_loglevel(output_loglevel)
if lvl is not None:
if not ignore_retcode and ret['retcode'] != 0:
if lvl < LOG_LEVELS['error']:
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if raise_err:
raise CommandExecutionError(
log_callback(ret['stdout'] if not hide_output else '')
)
log.log(lvl, 'output: %s', log_callback(ret['stdout']))
return ret['stdout'] if not hide_output else ''
def shell(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return the output as a string.
.. versionadded:: 2015.5.0
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.shell 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param int shell: Shell to execute under. Defaults to the system default
shell.
:param bool bg: If True, run command in background and do not await or
deliver its results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.shell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
.. warning::
This passes the cmd argument directly to the shell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.shell "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.shell template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.shell "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.shell "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.shell cmd='sed -e s/=/:/g'
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
return run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
def run_stdout(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command, and only return the standard out
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stdout 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stdout template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stdout "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stdout'] if not hide_output else ''
def run_stderr(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command and only return the standard error
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stderr 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stderr 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stderr "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stderr template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stderr "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stderr'] if not hide_output else ''
def run_all(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
redirect_stderr=False,
password=None,
encoded_cmd=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return a dict of return data
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_all 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
.. versionadded:: 2018.3.0
:param bool redirect_stderr: If set to ``True``, then stderr will be
redirected to stdout. This is helpful for cases where obtaining both
the retcode and output is desired, but it is not desired to have the
output separated into both stdout and stderr.
.. versionadded:: 2015.8.2
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param bool bg: If ``True``, run command in background and do not await or
deliver its results
.. versionadded:: 2016.3.6
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_all "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_all template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_all "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=stderr,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def retcode(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a shell command and return the command's return code.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.retcode 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.retcode 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:rtype: int
:rtype: None
:returns: Return Code as an int or None if there was an exception.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.retcode "file /bin/bash"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.retcode template=jinja "file {{grains.pythonpath[0]}}/python"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.retcode "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['retcode']
def _retcode_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Helper for running commands quietly for minion startup. Returns same as
the retcode() function.
'''
return retcode(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stderr,
success_stderr=success_stderr,
**kwargs)
def script(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
saltenv='base',
use_vt=False,
bg=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
.. code-block:: bash
salt myminion cmd.script salt://foo.sh "arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param bool bg: If True, run script in background and do not await or
deliver it's results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh
salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
def _cleanup_tempfile(path):
try:
__salt__['file.remove'](path)
except (SaltInvocationError, CommandExecutionError) as exc:
log.error(
'cmd.script: Unable to clean tempfile \'%s\': %s',
path, exc, exc_info_on_loglevel=logging.DEBUG
)
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
win_cwd = False
if salt.utils.platform.is_windows() and runas and cwd is None:
# Create a temp working directory
cwd = tempfile.mkdtemp(dir=__opts__['cachedir'])
win_cwd = True
salt.utils.win_dacl.set_permissions(obj_name=cwd,
principal=runas,
permissions='full_control')
path = salt.utils.files.mkstemp(dir=cwd, suffix=os.path.splitext(source)[1])
if template:
if 'pillarenv' in kwargs or 'pillar' in kwargs:
pillarenv = kwargs.get('pillarenv', __opts__.get('pillarenv'))
kwargs['pillar'] = _gather_pillar(pillarenv, kwargs.get('pillar'))
fn_ = __salt__['cp.get_template'](source,
path,
template,
saltenv,
**kwargs)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
else:
fn_ = __salt__['cp.cache_file'](source, saltenv)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
shutil.copyfile(fn_, path)
if not salt.utils.platform.is_windows():
os.chmod(path, 320)
os.chown(path, __salt__['file.user_to_uid'](runas), -1)
if salt.utils.platform.is_windows() and shell.lower() != 'powershell':
cmd_path = _cmd_quote(path, escape=False)
else:
cmd_path = _cmd_quote(path)
ret = _run(cmd_path + ' ' + six.text_type(args) if args else cmd_path,
cwd=cwd,
stdin=stdin,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def script_retcode(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template='jinja',
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
output_encoding=None,
output_loglevel='debug',
log_callback=None,
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
The script can also be formatted as a template, the default is jinja.
Only evaluate the script return code and do not block for terminal output
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
"arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script_retcode 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh
salt '*' cmd.script_retcode salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script_retcode salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
return script(source=source,
args=args,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)['retcode']
def which(cmd):
'''
Returns the path of an executable available on the minion, None otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.which cat
'''
return salt.utils.path.which(cmd)
def which_bin(cmds):
'''
Returns the first command found in a list of commands
CLI Example:
.. code-block:: bash
salt '*' cmd.which_bin '[pip2, pip, pip-python]'
'''
return salt.utils.path.which_bin(cmds)
def has_exec(cmd):
'''
Returns true if the executable is available on the minion, false otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.has_exec cat
'''
return which(cmd) is not None
def exec_code(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. The stdout will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code ruby 'puts "cheese"'
salt '*' cmd.exec_code ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
return exec_code_all(lang, code, cwd, args, **kwargs)['stdout']
def exec_code_all(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid)
will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code_all ruby 'puts "cheese"'
salt '*' cmd.exec_code_all ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
powershell = lang.lower().startswith("powershell")
if powershell:
codefile = salt.utils.files.mkstemp(suffix=".ps1")
else:
codefile = salt.utils.files.mkstemp()
with salt.utils.files.fopen(codefile, 'w+t', binary=False) as fp_:
fp_.write(salt.utils.stringutils.to_str(code))
if powershell:
cmd = [lang, "-File", codefile]
else:
cmd = [lang, codefile]
if isinstance(args, six.string_types):
cmd.append(args)
elif isinstance(args, list):
cmd += args
ret = run_all(cmd, cwd=cwd, python_shell=False, **kwargs)
os.remove(codefile)
return ret
def tty(device, echo=''):
'''
Echo a string to a specific tty
CLI Example:
.. code-block:: bash
salt '*' cmd.tty tty0 'This is a test'
salt '*' cmd.tty pts3 'This is a test'
'''
if device.startswith('tty'):
teletype = '/dev/{0}'.format(device)
elif device.startswith('pts'):
teletype = '/dev/{0}'.format(device.replace('pts', 'pts/'))
else:
return {'Error': 'The specified device is not a valid TTY'}
try:
with salt.utils.files.fopen(teletype, 'wb') as tty_device:
tty_device.write(salt.utils.stringutils.to_bytes(echo))
return {
'Success': 'Message was successfully echoed to {0}'.format(teletype)
}
except IOError:
return {
'Error': 'Echoing to {0} returned error'.format(teletype)
}
def run_chroot(root,
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=True,
binds=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='quiet',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
.. versionadded:: 2014.7.0
This function runs :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` wrapped
within a chroot, with dev and proc mounted in the chroot
:param str root: Path to the root of the jail to use.
:param str stdin: A string of standard input can be specified for
the command to be run using the ``stdin`` parameter. This can
be useful in cases where sensitive information must be read
from standard input.:
:param str runas: User to run script as.
:param str group: Group to run script as.
:param str shell: Shell to execute under. Defaults to the system
default shell.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:parar str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param list binds: List of directories that will be exported inside
the chroot with the bind option.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_chroot 'some command' env='{"FOO": "bar"}'
:param dict clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output
before it is returned.
:param str umask: The umask (in octal) to use when running the
command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout:
A timeout in seconds for the executed process to return.
:param bool use_vt:
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs. This is experimental.
:param success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' cmd.run_chroot /var/lib/lxc/container_name/rootfs 'sh /tmp/bootstrap.sh'
'''
__salt__['mount.mount'](
os.path.join(root, 'dev'),
'devtmpfs',
fstype='devtmpfs')
__salt__['mount.mount'](
os.path.join(root, 'proc'),
'proc',
fstype='proc')
__salt__['mount.mount'](
os.path.join(root, 'sys'),
'sysfs',
fstype='sysfs')
binds = binds if binds else []
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.mount'](
bind_exported_to,
bind_exported,
opts='default,bind')
# Execute chroot routine
sh_ = '/bin/sh'
if os.path.isfile(os.path.join(root, 'bin/bash')):
sh_ = '/bin/bash'
if isinstance(cmd, (list, tuple)):
cmd = ' '.join([six.text_type(i) for i in cmd])
cmd = 'chroot {0} {1} -c {2}'.format(root, sh_, _cmd_quote(cmd))
run_func = __context__.pop('cmd.run_chroot.func', run_all)
ret = run_func(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
pillarenv=kwargs.get('pillarenv'),
pillar=kwargs.get('pillar'),
use_vt=use_vt,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
bg=bg)
# Kill processes running in the chroot
for i in range(6):
pids = _chroot_pids(root)
if not pids:
break
for pid in pids:
# use sig 15 (TERM) for first 3 attempts, then 9 (KILL)
sig = 15 if i < 3 else 9
os.kill(pid, sig)
if _chroot_pids(root):
log.error('Processes running in chroot could not be killed, '
'filesystem will remain mounted')
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.umount'](bind_exported_to)
__salt__['mount.umount'](os.path.join(root, 'sys'))
__salt__['mount.umount'](os.path.join(root, 'proc'))
__salt__['mount.umount'](os.path.join(root, 'dev'))
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def _is_valid_shell(shell):
'''
Attempts to search for valid shells on a system and
see if a given shell is in the list
'''
if salt.utils.platform.is_windows():
return True # Don't even try this for Windows
shells = '/etc/shells'
available_shells = []
if os.path.exists(shells):
try:
with salt.utils.files.fopen(shells, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
if line.startswith('#'):
continue
else:
available_shells.append(line)
except OSError:
return True
else:
# No known method of determining available shells
return None
if shell in available_shells:
return True
else:
return False
def shells():
'''
Lists the valid shells on this system via the /etc/shells file
.. versionadded:: 2015.5.0
CLI Example::
salt '*' cmd.shells
'''
shells_fn = '/etc/shells'
ret = []
if os.path.exists(shells_fn):
try:
with salt.utils.files.fopen(shells_fn, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
line = line.strip()
if line.startswith('#'):
continue
elif not line:
continue
else:
ret.append(line)
except OSError:
log.error("File '%s' was not found", shells_fn)
return ret
def shell_info(shell, list_modules=False):
'''
.. versionadded:: 2016.11.0
Provides information about a shell or script languages which often use
``#!``. The values returned are dependent on the shell or scripting
languages all return the ``installed``, ``path``, ``version``,
``version_raw``
Args:
shell (str): Name of the shell. Support shells/script languages include
bash, cmd, perl, php, powershell, python, ruby and zsh
list_modules (bool): True to list modules available to the shell.
Currently only lists powershell modules.
Returns:
dict: A dictionary of information about the shell
.. code-block:: python
{'version': '<2 or 3 numeric components dot-separated>',
'version_raw': '<full version string>',
'path': '<full path to binary>',
'installed': <True, False or None>,
'<attribute>': '<attribute value>'}
.. note::
- ``installed`` is always returned, if ``None`` or ``False`` also
returns error and may also return ``stdout`` for diagnostics.
- ``version`` is for use in determine if a shell/script language has a
particular feature set, not for package management.
- The shell must be within the executable search path.
CLI Example:
.. code-block:: bash
salt '*' cmd.shell_info bash
salt '*' cmd.shell_info powershell
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
regex_shells = {
'bash': [r'version (\d\S*)', 'bash', '--version'],
'bash-test-error': [r'versioZ ([-\w.]+)', 'bash', '--version'], # used to test an error result
'bash-test-env': [r'(HOME=.*)', 'bash', '-c', 'declare'], # used to test an error result
'zsh': [r'^zsh (\d\S*)', 'zsh', '--version'],
'tcsh': [r'^tcsh (\d\S*)', 'tcsh', '--version'],
'cmd': [r'Version ([\d.]+)', 'cmd.exe', '/C', 'ver'],
'powershell': [r'PSVersion\s+(\d\S*)', 'powershell', '-NonInteractive', '$PSVersionTable'],
'perl': [r'^(\d\S*)', 'perl', '-e', 'printf "%vd\n", $^V;'],
'python': [r'^Python (\d\S*)', 'python', '-V'],
'ruby': [r'^ruby (\d\S*)', 'ruby', '-v'],
'php': [r'^PHP (\d\S*)', 'php', '-v']
}
# Ensure ret['installed'] always as a value of True, False or None (not sure)
ret = {'installed': False}
if salt.utils.platform.is_windows() and shell == 'powershell':
pw_keys = salt.utils.win_reg.list_keys(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell')
pw_keys.sort(key=int)
if not pw_keys:
return {
'error': 'Unable to locate \'powershell\' Reason: Cannot be '
'found in registry.',
'installed': False,
}
for reg_ver in pw_keys:
install_data = salt.utils.win_reg.read_value(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}'.format(reg_ver),
vname='Install')
if install_data.get('vtype') == 'REG_DWORD' and \
install_data.get('vdata') == 1:
details = salt.utils.win_reg.list_values(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}\\'
'PowerShellEngine'.format(reg_ver))
# reset data, want the newest version details only as powershell
# is backwards compatible
ret = {}
# if all goes well this will become True
ret['installed'] = None
ret['path'] = which('powershell.exe')
for attribute in details:
if attribute['vname'].lower() == '(default)':
continue
elif attribute['vname'].lower() == 'powershellversion':
ret['psversion'] = attribute['vdata']
ret['version_raw'] = attribute['vdata']
elif attribute['vname'].lower() == 'runtimeversion':
ret['crlversion'] = attribute['vdata']
if ret['crlversion'][0].lower() == 'v':
ret['crlversion'] = ret['crlversion'][1::]
elif attribute['vname'].lower() == 'pscompatibleversion':
# reg attribute does not end in s, the powershell
# attribute does
ret['pscompatibleversions'] = \
attribute['vdata'].replace(' ', '').split(',')
else:
# keys are lower case as python is case sensitive the
# registry is not
ret[attribute['vname'].lower()] = attribute['vdata']
else:
if shell not in regex_shells:
return {
'error': 'Salt does not know how to get the version number for '
'{0}'.format(shell),
'installed': None
}
shell_data = regex_shells[shell]
pattern = shell_data.pop(0)
# We need to make sure HOME set, so shells work correctly
# salt-call will general have home set, the salt-minion service may not
# We need to assume ports of unix shells to windows will look after
# themselves in setting HOME as they do it in many different ways
newenv = os.environ
if ('HOME' not in newenv) and (not salt.utils.platform.is_windows()):
newenv['HOME'] = os.path.expanduser('~')
log.debug('HOME environment set to %s', newenv['HOME'])
try:
proc = salt.utils.timed_subprocess.TimedProc(
shell_data,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=10,
env=newenv
)
except (OSError, IOError) as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: {1}'.format(' '.join(shell_data), exc),
'installed': False,
}
try:
proc.run()
except TimedProcTimeoutError as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: Timed out.'.format(' '.join(shell_data)),
'installed': False,
}
ret['path'] = which(shell_data[0])
pattern_result = re.search(pattern, proc.stdout, flags=re.IGNORECASE)
# only set version if we find it, so code later on can deal with it
if pattern_result:
ret['version_raw'] = pattern_result.group(1)
if 'version_raw' in ret:
version_results = re.match(r'(\d[\d.]*)', ret['version_raw'])
if version_results:
ret['installed'] = True
ver_list = version_results.group(1).split('.')[:3]
if len(ver_list) == 1:
ver_list.append('0')
ret['version'] = '.'.join(ver_list[:3])
else:
ret['installed'] = None # Have an unexpected result
# Get a list of the PowerShell modules which are potentially available
# to be imported
if shell == 'powershell' and ret['installed'] and list_modules:
ret['modules'] = salt.utils.powershell.get_modules()
if 'version' not in ret:
ret['error'] = 'The version regex pattern for shell {0}, could not ' \
'find the version string'.format(shell)
ret['stdout'] = proc.stdout # include stdout so they can see the issue
log.error(ret['error'])
return ret
def powershell(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return the output as a dictionary.
Other ``cmd.*`` functions (besides ``cmd.powershell_all``)
return the raw text output of the command. This
function appends ``| ConvertTo-JSON`` to the command and then parses the
JSON into a Python dictionary. If you want the raw textual result of your
PowerShell command you should use ``cmd.run`` with the ``shell=powershell``
option.
For example:
.. code-block:: bash
salt '*' cmd.run '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2016.3.0
.. warning::
This passes the cmd argument directly to PowerShell
without any further processing! Be absolutely sure that you
have properly sanitized the command passed to this function
and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in cases
where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
.. versionadded:: 2016.3.4
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:returns:
:dict: A dictionary of data returned by the powershell command.
CLI Example:
.. code-block:: powershell
salt '*' cmd.powershell "$PSVersionTable.CLRVersion"
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
# ConvertTo-JSON is only available on PowerShell 3.0 and later
psversion = shell_info('powershell')['psversion']
if salt.utils.versions.version_cmp(psversion, '2.0') == 1:
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Put the whole command inside a try / catch block
# Some errors in PowerShell are not "Terminating Errors" and will not be
# caught in a try/catch block. For example, the `Get-WmiObject` command will
# often return a "Non Terminating Error". To fix this, make sure
# `-ErrorAction Stop` is set in the powershell command
cmd = 'try {' + cmd + '} catch { "{}" }'
# Retrieve the response, while overriding shell with 'powershell'
response = run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
try:
return salt.utils.json.loads(response)
except Exception:
log.error("Error converting PowerShell JSON return", exc_info=True)
return {}
def powershell_all(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
quiet=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
force_list=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return a dictionary with a result
field representing the output of the command, as well as other fields
showing us what the PowerShell invocation wrote to ``stderr``, the process
id, and the exit code of the invocation.
This function appends ``| ConvertTo-JSON`` to the command before actually
invoking powershell.
An unquoted empty string is not valid JSON, but it's very normal for the
Powershell output to be exactly that. Therefore, we do not attempt to parse
empty Powershell output (which would result in an exception). Instead we
treat this as a special case and one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field of the return dictionary will be an empty list.
- If the value of the ``force_list`` parameter is ``False``, then the
return dictionary **will not have a result key added to it**. We aren't
setting ``result`` to ``None`` in this case, because ``None`` is the
Python representation of "null" in JSON. (We likewise can't use ``False``
for the equivalent reason.)
If Powershell's output is not an empty string and Python cannot parse its
content, then a ``CommandExecutionError`` exception will be raised.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is other than ``list``
then one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field will be a singleton list with the Python object as its
sole member.
- If the value of the ``force_list`` parameter is ``False``, then the value
of ``result`` will be the unmodified Python object.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is ``list``, then the
value of ``result`` will be the unmodified Python object. The
``force_list`` parameter has no effect in this case.
.. note::
An example of why the ``force_list`` parameter is useful is as
follows: The Powershell command ``dir x | Convert-ToJson`` results in
- no output when x is an empty directory.
- a dictionary object when x contains just one item.
- a list of dictionary objects when x contains multiple items.
By setting ``force_list`` to ``True`` we will always end up with a
list of dictionary items, representing files, no matter how many files
x contains. Conversely, if ``force_list`` is ``False``, we will end
up with no ``result`` key in our return dictionary when x is an empty
directory, and a dictionary object when x contains just one file.
If you want a similar function but with a raw textual result instead of a
Python dictionary, you should use ``cmd.run_all`` in combination with
``shell=powershell``.
The remaining fields in the return dictionary are described in more detail
in the ``Returns`` section.
Example:
.. code-block:: bash
salt '*' cmd.run_all '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run_all 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2018.3.0
.. warning::
This passes the cmd argument directly to PowerShell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param bool force_list: The purpose of this parameter is described in the
preamble of this function's documentation. Default value is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:return: A dictionary with the following entries:
result
For a complete description of this field, please refer to this
function's preamble. **This key will not be added to the dictionary
when force_list is False and Powershell's output is the empty
string.**
stderr
What the PowerShell invocation wrote to ``stderr``.
pid
The process id of the PowerShell invocation
retcode
This is the exit code of the invocation of PowerShell.
If the final execution status (in PowerShell) of our command
(with ``| ConvertTo-JSON`` appended) is ``False`` this should be non-0.
Likewise if PowerShell exited with ``$LASTEXITCODE`` set to some
non-0 value, then ``retcode`` will end up with this value.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "$PSVersionTable.CLRVersion"
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "dir mydirectory" force_list=True
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Retrieve the response, while overriding shell with 'powershell'
response = run_all(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
quiet=quiet,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
stdoutput = response['stdout']
# if stdoutput is the empty string and force_list is True we return an empty list
# Otherwise we return response with no result key
if not stdoutput:
response.pop('stdout')
if force_list:
response['result'] = []
return response
# If we fail to parse stdoutput we will raise an exception
try:
result = salt.utils.json.loads(stdoutput)
except Exception:
err_msg = "cmd.powershell_all " + \
"cannot parse the Powershell output."
response["cmd"] = cmd
raise CommandExecutionError(
message=err_msg,
info=response
)
response.pop("stdout")
if type(result) is not list:
if force_list:
response['result'] = [result]
else:
response['result'] = result
else:
# result type is list so the force_list param has no effect
response['result'] = result
return response
def run_bg(cmd,
cwd=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
timeout=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
.. versionadded: 2016.3.0
Execute the passed command in the background and return it's PID
.. note::
If the init system is systemd and the backgrounded task should run even
if the salt-minion process is restarted, prepend ``systemd-run
--scope`` to the command. This will reparent the process in its own
scope separate from salt-minion, and will not be affected by restarting
the minion service.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Shell to execute under. Defaults to the system default
shell.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_bg 'echo '\''h=\"baz\"'\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_bg 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param int timeout: A timeout in seconds for the executed process to return.
.. warning::
This function does not process commands through a shell unless the
``python_shell`` argument is set to ``True``. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or have the
python_shell=True flag set here.
The use of ``python_shell=True`` means that the shell will accept _any_
input including potentially malicious commands such as 'good_command;rm
-rf /'. Be absolutely certain that you have sanitized your input prior
to using ``python_shell=True``.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_bg "fstrim-all"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_bg template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run_bg "Get-ChildItem C:\\ " shell='powershell'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run_bg cmd='ls -lR / | sed -e s/=/:/g > /tmp/dontwait'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
res = _run(cmd,
stdin=None,
stderr=None,
stdout=None,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
use_vt=None,
bg=True,
with_communicate=False,
rstrip=False,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
umask=umask,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs
)
return {
'pid': res['pid']
}
|
saltstack/salt
|
salt/modules/cmdmod.py
|
_run
|
python
|
def _run(cmd,
cwd=None,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
prepend_path=None,
rstrip=True,
template=None,
umask=None,
timeout=None,
with_communicate=True,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
pillarenv=None,
pillar_override=None,
use_vt=False,
password=None,
bg=False,
encoded_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Do the DRY thing and only call subprocess.Popen() once
'''
if 'pillar' in kwargs and not pillar_override:
pillar_override = kwargs['pillar']
if output_loglevel != 'quiet' and _is_valid_shell(shell) is False:
log.warning(
'Attempt to run a shell command with what may be an invalid shell! '
'Check to ensure that the shell <%s> is valid for this user.',
shell
)
output_loglevel = _check_loglevel(output_loglevel)
log_callback = _check_cb(log_callback)
use_sudo = False
if runas is None and '__context__' in globals():
runas = __context__.get('runas')
if password is None and '__context__' in globals():
password = __context__.get('runas_password')
# Set the default working directory to the home directory of the user
# salt-minion is running as. Defaults to home directory of user under which
# the minion is running.
if not cwd:
cwd = os.path.expanduser('~{0}'.format('' if not runas else runas))
# make sure we can access the cwd
# when run from sudo or another environment where the euid is
# changed ~ will expand to the home of the original uid and
# the euid might not have access to it. See issue #1844
if not os.access(cwd, os.R_OK):
cwd = '/'
if salt.utils.platform.is_windows():
cwd = os.path.abspath(os.sep)
else:
# Handle edge cases where numeric/other input is entered, and would be
# yaml-ified into non-string types
cwd = six.text_type(cwd)
if bg:
ignore_retcode = True
use_vt = False
if not salt.utils.platform.is_windows():
if not os.path.isfile(shell) or not os.access(shell, os.X_OK):
msg = 'The shell {0} is not available'.format(shell)
raise CommandExecutionError(msg)
if salt.utils.platform.is_windows() and use_vt: # Memozation so not much overhead
raise CommandExecutionError('VT not available on windows')
if shell.lower().strip() == 'powershell':
# Strip whitespace
if isinstance(cmd, six.string_types):
cmd = cmd.strip()
# If we were called by script(), then fakeout the Windows
# shell to run a Powershell script.
# Else just run a Powershell command.
stack = traceback.extract_stack(limit=2)
# extract_stack() returns a list of tuples.
# The last item in the list [-1] is the current method.
# The third item[2] in each tuple is the name of that method.
if stack[-2][2] == 'script':
cmd = 'Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -File ' + cmd
elif encoded_cmd:
cmd = 'Powershell -NonInteractive -EncodedCommand {0}'.format(cmd)
else:
cmd = 'Powershell -NonInteractive -NoProfile "{0}"'.format(cmd.replace('"', '\\"'))
# munge the cmd and cwd through the template
(cmd, cwd) = _render_cmd(cmd, cwd, template, saltenv, pillarenv, pillar_override)
ret = {}
# If the pub jid is here then this is a remote ex or salt call command and needs to be
# checked if blacklisted
if '__pub_jid' in kwargs:
if not _check_avail(cmd):
raise CommandExecutionError(
'The shell command "{0}" is not permitted'.format(cmd)
)
env = _parse_env(env)
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, six.string_types) else x for x in cmd]
elif isinstance(cmd, six.string_types):
return cmd.strip()
else:
return cmd
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' parameter.
msg = (
'Executing command {0}{1}{0} {2}{3}in directory \'{4}\'{5}'.format(
'\'' if not isinstance(cmd, list) else '',
_get_stripped(cmd),
'as user \'{0}\' '.format(runas) if runas else '',
'in group \'{0}\' '.format(group) if group else '',
cwd,
'. Executing command in the background, no output will be '
'logged.' if bg else ''
)
)
log.info(log_callback(msg))
if runas and salt.utils.platform.is_windows():
if not HAS_WIN_RUNAS:
msg = 'missing salt/utils/win_runas.py'
raise CommandExecutionError(msg)
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(cmd)
return win_runas(cmd, runas, password, cwd)
if runas and salt.utils.platform.is_darwin():
# we need to insert the user simulation into the command itself and not
# just run it from the environment on macOS as that
# method doesn't work properly when run as root for certain commands.
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(map(_cmd_quote, cmd))
cmd = 'su -l {0} -c "cd {1}; {2}"'.format(runas, cwd, cmd)
# set runas to None, because if you try to run `su -l` as well as
# simulate the environment macOS will prompt for the password of the
# user and will cause salt to hang.
runas = None
if runas:
# Save the original command before munging it
try:
pwd.getpwnam(runas)
except KeyError:
raise CommandExecutionError(
'User \'{0}\' is not available'.format(runas)
)
if group:
if salt.utils.platform.is_windows():
msg = 'group is not currently available on Windows'
raise SaltInvocationError(msg)
if not which_bin(['sudo']):
msg = 'group argument requires sudo but not found'
raise CommandExecutionError(msg)
try:
grp.getgrnam(group)
except KeyError:
raise CommandExecutionError(
'Group \'{0}\' is not available'.format(runas)
)
else:
use_sudo = True
if runas or group:
try:
# Getting the environment for the runas user
# Use markers to thwart any stdout noise
# There must be a better way to do this.
import uuid
marker = '<<<' + str(uuid.uuid4()) + '>>>'
marker_b = marker.encode(__salt_system_encoding__)
py_code = (
'import sys, os, itertools; '
'sys.stdout.write(\"' + marker + '\"); '
'sys.stdout.write(\"\\0\".join(itertools.chain(*os.environ.items()))); '
'sys.stdout.write(\"' + marker + '\");'
)
if use_sudo or __grains__['os'] in ['MacOS', 'Darwin']:
env_cmd = ['sudo']
# runas is optional if use_sudo is set.
if runas:
env_cmd.extend(['-u', runas])
if group:
env_cmd.extend(['-g', group])
if shell != DEFAULT_SHELL:
env_cmd.extend(['-s', '--', shell, '-c'])
else:
env_cmd.extend(['-i', '--'])
env_cmd.extend([sys.executable])
elif __grains__['os'] in ['FreeBSD']:
env_cmd = ('su', '-', runas, '-c',
"{0} -c {1}".format(shell, sys.executable))
elif __grains__['os_family'] in ['Solaris']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
elif __grains__['os_family'] in ['AIX']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
else:
env_cmd = ('su', '-s', shell, '-', runas, '-c', sys.executable)
msg = 'env command: {0}'.format(env_cmd)
log.debug(log_callback(msg))
env_bytes, env_encoded_err = subprocess.Popen(
env_cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
).communicate(salt.utils.stringutils.to_bytes(py_code))
marker_count = env_bytes.count(marker_b)
if marker_count == 0:
# Possibly PAM prevented the login
log.error(
'Environment could not be retrieved for user \'%s\': '
'stderr=%r stdout=%r',
runas, env_encoded_err, env_bytes
)
# Ensure that we get an empty env_runas dict below since we
# were not able to get the environment.
env_bytes = b''
elif marker_count != 2:
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\'',
info={'stderr': repr(env_encoded_err),
'stdout': repr(env_bytes)}
)
else:
# Strip the marker
env_bytes = env_bytes.split(marker_b)[1]
if six.PY2:
import itertools
env_runas = dict(itertools.izip(*[iter(env_bytes.split(b'\0'))]*2))
elif six.PY3:
env_runas = dict(list(zip(*[iter(env_bytes.split(b'\0'))]*2)))
env_runas = dict(
(salt.utils.stringutils.to_str(k),
salt.utils.stringutils.to_str(v))
for k, v in six.iteritems(env_runas)
)
env_runas.update(env)
# Fix platforms like Solaris that don't set a USER env var in the
# user's default environment as obtained above.
if env_runas.get('USER') != runas:
env_runas['USER'] = runas
# Fix some corner cases where shelling out to get the user's
# environment returns the wrong home directory.
runas_home = os.path.expanduser('~{0}'.format(runas))
if env_runas.get('HOME') != runas_home:
env_runas['HOME'] = runas_home
env = env_runas
except ValueError as exc:
log.exception('Error raised retrieving environment for user %s', runas)
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\': {1}'.format(
runas, exc
)
)
if reset_system_locale is True:
if not salt.utils.platform.is_windows():
# Default to C!
# Salt only knows how to parse English words
# Don't override if the user has passed LC_ALL
env.setdefault('LC_CTYPE', 'C')
env.setdefault('LC_NUMERIC', 'C')
env.setdefault('LC_TIME', 'C')
env.setdefault('LC_COLLATE', 'C')
env.setdefault('LC_MONETARY', 'C')
env.setdefault('LC_MESSAGES', 'C')
env.setdefault('LC_PAPER', 'C')
env.setdefault('LC_NAME', 'C')
env.setdefault('LC_ADDRESS', 'C')
env.setdefault('LC_TELEPHONE', 'C')
env.setdefault('LC_MEASUREMENT', 'C')
env.setdefault('LC_IDENTIFICATION', 'C')
env.setdefault('LANGUAGE', 'C')
else:
# On Windows set the codepage to US English.
if python_shell:
cmd = 'chcp 437 > nul & ' + cmd
if clean_env:
run_env = env
else:
run_env = os.environ.copy()
run_env.update(env)
if prepend_path:
run_env['PATH'] = ':'.join((prepend_path, run_env['PATH']))
if python_shell is None:
python_shell = False
new_kwargs = {'cwd': cwd,
'shell': python_shell,
'env': run_env if six.PY3 else salt.utils.data.encode(run_env),
'stdin': six.text_type(stdin) if stdin is not None else stdin,
'stdout': stdout,
'stderr': stderr,
'with_communicate': with_communicate,
'timeout': timeout,
'bg': bg,
}
if 'stdin_raw_newlines' in kwargs:
new_kwargs['stdin_raw_newlines'] = kwargs['stdin_raw_newlines']
if umask is not None:
_umask = six.text_type(umask).lstrip('0')
if _umask == '':
msg = 'Zero umask is not allowed.'
raise CommandExecutionError(msg)
try:
_umask = int(_umask, 8)
except ValueError:
raise CommandExecutionError("Invalid umask: '{0}'".format(umask))
else:
_umask = None
if runas or group or umask:
new_kwargs['preexec_fn'] = functools.partial(
salt.utils.user.chugid_and_umask,
runas,
_umask,
group)
if not salt.utils.platform.is_windows():
# close_fds is not supported on Windows platforms if you redirect
# stdin/stdout/stderr
if new_kwargs['shell'] is True:
new_kwargs['executable'] = shell
new_kwargs['close_fds'] = True
if not os.path.isabs(cwd) or not os.path.isdir(cwd):
raise CommandExecutionError(
'Specified cwd \'{0}\' either not absolute or does not exist'
.format(cwd)
)
if python_shell is not True \
and not salt.utils.platform.is_windows() \
and not isinstance(cmd, list):
cmd = salt.utils.args.shlex_split(cmd)
if success_retcodes is None:
success_retcodes = [0]
else:
try:
success_retcodes = [int(i) for i in
salt.utils.args.split_input(
success_retcodes
)]
except ValueError:
raise SaltInvocationError(
'success_retcodes must be a list of integers'
)
if success_stdout is None:
success_stdout = []
else:
try:
success_stdout = [i for i in
salt.utils.args.split_input(
success_stdout
)]
except ValueError:
raise SaltInvocationError(
'success_stdout must be a list of integers'
)
if success_stderr is None:
success_stderr = []
else:
try:
success_stderr = [i for i in
salt.utils.args.split_input(
success_stderr
)]
except ValueError:
raise SaltInvocationError(
'success_stderr must be a list of integers'
)
if not use_vt:
# This is where the magic happens
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **new_kwargs)
except (OSError, IOError) as exc:
msg = (
'Unable to run command \'{0}\' with the context \'{1}\', '
'reason: {2}'.format(
cmd if output_loglevel is not None else 'REDACTED',
new_kwargs,
exc
)
)
raise CommandExecutionError(msg)
try:
proc.run()
except TimedProcTimeoutError as exc:
ret['stdout'] = six.text_type(exc)
ret['stderr'] = ''
ret['retcode'] = None
ret['pid'] = proc.process.pid
# ok return code for timeouts?
ret['retcode'] = 1
return ret
if output_loglevel != 'quiet' and output_encoding is not None:
log.debug('Decoding output from command %s using %s encoding',
cmd, output_encoding)
try:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding)
except TypeError:
# stdout is None
out = ''
except UnicodeDecodeError:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', cmd
)
try:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding)
except TypeError:
# stderr is None
err = ''
except UnicodeDecodeError:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', cmd
)
if rstrip:
if out is not None:
out = out.rstrip()
if err is not None:
err = err.rstrip()
ret['pid'] = proc.process.pid
ret['retcode'] = proc.process.returncode
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
ret['stdout'] = out
ret['stderr'] = err
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
else:
formatted_timeout = ''
if timeout:
formatted_timeout = ' (timeout: {0}s)'.format(timeout)
if output_loglevel is not None:
msg = 'Running {0} in VT{1}'.format(cmd, formatted_timeout)
log.debug(log_callback(msg))
stdout, stderr = '', ''
now = time.time()
if timeout:
will_timeout = now + timeout
else:
will_timeout = -1
try:
proc = salt.utils.vt.Terminal(
cmd,
shell=True,
log_stdout=True,
log_stderr=True,
cwd=cwd,
preexec_fn=new_kwargs.get('preexec_fn', None),
env=run_env,
log_stdin_level=output_loglevel,
log_stdout_level=output_loglevel,
log_stderr_level=output_loglevel,
stream_stdout=True,
stream_stderr=True
)
ret['pid'] = proc.pid
while proc.has_unread_data:
try:
try:
time.sleep(0.5)
try:
cstdout, cstderr = proc.recv()
except IOError:
cstdout, cstderr = '', ''
if cstdout:
stdout += cstdout
else:
cstdout = ''
if cstderr:
stderr += cstderr
else:
cstderr = ''
if timeout and (time.time() > will_timeout):
ret['stderr'] = (
'SALT: Timeout after {0}s\n{1}').format(
timeout, stderr)
ret['retcode'] = None
break
except KeyboardInterrupt:
ret['stderr'] = 'SALT: User break\n{0}'.format(stderr)
ret['retcode'] = 1
break
except salt.utils.vt.TerminalException as exc:
log.error('VT: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
ret = {'retcode': 1, 'pid': '2'}
break
# only set stdout on success as we already mangled in other
# cases
ret['stdout'] = stdout
if not proc.isalive():
# Process terminated, i.e., not canceled by the user or by
# the timeout
ret['stderr'] = stderr
ret['retcode'] = proc.exitstatus
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
ret['pid'] = proc.pid
finally:
proc.close(terminate=True, kill=True)
try:
if ignore_retcode:
__context__['retcode'] = 0
else:
__context__['retcode'] = ret['retcode']
except NameError:
# Ignore the context error during grain generation
pass
# Log the output
if output_loglevel is not None:
if not ignore_retcode and ret['retcode'] != 0:
if output_loglevel < LOG_LEVELS['error']:
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if ret['stdout']:
log.log(output_loglevel, 'stdout: %s', log_callback(ret['stdout']))
if ret['stderr']:
log.log(output_loglevel, 'stderr: %s', log_callback(ret['stderr']))
if ret['retcode']:
log.log(output_loglevel, 'retcode: %s', ret['retcode'])
return ret
|
Do the DRY thing and only call subprocess.Popen() once
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cmdmod.py#L250-L858
|
[
"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 iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def which_bin(cmds):\n '''\n Returns the first command found in a list of commands\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cmd.which_bin '[pip2, pip, pip-python]'\n '''\n return salt.utils.path.which_bin(cmds)\n",
"def runas(cmdLine, username, password=None, cwd=None):\n '''\n Run a command as another user. If the process is running as an admin or\n system account this method does not require a password. Other non\n privileged accounts need to provide a password for the user to runas.\n Commands are run in with the highest level privileges possible for the\n account provided.\n '''\n\n # Elevate the token from the current process\n access = (\n win32security.TOKEN_QUERY |\n win32security.TOKEN_ADJUST_PRIVILEGES\n )\n th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), access)\n salt.platform.win.elevate_token(th)\n\n # Try to impersonate the SYSTEM user. This process needs to be running as a\n # user who as been granted the SeImpersonatePrivilege, Administrator\n # accounts have this permission by default.\n try:\n impersonation_token = salt.platform.win.impersonate_sid(\n salt.platform.win.SYSTEM_SID,\n session_id=0,\n privs=['SeTcbPrivilege'],\n )\n except WindowsError: # pylint: disable=undefined-variable\n log.debug(\"Unable to impersonate SYSTEM user\")\n impersonation_token = None\n\n # Impersonation of the SYSTEM user failed. Fallback to an un-privileged\n # runas.\n if not impersonation_token:\n log.debug(\"No impersonation token, using unprivileged runas\")\n return runas_unpriv(cmdLine, username, password, cwd)\n\n username, domain = split_username(username)\n # Validate the domain and sid exist for the username\n try:\n _, domain, _ = win32security.LookupAccountName(domain, username)\n except pywintypes.error as exc:\n message = win32api.FormatMessage(exc.winerror).rstrip('\\n')\n raise CommandExecutionError(message)\n\n if domain == 'NT AUTHORITY':\n # Logon as a system level account, SYSTEM, LOCAL SERVICE, or NETWORK\n # SERVICE.\n logonType = win32con.LOGON32_LOGON_SERVICE\n user_token = win32security.LogonUser(\n username,\n domain,\n '',\n win32con.LOGON32_LOGON_SERVICE,\n win32con.LOGON32_PROVIDER_DEFAULT,\n )\n elif password:\n # Login with a password.\n user_token = win32security.LogonUser(\n username,\n domain,\n password,\n win32con.LOGON32_LOGON_INTERACTIVE,\n win32con.LOGON32_PROVIDER_DEFAULT,\n )\n else:\n # Login without a password. This always returns an elevated token.\n user_token = salt.platform.win.logon_msv1_s4u(username).Token\n\n # Get a linked user token to elevate if needed\n elevation_type = win32security.GetTokenInformation(\n user_token, win32security.TokenElevationType\n )\n if elevation_type > 1:\n user_token = win32security.GetTokenInformation(\n user_token,\n win32security.TokenLinkedToken\n )\n\n # Elevate the user token\n salt.platform.win.elevate_token(user_token)\n\n # Make sure the user's token has access to a windows station and desktop\n salt.platform.win.grant_winsta_and_desktop(user_token)\n\n # Create pipes for standard in, out and error streams\n security_attributes = win32security.SECURITY_ATTRIBUTES()\n security_attributes.bInheritHandle = 1\n\n stdin_read, stdin_write = win32pipe.CreatePipe(security_attributes, 0)\n stdin_read = salt.platform.win.make_inheritable(stdin_read)\n\n stdout_read, stdout_write = win32pipe.CreatePipe(security_attributes, 0)\n stdout_write = salt.platform.win.make_inheritable(stdout_write)\n\n stderr_read, stderr_write = win32pipe.CreatePipe(security_attributes, 0)\n stderr_write = salt.platform.win.make_inheritable(stderr_write)\n\n # Run the process without showing a window.\n creationflags = (\n win32process.CREATE_NO_WINDOW |\n win32process.CREATE_NEW_CONSOLE |\n win32process.CREATE_SUSPENDED\n )\n\n startup_info = salt.platform.win.STARTUPINFO(\n dwFlags=win32con.STARTF_USESTDHANDLES,\n hStdInput=stdin_read.handle,\n hStdOutput=stdout_write.handle,\n hStdError=stderr_write.handle,\n )\n\n # Create the environment for the user\n env = win32profile.CreateEnvironmentBlock(user_token, False)\n\n # Start the process in a suspended state.\n process_info = salt.platform.win.CreateProcessWithTokenW(\n int(user_token),\n logonflags=1,\n applicationname=None,\n commandline=cmdLine,\n currentdirectory=cwd,\n creationflags=creationflags,\n startupinfo=startup_info,\n environment=env,\n )\n\n hProcess = process_info.hProcess\n hThread = process_info.hThread\n dwProcessId = process_info.dwProcessId\n dwThreadId = process_info.dwThreadId\n\n salt.platform.win.kernel32.CloseHandle(stdin_write.handle)\n salt.platform.win.kernel32.CloseHandle(stdout_write.handle)\n salt.platform.win.kernel32.CloseHandle(stderr_write.handle)\n\n ret = {'pid': dwProcessId}\n # Resume the process\n psutil.Process(dwProcessId).resume()\n\n # Wait for the process to exit and get it's return code.\n if win32event.WaitForSingleObject(hProcess, win32event.INFINITE) == win32con.WAIT_OBJECT_0:\n exitcode = win32process.GetExitCodeProcess(hProcess)\n ret['retcode'] = exitcode\n\n # Read standard out\n fd_out = msvcrt.open_osfhandle(stdout_read.handle, os.O_RDONLY | os.O_TEXT)\n with os.fdopen(fd_out, 'r') as f_out:\n stdout = f_out.read()\n ret['stdout'] = stdout\n\n # Read standard error\n fd_err = msvcrt.open_osfhandle(stderr_read.handle, os.O_RDONLY | os.O_TEXT)\n with os.fdopen(fd_err, 'r') as f_err:\n stderr = f_err.read()\n ret['stderr'] = stderr\n\n salt.platform.win.kernel32.CloseHandle(hProcess)\n win32api.CloseHandle(user_token)\n if impersonation_token:\n win32security.RevertToSelf()\n win32api.CloseHandle(impersonation_token)\n\n return ret\n",
"def _parse_env(env):\n if not env:\n env = {}\n if isinstance(env, list):\n env = salt.utils.data.repack_dictlist(env)\n if not isinstance(env, dict):\n env = {}\n return env\n",
"def _check_cb(cb_):\n '''\n If the callback is None or is not callable, return a lambda that returns\n the value passed.\n '''\n if cb_ is not None:\n if hasattr(cb_, '__call__'):\n return cb_\n else:\n log.error('log_callback is not callable, ignoring')\n return lambda x: x\n",
"def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):\n '''\n If template is a valid template engine, process the cmd and cwd through\n that engine.\n '''\n if not template:\n return (cmd, cwd)\n\n # render the path as a template using path_template_engine as the engine\n if template not in salt.utils.templates.TEMPLATE_REGISTRY:\n raise CommandExecutionError(\n 'Attempted to render file paths with unavailable engine '\n '{0}'.format(template)\n )\n\n kwargs = {}\n kwargs['salt'] = __salt__\n if pillarenv is not None or pillar_override is not None:\n pillarenv = pillarenv or __opts__['pillarenv']\n kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override)\n else:\n kwargs['pillar'] = __pillar__\n kwargs['grains'] = __grains__\n kwargs['opts'] = __opts__\n kwargs['saltenv'] = saltenv\n\n def _render(contents):\n # write out path to temp file\n tmp_path_fn = salt.utils.files.mkstemp()\n with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:\n fp_.write(salt.utils.stringutils.to_str(contents))\n data = salt.utils.templates.TEMPLATE_REGISTRY[template](\n tmp_path_fn,\n to_str=True,\n **kwargs\n )\n salt.utils.files.safe_rm(tmp_path_fn)\n if not data['result']:\n # Failed to render the template\n raise CommandExecutionError(\n 'Failed to execute cmd with error: {0}'.format(\n data['data']\n )\n )\n else:\n return data['data']\n\n cmd = _render(cmd)\n cwd = _render(cwd)\n return (cmd, cwd)\n",
"def _check_loglevel(level='info'):\n '''\n Retrieve the level code for use in logging.Logger.log().\n '''\n try:\n level = level.lower()\n if level == 'quiet':\n return None\n else:\n return LOG_LEVELS[level]\n except (AttributeError, KeyError):\n log.error(\n 'Invalid output_loglevel \\'%s\\'. Valid levels are: %s. Falling '\n 'back to \\'info\\'.',\n level, ', '.join(sorted(LOG_LEVELS, reverse=True))\n )\n return LOG_LEVELS['info']\n",
"def _check_avail(cmd):\n '''\n Check to see if the given command can be run\n '''\n if isinstance(cmd, list):\n cmd = ' '.join([six.text_type(x) if not isinstance(x, six.string_types) else x\n for x in cmd])\n bret = True\n wret = False\n if __salt__['config.get']('cmd_blacklist_glob'):\n blist = __salt__['config.get']('cmd_blacklist_glob', [])\n for comp in blist:\n if fnmatch.fnmatch(cmd, comp):\n # BAD! you are blacklisted\n bret = False\n if __salt__['config.get']('cmd_whitelist_glob', []):\n blist = __salt__['config.get']('cmd_whitelist_glob', [])\n for comp in blist:\n if fnmatch.fnmatch(cmd, comp):\n # GOOD! You are whitelisted\n wret = True\n break\n else:\n # If no whitelist set then alls good!\n wret = True\n return bret and wret\n",
"def _is_valid_shell(shell):\n '''\n Attempts to search for valid shells on a system and\n see if a given shell is in the list\n '''\n if salt.utils.platform.is_windows():\n return True # Don't even try this for Windows\n shells = '/etc/shells'\n available_shells = []\n if os.path.exists(shells):\n try:\n with salt.utils.files.fopen(shells, 'r') as shell_fp:\n lines = [salt.utils.stringutils.to_unicode(x)\n for x in shell_fp.read().splitlines()]\n for line in lines:\n if line.startswith('#'):\n continue\n else:\n available_shells.append(line)\n except OSError:\n return True\n else:\n # No known method of determining available shells\n return None\n if shell in available_shells:\n return True\n else:\n return False\n",
"def _get_stripped(cmd):\n # Return stripped command string copies to improve logging.\n if isinstance(cmd, list):\n return [x.strip() if isinstance(x, six.string_types) else x for x in cmd]\n elif isinstance(cmd, six.string_types):\n return cmd.strip()\n else:\n return cmd\n"
] |
# -*- coding: utf-8 -*-
'''
A module for shelling out.
Keep in mind that this module is insecure, in that it can give whomever has
access to the master root execution access to all salt minions.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import functools
import glob
import logging
import os
import shutil
import subprocess
import sys
import time
import traceback
import fnmatch
import base64
import re
import tempfile
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.powershell
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.timed_subprocess
import salt.utils.user
import salt.utils.versions
import salt.utils.vt
import salt.utils.win_dacl
import salt.utils.win_reg
import salt.grains.extra
from salt.ext import six
from salt.exceptions import CommandExecutionError, TimedProcTimeoutError, \
SaltInvocationError
from salt.log import LOG_LEVELS
from salt.ext.six.moves import range, zip, map
# Only available on POSIX systems, nonfatal on windows
try:
import pwd
import grp
except ImportError:
pass
if salt.utils.platform.is_windows():
from salt.utils.win_runas import runas as win_runas
from salt.utils.win_functions import escape_argument as _cmd_quote
HAS_WIN_RUNAS = True
else:
from salt.ext.six.moves import shlex_quote as _cmd_quote
HAS_WIN_RUNAS = False
__proxyenabled__ = ['*']
# Define the module's virtual name
__virtualname__ = 'cmd'
# Set up logging
log = logging.getLogger(__name__)
DEFAULT_SHELL = salt.grains.extra.shell()['shell']
# Overwriting the cmd python module makes debugging modules with pdb a bit
# harder so lets do it this way instead.
def __virtual__():
return __virtualname__
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns
the value passed.
'''
if cb_ is not None:
if hasattr(cb_, '__call__'):
return cb_
else:
log.error('log_callback is not callable, ignoring')
return lambda x: x
def _python_shell_default(python_shell, __pub_jid):
'''
Set python_shell default based on remote execution and __opts__['cmd_safe']
'''
try:
# Default to python_shell=True when run directly from remote execution
# system. Cross-module calls won't have a jid.
if __pub_jid and python_shell is None:
return True
elif __opts__.get('cmd_safe', True) is False and python_shell is None:
# Override-switch for python_shell
return True
except NameError:
pass
return python_shell
def _chroot_pids(chroot):
pids = []
for root in glob.glob('/proc/[0-9]*/root'):
try:
link = os.path.realpath(root)
if link.startswith(chroot):
pids.append(int(os.path.basename(
os.path.dirname(root)
)))
except OSError:
pass
return pids
def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):
'''
If template is a valid template engine, process the cmd and cwd through
that engine.
'''
if not template:
return (cmd, cwd)
# render the path as a template using path_template_engine as the engine
if template not in salt.utils.templates.TEMPLATE_REGISTRY:
raise CommandExecutionError(
'Attempted to render file paths with unavailable engine '
'{0}'.format(template)
)
kwargs = {}
kwargs['salt'] = __salt__
if pillarenv is not None or pillar_override is not None:
pillarenv = pillarenv or __opts__['pillarenv']
kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override)
else:
kwargs['pillar'] = __pillar__
kwargs['grains'] = __grains__
kwargs['opts'] = __opts__
kwargs['saltenv'] = saltenv
def _render(contents):
# write out path to temp file
tmp_path_fn = salt.utils.files.mkstemp()
with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(contents))
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
tmp_path_fn,
to_str=True,
**kwargs
)
salt.utils.files.safe_rm(tmp_path_fn)
if not data['result']:
# Failed to render the template
raise CommandExecutionError(
'Failed to execute cmd with error: {0}'.format(
data['data']
)
)
else:
return data['data']
cmd = _render(cmd)
cwd = _render(cwd)
return (cmd, cwd)
def _check_loglevel(level='info'):
'''
Retrieve the level code for use in logging.Logger.log().
'''
try:
level = level.lower()
if level == 'quiet':
return None
else:
return LOG_LEVELS[level]
except (AttributeError, KeyError):
log.error(
'Invalid output_loglevel \'%s\'. Valid levels are: %s. Falling '
'back to \'info\'.',
level, ', '.join(sorted(LOG_LEVELS, reverse=True))
)
return LOG_LEVELS['info']
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
return env
def _gather_pillar(pillarenv, pillar_override):
'''
Whenever a state run starts, gather the pillar data fresh
'''
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
pillar_override=pillar_override,
pillarenv=pillarenv
)
ret = pillar.compile_pillar()
if pillar_override and isinstance(pillar_override, dict):
ret.update(pillar_override)
return ret
def _check_avail(cmd):
'''
Check to see if the given command can be run
'''
if isinstance(cmd, list):
cmd = ' '.join([six.text_type(x) if not isinstance(x, six.string_types) else x
for x in cmd])
bret = True
wret = False
if __salt__['config.get']('cmd_blacklist_glob'):
blist = __salt__['config.get']('cmd_blacklist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# BAD! you are blacklisted
bret = False
if __salt__['config.get']('cmd_whitelist_glob', []):
blist = __salt__['config.get']('cmd_whitelist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# GOOD! You are whitelisted
wret = True
break
else:
# If no whitelist set then alls good!
wret = True
return bret and wret
def _run_quiet(cmd,
cwd=None,
stdin=None,
output_encoding=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)['stdout']
def _run_all_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
output_encoding=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup.
Returns a dict of return data.
output_loglevel argument is ignored. This is here for when we alias
cmd.run_all directly to _run_all_quiet in certain chicken-and-egg
situations where modules need to work both before and after
the __salt__ dictionary is populated (cf dracr.py)
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)
def run(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
encoded_cmd=False,
raise_err=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
Execute the passed command and return the output as a string
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run 'echo '\''h=\"baz\"'\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If ``False``, let python handle the positional
arguments. Set to ``True`` to use shell features, such as pipes or
redirection.
:param bool bg: If ``True``, run command in background and do not await or
deliver it's results
.. versionadded:: 2016.3.0
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
:param bool raise_err: If ``True`` and the command has a nonzero exit code,
a CommandExecutionError exception will be raised.
.. warning::
This function does not process commands through a shell
unless the python_shell flag is set to True. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or
have the python_shell=True flag set here.
The use of python_shell=True means that the shell will accept _any_ input
including potentially malicious commands such as 'good_command;rm -rf /'.
Be absolutely certain that you have sanitized your input prior to using
python_shell=True
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run cmd='sed -e s/=/:/g'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
log_callback = _check_cb(log_callback)
lvl = _check_loglevel(output_loglevel)
if lvl is not None:
if not ignore_retcode and ret['retcode'] != 0:
if lvl < LOG_LEVELS['error']:
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if raise_err:
raise CommandExecutionError(
log_callback(ret['stdout'] if not hide_output else '')
)
log.log(lvl, 'output: %s', log_callback(ret['stdout']))
return ret['stdout'] if not hide_output else ''
def shell(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return the output as a string.
.. versionadded:: 2015.5.0
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.shell 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param int shell: Shell to execute under. Defaults to the system default
shell.
:param bool bg: If True, run command in background and do not await or
deliver its results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.shell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
.. warning::
This passes the cmd argument directly to the shell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.shell "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.shell template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.shell "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.shell "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.shell cmd='sed -e s/=/:/g'
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
return run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
def run_stdout(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command, and only return the standard out
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stdout 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stdout template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stdout "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stdout'] if not hide_output else ''
def run_stderr(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command and only return the standard error
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stderr 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stderr 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stderr "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stderr template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stderr "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stderr'] if not hide_output else ''
def run_all(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
redirect_stderr=False,
password=None,
encoded_cmd=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return a dict of return data
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_all 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
.. versionadded:: 2018.3.0
:param bool redirect_stderr: If set to ``True``, then stderr will be
redirected to stdout. This is helpful for cases where obtaining both
the retcode and output is desired, but it is not desired to have the
output separated into both stdout and stderr.
.. versionadded:: 2015.8.2
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param bool bg: If ``True``, run command in background and do not await or
deliver its results
.. versionadded:: 2016.3.6
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_all "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_all template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_all "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=stderr,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def retcode(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a shell command and return the command's return code.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.retcode 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.retcode 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:rtype: int
:rtype: None
:returns: Return Code as an int or None if there was an exception.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.retcode "file /bin/bash"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.retcode template=jinja "file {{grains.pythonpath[0]}}/python"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.retcode "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['retcode']
def _retcode_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Helper for running commands quietly for minion startup. Returns same as
the retcode() function.
'''
return retcode(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stderr,
success_stderr=success_stderr,
**kwargs)
def script(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
saltenv='base',
use_vt=False,
bg=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
.. code-block:: bash
salt myminion cmd.script salt://foo.sh "arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param bool bg: If True, run script in background and do not await or
deliver it's results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh
salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
def _cleanup_tempfile(path):
try:
__salt__['file.remove'](path)
except (SaltInvocationError, CommandExecutionError) as exc:
log.error(
'cmd.script: Unable to clean tempfile \'%s\': %s',
path, exc, exc_info_on_loglevel=logging.DEBUG
)
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
win_cwd = False
if salt.utils.platform.is_windows() and runas and cwd is None:
# Create a temp working directory
cwd = tempfile.mkdtemp(dir=__opts__['cachedir'])
win_cwd = True
salt.utils.win_dacl.set_permissions(obj_name=cwd,
principal=runas,
permissions='full_control')
path = salt.utils.files.mkstemp(dir=cwd, suffix=os.path.splitext(source)[1])
if template:
if 'pillarenv' in kwargs or 'pillar' in kwargs:
pillarenv = kwargs.get('pillarenv', __opts__.get('pillarenv'))
kwargs['pillar'] = _gather_pillar(pillarenv, kwargs.get('pillar'))
fn_ = __salt__['cp.get_template'](source,
path,
template,
saltenv,
**kwargs)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
else:
fn_ = __salt__['cp.cache_file'](source, saltenv)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
shutil.copyfile(fn_, path)
if not salt.utils.platform.is_windows():
os.chmod(path, 320)
os.chown(path, __salt__['file.user_to_uid'](runas), -1)
if salt.utils.platform.is_windows() and shell.lower() != 'powershell':
cmd_path = _cmd_quote(path, escape=False)
else:
cmd_path = _cmd_quote(path)
ret = _run(cmd_path + ' ' + six.text_type(args) if args else cmd_path,
cwd=cwd,
stdin=stdin,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def script_retcode(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template='jinja',
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
output_encoding=None,
output_loglevel='debug',
log_callback=None,
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
The script can also be formatted as a template, the default is jinja.
Only evaluate the script return code and do not block for terminal output
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
"arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script_retcode 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh
salt '*' cmd.script_retcode salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script_retcode salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
return script(source=source,
args=args,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)['retcode']
def which(cmd):
'''
Returns the path of an executable available on the minion, None otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.which cat
'''
return salt.utils.path.which(cmd)
def which_bin(cmds):
'''
Returns the first command found in a list of commands
CLI Example:
.. code-block:: bash
salt '*' cmd.which_bin '[pip2, pip, pip-python]'
'''
return salt.utils.path.which_bin(cmds)
def has_exec(cmd):
'''
Returns true if the executable is available on the minion, false otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.has_exec cat
'''
return which(cmd) is not None
def exec_code(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. The stdout will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code ruby 'puts "cheese"'
salt '*' cmd.exec_code ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
return exec_code_all(lang, code, cwd, args, **kwargs)['stdout']
def exec_code_all(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid)
will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code_all ruby 'puts "cheese"'
salt '*' cmd.exec_code_all ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
powershell = lang.lower().startswith("powershell")
if powershell:
codefile = salt.utils.files.mkstemp(suffix=".ps1")
else:
codefile = salt.utils.files.mkstemp()
with salt.utils.files.fopen(codefile, 'w+t', binary=False) as fp_:
fp_.write(salt.utils.stringutils.to_str(code))
if powershell:
cmd = [lang, "-File", codefile]
else:
cmd = [lang, codefile]
if isinstance(args, six.string_types):
cmd.append(args)
elif isinstance(args, list):
cmd += args
ret = run_all(cmd, cwd=cwd, python_shell=False, **kwargs)
os.remove(codefile)
return ret
def tty(device, echo=''):
'''
Echo a string to a specific tty
CLI Example:
.. code-block:: bash
salt '*' cmd.tty tty0 'This is a test'
salt '*' cmd.tty pts3 'This is a test'
'''
if device.startswith('tty'):
teletype = '/dev/{0}'.format(device)
elif device.startswith('pts'):
teletype = '/dev/{0}'.format(device.replace('pts', 'pts/'))
else:
return {'Error': 'The specified device is not a valid TTY'}
try:
with salt.utils.files.fopen(teletype, 'wb') as tty_device:
tty_device.write(salt.utils.stringutils.to_bytes(echo))
return {
'Success': 'Message was successfully echoed to {0}'.format(teletype)
}
except IOError:
return {
'Error': 'Echoing to {0} returned error'.format(teletype)
}
def run_chroot(root,
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=True,
binds=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='quiet',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
.. versionadded:: 2014.7.0
This function runs :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` wrapped
within a chroot, with dev and proc mounted in the chroot
:param str root: Path to the root of the jail to use.
:param str stdin: A string of standard input can be specified for
the command to be run using the ``stdin`` parameter. This can
be useful in cases where sensitive information must be read
from standard input.:
:param str runas: User to run script as.
:param str group: Group to run script as.
:param str shell: Shell to execute under. Defaults to the system
default shell.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:parar str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param list binds: List of directories that will be exported inside
the chroot with the bind option.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_chroot 'some command' env='{"FOO": "bar"}'
:param dict clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output
before it is returned.
:param str umask: The umask (in octal) to use when running the
command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout:
A timeout in seconds for the executed process to return.
:param bool use_vt:
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs. This is experimental.
:param success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' cmd.run_chroot /var/lib/lxc/container_name/rootfs 'sh /tmp/bootstrap.sh'
'''
__salt__['mount.mount'](
os.path.join(root, 'dev'),
'devtmpfs',
fstype='devtmpfs')
__salt__['mount.mount'](
os.path.join(root, 'proc'),
'proc',
fstype='proc')
__salt__['mount.mount'](
os.path.join(root, 'sys'),
'sysfs',
fstype='sysfs')
binds = binds if binds else []
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.mount'](
bind_exported_to,
bind_exported,
opts='default,bind')
# Execute chroot routine
sh_ = '/bin/sh'
if os.path.isfile(os.path.join(root, 'bin/bash')):
sh_ = '/bin/bash'
if isinstance(cmd, (list, tuple)):
cmd = ' '.join([six.text_type(i) for i in cmd])
cmd = 'chroot {0} {1} -c {2}'.format(root, sh_, _cmd_quote(cmd))
run_func = __context__.pop('cmd.run_chroot.func', run_all)
ret = run_func(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
pillarenv=kwargs.get('pillarenv'),
pillar=kwargs.get('pillar'),
use_vt=use_vt,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
bg=bg)
# Kill processes running in the chroot
for i in range(6):
pids = _chroot_pids(root)
if not pids:
break
for pid in pids:
# use sig 15 (TERM) for first 3 attempts, then 9 (KILL)
sig = 15 if i < 3 else 9
os.kill(pid, sig)
if _chroot_pids(root):
log.error('Processes running in chroot could not be killed, '
'filesystem will remain mounted')
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.umount'](bind_exported_to)
__salt__['mount.umount'](os.path.join(root, 'sys'))
__salt__['mount.umount'](os.path.join(root, 'proc'))
__salt__['mount.umount'](os.path.join(root, 'dev'))
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def _is_valid_shell(shell):
'''
Attempts to search for valid shells on a system and
see if a given shell is in the list
'''
if salt.utils.platform.is_windows():
return True # Don't even try this for Windows
shells = '/etc/shells'
available_shells = []
if os.path.exists(shells):
try:
with salt.utils.files.fopen(shells, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
if line.startswith('#'):
continue
else:
available_shells.append(line)
except OSError:
return True
else:
# No known method of determining available shells
return None
if shell in available_shells:
return True
else:
return False
def shells():
'''
Lists the valid shells on this system via the /etc/shells file
.. versionadded:: 2015.5.0
CLI Example::
salt '*' cmd.shells
'''
shells_fn = '/etc/shells'
ret = []
if os.path.exists(shells_fn):
try:
with salt.utils.files.fopen(shells_fn, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
line = line.strip()
if line.startswith('#'):
continue
elif not line:
continue
else:
ret.append(line)
except OSError:
log.error("File '%s' was not found", shells_fn)
return ret
def shell_info(shell, list_modules=False):
'''
.. versionadded:: 2016.11.0
Provides information about a shell or script languages which often use
``#!``. The values returned are dependent on the shell or scripting
languages all return the ``installed``, ``path``, ``version``,
``version_raw``
Args:
shell (str): Name of the shell. Support shells/script languages include
bash, cmd, perl, php, powershell, python, ruby and zsh
list_modules (bool): True to list modules available to the shell.
Currently only lists powershell modules.
Returns:
dict: A dictionary of information about the shell
.. code-block:: python
{'version': '<2 or 3 numeric components dot-separated>',
'version_raw': '<full version string>',
'path': '<full path to binary>',
'installed': <True, False or None>,
'<attribute>': '<attribute value>'}
.. note::
- ``installed`` is always returned, if ``None`` or ``False`` also
returns error and may also return ``stdout`` for diagnostics.
- ``version`` is for use in determine if a shell/script language has a
particular feature set, not for package management.
- The shell must be within the executable search path.
CLI Example:
.. code-block:: bash
salt '*' cmd.shell_info bash
salt '*' cmd.shell_info powershell
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
regex_shells = {
'bash': [r'version (\d\S*)', 'bash', '--version'],
'bash-test-error': [r'versioZ ([-\w.]+)', 'bash', '--version'], # used to test an error result
'bash-test-env': [r'(HOME=.*)', 'bash', '-c', 'declare'], # used to test an error result
'zsh': [r'^zsh (\d\S*)', 'zsh', '--version'],
'tcsh': [r'^tcsh (\d\S*)', 'tcsh', '--version'],
'cmd': [r'Version ([\d.]+)', 'cmd.exe', '/C', 'ver'],
'powershell': [r'PSVersion\s+(\d\S*)', 'powershell', '-NonInteractive', '$PSVersionTable'],
'perl': [r'^(\d\S*)', 'perl', '-e', 'printf "%vd\n", $^V;'],
'python': [r'^Python (\d\S*)', 'python', '-V'],
'ruby': [r'^ruby (\d\S*)', 'ruby', '-v'],
'php': [r'^PHP (\d\S*)', 'php', '-v']
}
# Ensure ret['installed'] always as a value of True, False or None (not sure)
ret = {'installed': False}
if salt.utils.platform.is_windows() and shell == 'powershell':
pw_keys = salt.utils.win_reg.list_keys(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell')
pw_keys.sort(key=int)
if not pw_keys:
return {
'error': 'Unable to locate \'powershell\' Reason: Cannot be '
'found in registry.',
'installed': False,
}
for reg_ver in pw_keys:
install_data = salt.utils.win_reg.read_value(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}'.format(reg_ver),
vname='Install')
if install_data.get('vtype') == 'REG_DWORD' and \
install_data.get('vdata') == 1:
details = salt.utils.win_reg.list_values(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}\\'
'PowerShellEngine'.format(reg_ver))
# reset data, want the newest version details only as powershell
# is backwards compatible
ret = {}
# if all goes well this will become True
ret['installed'] = None
ret['path'] = which('powershell.exe')
for attribute in details:
if attribute['vname'].lower() == '(default)':
continue
elif attribute['vname'].lower() == 'powershellversion':
ret['psversion'] = attribute['vdata']
ret['version_raw'] = attribute['vdata']
elif attribute['vname'].lower() == 'runtimeversion':
ret['crlversion'] = attribute['vdata']
if ret['crlversion'][0].lower() == 'v':
ret['crlversion'] = ret['crlversion'][1::]
elif attribute['vname'].lower() == 'pscompatibleversion':
# reg attribute does not end in s, the powershell
# attribute does
ret['pscompatibleversions'] = \
attribute['vdata'].replace(' ', '').split(',')
else:
# keys are lower case as python is case sensitive the
# registry is not
ret[attribute['vname'].lower()] = attribute['vdata']
else:
if shell not in regex_shells:
return {
'error': 'Salt does not know how to get the version number for '
'{0}'.format(shell),
'installed': None
}
shell_data = regex_shells[shell]
pattern = shell_data.pop(0)
# We need to make sure HOME set, so shells work correctly
# salt-call will general have home set, the salt-minion service may not
# We need to assume ports of unix shells to windows will look after
# themselves in setting HOME as they do it in many different ways
newenv = os.environ
if ('HOME' not in newenv) and (not salt.utils.platform.is_windows()):
newenv['HOME'] = os.path.expanduser('~')
log.debug('HOME environment set to %s', newenv['HOME'])
try:
proc = salt.utils.timed_subprocess.TimedProc(
shell_data,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=10,
env=newenv
)
except (OSError, IOError) as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: {1}'.format(' '.join(shell_data), exc),
'installed': False,
}
try:
proc.run()
except TimedProcTimeoutError as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: Timed out.'.format(' '.join(shell_data)),
'installed': False,
}
ret['path'] = which(shell_data[0])
pattern_result = re.search(pattern, proc.stdout, flags=re.IGNORECASE)
# only set version if we find it, so code later on can deal with it
if pattern_result:
ret['version_raw'] = pattern_result.group(1)
if 'version_raw' in ret:
version_results = re.match(r'(\d[\d.]*)', ret['version_raw'])
if version_results:
ret['installed'] = True
ver_list = version_results.group(1).split('.')[:3]
if len(ver_list) == 1:
ver_list.append('0')
ret['version'] = '.'.join(ver_list[:3])
else:
ret['installed'] = None # Have an unexpected result
# Get a list of the PowerShell modules which are potentially available
# to be imported
if shell == 'powershell' and ret['installed'] and list_modules:
ret['modules'] = salt.utils.powershell.get_modules()
if 'version' not in ret:
ret['error'] = 'The version regex pattern for shell {0}, could not ' \
'find the version string'.format(shell)
ret['stdout'] = proc.stdout # include stdout so they can see the issue
log.error(ret['error'])
return ret
def powershell(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return the output as a dictionary.
Other ``cmd.*`` functions (besides ``cmd.powershell_all``)
return the raw text output of the command. This
function appends ``| ConvertTo-JSON`` to the command and then parses the
JSON into a Python dictionary. If you want the raw textual result of your
PowerShell command you should use ``cmd.run`` with the ``shell=powershell``
option.
For example:
.. code-block:: bash
salt '*' cmd.run '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2016.3.0
.. warning::
This passes the cmd argument directly to PowerShell
without any further processing! Be absolutely sure that you
have properly sanitized the command passed to this function
and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in cases
where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
.. versionadded:: 2016.3.4
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:returns:
:dict: A dictionary of data returned by the powershell command.
CLI Example:
.. code-block:: powershell
salt '*' cmd.powershell "$PSVersionTable.CLRVersion"
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
# ConvertTo-JSON is only available on PowerShell 3.0 and later
psversion = shell_info('powershell')['psversion']
if salt.utils.versions.version_cmp(psversion, '2.0') == 1:
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Put the whole command inside a try / catch block
# Some errors in PowerShell are not "Terminating Errors" and will not be
# caught in a try/catch block. For example, the `Get-WmiObject` command will
# often return a "Non Terminating Error". To fix this, make sure
# `-ErrorAction Stop` is set in the powershell command
cmd = 'try {' + cmd + '} catch { "{}" }'
# Retrieve the response, while overriding shell with 'powershell'
response = run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
try:
return salt.utils.json.loads(response)
except Exception:
log.error("Error converting PowerShell JSON return", exc_info=True)
return {}
def powershell_all(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
quiet=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
force_list=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return a dictionary with a result
field representing the output of the command, as well as other fields
showing us what the PowerShell invocation wrote to ``stderr``, the process
id, and the exit code of the invocation.
This function appends ``| ConvertTo-JSON`` to the command before actually
invoking powershell.
An unquoted empty string is not valid JSON, but it's very normal for the
Powershell output to be exactly that. Therefore, we do not attempt to parse
empty Powershell output (which would result in an exception). Instead we
treat this as a special case and one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field of the return dictionary will be an empty list.
- If the value of the ``force_list`` parameter is ``False``, then the
return dictionary **will not have a result key added to it**. We aren't
setting ``result`` to ``None`` in this case, because ``None`` is the
Python representation of "null" in JSON. (We likewise can't use ``False``
for the equivalent reason.)
If Powershell's output is not an empty string and Python cannot parse its
content, then a ``CommandExecutionError`` exception will be raised.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is other than ``list``
then one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field will be a singleton list with the Python object as its
sole member.
- If the value of the ``force_list`` parameter is ``False``, then the value
of ``result`` will be the unmodified Python object.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is ``list``, then the
value of ``result`` will be the unmodified Python object. The
``force_list`` parameter has no effect in this case.
.. note::
An example of why the ``force_list`` parameter is useful is as
follows: The Powershell command ``dir x | Convert-ToJson`` results in
- no output when x is an empty directory.
- a dictionary object when x contains just one item.
- a list of dictionary objects when x contains multiple items.
By setting ``force_list`` to ``True`` we will always end up with a
list of dictionary items, representing files, no matter how many files
x contains. Conversely, if ``force_list`` is ``False``, we will end
up with no ``result`` key in our return dictionary when x is an empty
directory, and a dictionary object when x contains just one file.
If you want a similar function but with a raw textual result instead of a
Python dictionary, you should use ``cmd.run_all`` in combination with
``shell=powershell``.
The remaining fields in the return dictionary are described in more detail
in the ``Returns`` section.
Example:
.. code-block:: bash
salt '*' cmd.run_all '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run_all 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2018.3.0
.. warning::
This passes the cmd argument directly to PowerShell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param bool force_list: The purpose of this parameter is described in the
preamble of this function's documentation. Default value is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:return: A dictionary with the following entries:
result
For a complete description of this field, please refer to this
function's preamble. **This key will not be added to the dictionary
when force_list is False and Powershell's output is the empty
string.**
stderr
What the PowerShell invocation wrote to ``stderr``.
pid
The process id of the PowerShell invocation
retcode
This is the exit code of the invocation of PowerShell.
If the final execution status (in PowerShell) of our command
(with ``| ConvertTo-JSON`` appended) is ``False`` this should be non-0.
Likewise if PowerShell exited with ``$LASTEXITCODE`` set to some
non-0 value, then ``retcode`` will end up with this value.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "$PSVersionTable.CLRVersion"
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "dir mydirectory" force_list=True
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Retrieve the response, while overriding shell with 'powershell'
response = run_all(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
quiet=quiet,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
stdoutput = response['stdout']
# if stdoutput is the empty string and force_list is True we return an empty list
# Otherwise we return response with no result key
if not stdoutput:
response.pop('stdout')
if force_list:
response['result'] = []
return response
# If we fail to parse stdoutput we will raise an exception
try:
result = salt.utils.json.loads(stdoutput)
except Exception:
err_msg = "cmd.powershell_all " + \
"cannot parse the Powershell output."
response["cmd"] = cmd
raise CommandExecutionError(
message=err_msg,
info=response
)
response.pop("stdout")
if type(result) is not list:
if force_list:
response['result'] = [result]
else:
response['result'] = result
else:
# result type is list so the force_list param has no effect
response['result'] = result
return response
def run_bg(cmd,
cwd=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
timeout=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
.. versionadded: 2016.3.0
Execute the passed command in the background and return it's PID
.. note::
If the init system is systemd and the backgrounded task should run even
if the salt-minion process is restarted, prepend ``systemd-run
--scope`` to the command. This will reparent the process in its own
scope separate from salt-minion, and will not be affected by restarting
the minion service.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Shell to execute under. Defaults to the system default
shell.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_bg 'echo '\''h=\"baz\"'\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_bg 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param int timeout: A timeout in seconds for the executed process to return.
.. warning::
This function does not process commands through a shell unless the
``python_shell`` argument is set to ``True``. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or have the
python_shell=True flag set here.
The use of ``python_shell=True`` means that the shell will accept _any_
input including potentially malicious commands such as 'good_command;rm
-rf /'. Be absolutely certain that you have sanitized your input prior
to using ``python_shell=True``.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_bg "fstrim-all"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_bg template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run_bg "Get-ChildItem C:\\ " shell='powershell'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run_bg cmd='ls -lR / | sed -e s/=/:/g > /tmp/dontwait'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
res = _run(cmd,
stdin=None,
stderr=None,
stdout=None,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
use_vt=None,
bg=True,
with_communicate=False,
rstrip=False,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
umask=umask,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs
)
return {
'pid': res['pid']
}
|
saltstack/salt
|
salt/modules/cmdmod.py
|
_run_quiet
|
python
|
def _run_quiet(cmd,
cwd=None,
stdin=None,
output_encoding=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)['stdout']
|
Helper for running commands quietly for minion startup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cmdmod.py#L861-L902
| null |
# -*- coding: utf-8 -*-
'''
A module for shelling out.
Keep in mind that this module is insecure, in that it can give whomever has
access to the master root execution access to all salt minions.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import functools
import glob
import logging
import os
import shutil
import subprocess
import sys
import time
import traceback
import fnmatch
import base64
import re
import tempfile
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.powershell
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.timed_subprocess
import salt.utils.user
import salt.utils.versions
import salt.utils.vt
import salt.utils.win_dacl
import salt.utils.win_reg
import salt.grains.extra
from salt.ext import six
from salt.exceptions import CommandExecutionError, TimedProcTimeoutError, \
SaltInvocationError
from salt.log import LOG_LEVELS
from salt.ext.six.moves import range, zip, map
# Only available on POSIX systems, nonfatal on windows
try:
import pwd
import grp
except ImportError:
pass
if salt.utils.platform.is_windows():
from salt.utils.win_runas import runas as win_runas
from salt.utils.win_functions import escape_argument as _cmd_quote
HAS_WIN_RUNAS = True
else:
from salt.ext.six.moves import shlex_quote as _cmd_quote
HAS_WIN_RUNAS = False
__proxyenabled__ = ['*']
# Define the module's virtual name
__virtualname__ = 'cmd'
# Set up logging
log = logging.getLogger(__name__)
DEFAULT_SHELL = salt.grains.extra.shell()['shell']
# Overwriting the cmd python module makes debugging modules with pdb a bit
# harder so lets do it this way instead.
def __virtual__():
return __virtualname__
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns
the value passed.
'''
if cb_ is not None:
if hasattr(cb_, '__call__'):
return cb_
else:
log.error('log_callback is not callable, ignoring')
return lambda x: x
def _python_shell_default(python_shell, __pub_jid):
'''
Set python_shell default based on remote execution and __opts__['cmd_safe']
'''
try:
# Default to python_shell=True when run directly from remote execution
# system. Cross-module calls won't have a jid.
if __pub_jid and python_shell is None:
return True
elif __opts__.get('cmd_safe', True) is False and python_shell is None:
# Override-switch for python_shell
return True
except NameError:
pass
return python_shell
def _chroot_pids(chroot):
pids = []
for root in glob.glob('/proc/[0-9]*/root'):
try:
link = os.path.realpath(root)
if link.startswith(chroot):
pids.append(int(os.path.basename(
os.path.dirname(root)
)))
except OSError:
pass
return pids
def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):
'''
If template is a valid template engine, process the cmd and cwd through
that engine.
'''
if not template:
return (cmd, cwd)
# render the path as a template using path_template_engine as the engine
if template not in salt.utils.templates.TEMPLATE_REGISTRY:
raise CommandExecutionError(
'Attempted to render file paths with unavailable engine '
'{0}'.format(template)
)
kwargs = {}
kwargs['salt'] = __salt__
if pillarenv is not None or pillar_override is not None:
pillarenv = pillarenv or __opts__['pillarenv']
kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override)
else:
kwargs['pillar'] = __pillar__
kwargs['grains'] = __grains__
kwargs['opts'] = __opts__
kwargs['saltenv'] = saltenv
def _render(contents):
# write out path to temp file
tmp_path_fn = salt.utils.files.mkstemp()
with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(contents))
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
tmp_path_fn,
to_str=True,
**kwargs
)
salt.utils.files.safe_rm(tmp_path_fn)
if not data['result']:
# Failed to render the template
raise CommandExecutionError(
'Failed to execute cmd with error: {0}'.format(
data['data']
)
)
else:
return data['data']
cmd = _render(cmd)
cwd = _render(cwd)
return (cmd, cwd)
def _check_loglevel(level='info'):
'''
Retrieve the level code for use in logging.Logger.log().
'''
try:
level = level.lower()
if level == 'quiet':
return None
else:
return LOG_LEVELS[level]
except (AttributeError, KeyError):
log.error(
'Invalid output_loglevel \'%s\'. Valid levels are: %s. Falling '
'back to \'info\'.',
level, ', '.join(sorted(LOG_LEVELS, reverse=True))
)
return LOG_LEVELS['info']
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
return env
def _gather_pillar(pillarenv, pillar_override):
'''
Whenever a state run starts, gather the pillar data fresh
'''
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
pillar_override=pillar_override,
pillarenv=pillarenv
)
ret = pillar.compile_pillar()
if pillar_override and isinstance(pillar_override, dict):
ret.update(pillar_override)
return ret
def _check_avail(cmd):
'''
Check to see if the given command can be run
'''
if isinstance(cmd, list):
cmd = ' '.join([six.text_type(x) if not isinstance(x, six.string_types) else x
for x in cmd])
bret = True
wret = False
if __salt__['config.get']('cmd_blacklist_glob'):
blist = __salt__['config.get']('cmd_blacklist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# BAD! you are blacklisted
bret = False
if __salt__['config.get']('cmd_whitelist_glob', []):
blist = __salt__['config.get']('cmd_whitelist_glob', [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# GOOD! You are whitelisted
wret = True
break
else:
# If no whitelist set then alls good!
wret = True
return bret and wret
def _run(cmd,
cwd=None,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
prepend_path=None,
rstrip=True,
template=None,
umask=None,
timeout=None,
with_communicate=True,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
pillarenv=None,
pillar_override=None,
use_vt=False,
password=None,
bg=False,
encoded_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Do the DRY thing and only call subprocess.Popen() once
'''
if 'pillar' in kwargs and not pillar_override:
pillar_override = kwargs['pillar']
if output_loglevel != 'quiet' and _is_valid_shell(shell) is False:
log.warning(
'Attempt to run a shell command with what may be an invalid shell! '
'Check to ensure that the shell <%s> is valid for this user.',
shell
)
output_loglevel = _check_loglevel(output_loglevel)
log_callback = _check_cb(log_callback)
use_sudo = False
if runas is None and '__context__' in globals():
runas = __context__.get('runas')
if password is None and '__context__' in globals():
password = __context__.get('runas_password')
# Set the default working directory to the home directory of the user
# salt-minion is running as. Defaults to home directory of user under which
# the minion is running.
if not cwd:
cwd = os.path.expanduser('~{0}'.format('' if not runas else runas))
# make sure we can access the cwd
# when run from sudo or another environment where the euid is
# changed ~ will expand to the home of the original uid and
# the euid might not have access to it. See issue #1844
if not os.access(cwd, os.R_OK):
cwd = '/'
if salt.utils.platform.is_windows():
cwd = os.path.abspath(os.sep)
else:
# Handle edge cases where numeric/other input is entered, and would be
# yaml-ified into non-string types
cwd = six.text_type(cwd)
if bg:
ignore_retcode = True
use_vt = False
if not salt.utils.platform.is_windows():
if not os.path.isfile(shell) or not os.access(shell, os.X_OK):
msg = 'The shell {0} is not available'.format(shell)
raise CommandExecutionError(msg)
if salt.utils.platform.is_windows() and use_vt: # Memozation so not much overhead
raise CommandExecutionError('VT not available on windows')
if shell.lower().strip() == 'powershell':
# Strip whitespace
if isinstance(cmd, six.string_types):
cmd = cmd.strip()
# If we were called by script(), then fakeout the Windows
# shell to run a Powershell script.
# Else just run a Powershell command.
stack = traceback.extract_stack(limit=2)
# extract_stack() returns a list of tuples.
# The last item in the list [-1] is the current method.
# The third item[2] in each tuple is the name of that method.
if stack[-2][2] == 'script':
cmd = 'Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -File ' + cmd
elif encoded_cmd:
cmd = 'Powershell -NonInteractive -EncodedCommand {0}'.format(cmd)
else:
cmd = 'Powershell -NonInteractive -NoProfile "{0}"'.format(cmd.replace('"', '\\"'))
# munge the cmd and cwd through the template
(cmd, cwd) = _render_cmd(cmd, cwd, template, saltenv, pillarenv, pillar_override)
ret = {}
# If the pub jid is here then this is a remote ex or salt call command and needs to be
# checked if blacklisted
if '__pub_jid' in kwargs:
if not _check_avail(cmd):
raise CommandExecutionError(
'The shell command "{0}" is not permitted'.format(cmd)
)
env = _parse_env(env)
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, six.string_types) else x for x in cmd]
elif isinstance(cmd, six.string_types):
return cmd.strip()
else:
return cmd
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' parameter.
msg = (
'Executing command {0}{1}{0} {2}{3}in directory \'{4}\'{5}'.format(
'\'' if not isinstance(cmd, list) else '',
_get_stripped(cmd),
'as user \'{0}\' '.format(runas) if runas else '',
'in group \'{0}\' '.format(group) if group else '',
cwd,
'. Executing command in the background, no output will be '
'logged.' if bg else ''
)
)
log.info(log_callback(msg))
if runas and salt.utils.platform.is_windows():
if not HAS_WIN_RUNAS:
msg = 'missing salt/utils/win_runas.py'
raise CommandExecutionError(msg)
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(cmd)
return win_runas(cmd, runas, password, cwd)
if runas and salt.utils.platform.is_darwin():
# we need to insert the user simulation into the command itself and not
# just run it from the environment on macOS as that
# method doesn't work properly when run as root for certain commands.
if isinstance(cmd, (list, tuple)):
cmd = ' '.join(map(_cmd_quote, cmd))
cmd = 'su -l {0} -c "cd {1}; {2}"'.format(runas, cwd, cmd)
# set runas to None, because if you try to run `su -l` as well as
# simulate the environment macOS will prompt for the password of the
# user and will cause salt to hang.
runas = None
if runas:
# Save the original command before munging it
try:
pwd.getpwnam(runas)
except KeyError:
raise CommandExecutionError(
'User \'{0}\' is not available'.format(runas)
)
if group:
if salt.utils.platform.is_windows():
msg = 'group is not currently available on Windows'
raise SaltInvocationError(msg)
if not which_bin(['sudo']):
msg = 'group argument requires sudo but not found'
raise CommandExecutionError(msg)
try:
grp.getgrnam(group)
except KeyError:
raise CommandExecutionError(
'Group \'{0}\' is not available'.format(runas)
)
else:
use_sudo = True
if runas or group:
try:
# Getting the environment for the runas user
# Use markers to thwart any stdout noise
# There must be a better way to do this.
import uuid
marker = '<<<' + str(uuid.uuid4()) + '>>>'
marker_b = marker.encode(__salt_system_encoding__)
py_code = (
'import sys, os, itertools; '
'sys.stdout.write(\"' + marker + '\"); '
'sys.stdout.write(\"\\0\".join(itertools.chain(*os.environ.items()))); '
'sys.stdout.write(\"' + marker + '\");'
)
if use_sudo or __grains__['os'] in ['MacOS', 'Darwin']:
env_cmd = ['sudo']
# runas is optional if use_sudo is set.
if runas:
env_cmd.extend(['-u', runas])
if group:
env_cmd.extend(['-g', group])
if shell != DEFAULT_SHELL:
env_cmd.extend(['-s', '--', shell, '-c'])
else:
env_cmd.extend(['-i', '--'])
env_cmd.extend([sys.executable])
elif __grains__['os'] in ['FreeBSD']:
env_cmd = ('su', '-', runas, '-c',
"{0} -c {1}".format(shell, sys.executable))
elif __grains__['os_family'] in ['Solaris']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
elif __grains__['os_family'] in ['AIX']:
env_cmd = ('su', '-', runas, '-c', sys.executable)
else:
env_cmd = ('su', '-s', shell, '-', runas, '-c', sys.executable)
msg = 'env command: {0}'.format(env_cmd)
log.debug(log_callback(msg))
env_bytes, env_encoded_err = subprocess.Popen(
env_cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
).communicate(salt.utils.stringutils.to_bytes(py_code))
marker_count = env_bytes.count(marker_b)
if marker_count == 0:
# Possibly PAM prevented the login
log.error(
'Environment could not be retrieved for user \'%s\': '
'stderr=%r stdout=%r',
runas, env_encoded_err, env_bytes
)
# Ensure that we get an empty env_runas dict below since we
# were not able to get the environment.
env_bytes = b''
elif marker_count != 2:
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\'',
info={'stderr': repr(env_encoded_err),
'stdout': repr(env_bytes)}
)
else:
# Strip the marker
env_bytes = env_bytes.split(marker_b)[1]
if six.PY2:
import itertools
env_runas = dict(itertools.izip(*[iter(env_bytes.split(b'\0'))]*2))
elif six.PY3:
env_runas = dict(list(zip(*[iter(env_bytes.split(b'\0'))]*2)))
env_runas = dict(
(salt.utils.stringutils.to_str(k),
salt.utils.stringutils.to_str(v))
for k, v in six.iteritems(env_runas)
)
env_runas.update(env)
# Fix platforms like Solaris that don't set a USER env var in the
# user's default environment as obtained above.
if env_runas.get('USER') != runas:
env_runas['USER'] = runas
# Fix some corner cases where shelling out to get the user's
# environment returns the wrong home directory.
runas_home = os.path.expanduser('~{0}'.format(runas))
if env_runas.get('HOME') != runas_home:
env_runas['HOME'] = runas_home
env = env_runas
except ValueError as exc:
log.exception('Error raised retrieving environment for user %s', runas)
raise CommandExecutionError(
'Environment could not be retrieved for user \'{0}\': {1}'.format(
runas, exc
)
)
if reset_system_locale is True:
if not salt.utils.platform.is_windows():
# Default to C!
# Salt only knows how to parse English words
# Don't override if the user has passed LC_ALL
env.setdefault('LC_CTYPE', 'C')
env.setdefault('LC_NUMERIC', 'C')
env.setdefault('LC_TIME', 'C')
env.setdefault('LC_COLLATE', 'C')
env.setdefault('LC_MONETARY', 'C')
env.setdefault('LC_MESSAGES', 'C')
env.setdefault('LC_PAPER', 'C')
env.setdefault('LC_NAME', 'C')
env.setdefault('LC_ADDRESS', 'C')
env.setdefault('LC_TELEPHONE', 'C')
env.setdefault('LC_MEASUREMENT', 'C')
env.setdefault('LC_IDENTIFICATION', 'C')
env.setdefault('LANGUAGE', 'C')
else:
# On Windows set the codepage to US English.
if python_shell:
cmd = 'chcp 437 > nul & ' + cmd
if clean_env:
run_env = env
else:
run_env = os.environ.copy()
run_env.update(env)
if prepend_path:
run_env['PATH'] = ':'.join((prepend_path, run_env['PATH']))
if python_shell is None:
python_shell = False
new_kwargs = {'cwd': cwd,
'shell': python_shell,
'env': run_env if six.PY3 else salt.utils.data.encode(run_env),
'stdin': six.text_type(stdin) if stdin is not None else stdin,
'stdout': stdout,
'stderr': stderr,
'with_communicate': with_communicate,
'timeout': timeout,
'bg': bg,
}
if 'stdin_raw_newlines' in kwargs:
new_kwargs['stdin_raw_newlines'] = kwargs['stdin_raw_newlines']
if umask is not None:
_umask = six.text_type(umask).lstrip('0')
if _umask == '':
msg = 'Zero umask is not allowed.'
raise CommandExecutionError(msg)
try:
_umask = int(_umask, 8)
except ValueError:
raise CommandExecutionError("Invalid umask: '{0}'".format(umask))
else:
_umask = None
if runas or group or umask:
new_kwargs['preexec_fn'] = functools.partial(
salt.utils.user.chugid_and_umask,
runas,
_umask,
group)
if not salt.utils.platform.is_windows():
# close_fds is not supported on Windows platforms if you redirect
# stdin/stdout/stderr
if new_kwargs['shell'] is True:
new_kwargs['executable'] = shell
new_kwargs['close_fds'] = True
if not os.path.isabs(cwd) or not os.path.isdir(cwd):
raise CommandExecutionError(
'Specified cwd \'{0}\' either not absolute or does not exist'
.format(cwd)
)
if python_shell is not True \
and not salt.utils.platform.is_windows() \
and not isinstance(cmd, list):
cmd = salt.utils.args.shlex_split(cmd)
if success_retcodes is None:
success_retcodes = [0]
else:
try:
success_retcodes = [int(i) for i in
salt.utils.args.split_input(
success_retcodes
)]
except ValueError:
raise SaltInvocationError(
'success_retcodes must be a list of integers'
)
if success_stdout is None:
success_stdout = []
else:
try:
success_stdout = [i for i in
salt.utils.args.split_input(
success_stdout
)]
except ValueError:
raise SaltInvocationError(
'success_stdout must be a list of integers'
)
if success_stderr is None:
success_stderr = []
else:
try:
success_stderr = [i for i in
salt.utils.args.split_input(
success_stderr
)]
except ValueError:
raise SaltInvocationError(
'success_stderr must be a list of integers'
)
if not use_vt:
# This is where the magic happens
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **new_kwargs)
except (OSError, IOError) as exc:
msg = (
'Unable to run command \'{0}\' with the context \'{1}\', '
'reason: {2}'.format(
cmd if output_loglevel is not None else 'REDACTED',
new_kwargs,
exc
)
)
raise CommandExecutionError(msg)
try:
proc.run()
except TimedProcTimeoutError as exc:
ret['stdout'] = six.text_type(exc)
ret['stderr'] = ''
ret['retcode'] = None
ret['pid'] = proc.process.pid
# ok return code for timeouts?
ret['retcode'] = 1
return ret
if output_loglevel != 'quiet' and output_encoding is not None:
log.debug('Decoding output from command %s using %s encoding',
cmd, output_encoding)
try:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding)
except TypeError:
# stdout is None
out = ''
except UnicodeDecodeError:
out = salt.utils.stringutils.to_unicode(
proc.stdout,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', cmd
)
try:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding)
except TypeError:
# stderr is None
err = ''
except UnicodeDecodeError:
err = salt.utils.stringutils.to_unicode(
proc.stderr,
encoding=output_encoding,
errors='replace')
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', cmd
)
if rstrip:
if out is not None:
out = out.rstrip()
if err is not None:
err = err.rstrip()
ret['pid'] = proc.process.pid
ret['retcode'] = proc.process.returncode
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
ret['stdout'] = out
ret['stderr'] = err
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
else:
formatted_timeout = ''
if timeout:
formatted_timeout = ' (timeout: {0}s)'.format(timeout)
if output_loglevel is not None:
msg = 'Running {0} in VT{1}'.format(cmd, formatted_timeout)
log.debug(log_callback(msg))
stdout, stderr = '', ''
now = time.time()
if timeout:
will_timeout = now + timeout
else:
will_timeout = -1
try:
proc = salt.utils.vt.Terminal(
cmd,
shell=True,
log_stdout=True,
log_stderr=True,
cwd=cwd,
preexec_fn=new_kwargs.get('preexec_fn', None),
env=run_env,
log_stdin_level=output_loglevel,
log_stdout_level=output_loglevel,
log_stderr_level=output_loglevel,
stream_stdout=True,
stream_stderr=True
)
ret['pid'] = proc.pid
while proc.has_unread_data:
try:
try:
time.sleep(0.5)
try:
cstdout, cstderr = proc.recv()
except IOError:
cstdout, cstderr = '', ''
if cstdout:
stdout += cstdout
else:
cstdout = ''
if cstderr:
stderr += cstderr
else:
cstderr = ''
if timeout and (time.time() > will_timeout):
ret['stderr'] = (
'SALT: Timeout after {0}s\n{1}').format(
timeout, stderr)
ret['retcode'] = None
break
except KeyboardInterrupt:
ret['stderr'] = 'SALT: User break\n{0}'.format(stderr)
ret['retcode'] = 1
break
except salt.utils.vt.TerminalException as exc:
log.error('VT: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
ret = {'retcode': 1, 'pid': '2'}
break
# only set stdout on success as we already mangled in other
# cases
ret['stdout'] = stdout
if not proc.isalive():
# Process terminated, i.e., not canceled by the user or by
# the timeout
ret['stderr'] = stderr
ret['retcode'] = proc.exitstatus
if ret['retcode'] in success_retcodes:
ret['retcode'] = 0
if ret['stdout'] in success_stdout or ret['stderr'] in success_stderr:
ret['retcode'] = 0
ret['pid'] = proc.pid
finally:
proc.close(terminate=True, kill=True)
try:
if ignore_retcode:
__context__['retcode'] = 0
else:
__context__['retcode'] = ret['retcode']
except NameError:
# Ignore the context error during grain generation
pass
# Log the output
if output_loglevel is not None:
if not ignore_retcode and ret['retcode'] != 0:
if output_loglevel < LOG_LEVELS['error']:
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if ret['stdout']:
log.log(output_loglevel, 'stdout: %s', log_callback(ret['stdout']))
if ret['stderr']:
log.log(output_loglevel, 'stderr: %s', log_callback(ret['stderr']))
if ret['retcode']:
log.log(output_loglevel, 'retcode: %s', ret['retcode'])
return ret
def _run_all_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
pillarenv=None,
pillar_override=None,
output_encoding=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None):
'''
Helper for running commands quietly for minion startup.
Returns a dict of return data.
output_loglevel argument is ignored. This is here for when we alias
cmd.run_all directly to _run_all_quiet in certain chicken-and-egg
situations where modules need to work both before and after
the __salt__ dictionary is populated (cf dracr.py)
'''
return _run(cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=None,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr)
def run(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
encoded_cmd=False,
raise_err=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
Execute the passed command and return the output as a string
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run 'echo '\''h=\"baz\"'\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If ``False``, let python handle the positional
arguments. Set to ``True`` to use shell features, such as pipes or
redirection.
:param bool bg: If ``True``, run command in background and do not await or
deliver it's results
.. versionadded:: 2016.3.0
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
:param bool raise_err: If ``True`` and the command has a nonzero exit code,
a CommandExecutionError exception will be raised.
.. warning::
This function does not process commands through a shell
unless the python_shell flag is set to True. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or
have the python_shell=True flag set here.
The use of python_shell=True means that the shell will accept _any_ input
including potentially malicious commands such as 'good_command;rm -rf /'.
Be absolutely certain that you have sanitized your input prior to using
python_shell=True
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run cmd='sed -e s/=/:/g'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
log_callback = _check_cb(log_callback)
lvl = _check_loglevel(output_loglevel)
if lvl is not None:
if not ignore_retcode and ret['retcode'] != 0:
if lvl < LOG_LEVELS['error']:
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
)
log.error(log_callback(msg))
if raise_err:
raise CommandExecutionError(
log_callback(ret['stdout'] if not hide_output else '')
)
log.log(lvl, 'output: %s', log_callback(ret['stdout']))
return ret['stdout'] if not hide_output else ''
def shell(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return the output as a string.
.. versionadded:: 2015.5.0
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.shell 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param int shell: Shell to execute under. Defaults to the system default
shell.
:param bool bg: If True, run command in background and do not await or
deliver its results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.shell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
.. warning::
This passes the cmd argument directly to the shell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.shell "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.shell template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.shell "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.shell "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.shell cmd='sed -e s/=/:/g'
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
return run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
def run_stdout(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command, and only return the standard out
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stdout 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stdout template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stdout "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stdout'] if not hide_output else ''
def run_stderr(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a command and only return the standard error
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stderr 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stderr 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stderr "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stderr template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stderr "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['stderr'] if not hide_output else ''
def run_all(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
redirect_stderr=False,
password=None,
encoded_cmd=False,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed command and return a dict of return data
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_all 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
.. versionadded:: 2018.3.0
:param bool redirect_stderr: If set to ``True``, then stderr will be
redirected to stdout. This is helpful for cases where obtaining both
the retcode and output is desired, but it is not desired to have the
output separated into both stdout and stderr.
.. versionadded:: 2015.8.2
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param bool bg: If ``True``, run command in background and do not await or
deliver its results
.. versionadded:: 2016.3.6
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_all "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_all template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_all "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=stderr,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def retcode(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute a shell command and return the command's return code.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.retcode 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.retcode 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:rtype: int
:rtype: None
:returns: Return Code as an int or None if there was an exception.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.retcode "file /bin/bash"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.retcode template=jinja "file {{grains.pythonpath[0]}}/python"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.retcode "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
ret = _run(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
return ret['retcode']
def _retcode_quiet(cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Helper for running commands quietly for minion startup. Returns same as
the retcode() function.
'''
return retcode(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel='quiet',
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stderr,
success_stderr=success_stderr,
**kwargs)
def script(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template=None,
umask=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
saltenv='base',
use_vt=False,
bg=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
.. code-block:: bash
salt myminion cmd.script salt://foo.sh "arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param bool bg: If True, run script in background and do not await or
deliver it's results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh
salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
def _cleanup_tempfile(path):
try:
__salt__['file.remove'](path)
except (SaltInvocationError, CommandExecutionError) as exc:
log.error(
'cmd.script: Unable to clean tempfile \'%s\': %s',
path, exc, exc_info_on_loglevel=logging.DEBUG
)
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
win_cwd = False
if salt.utils.platform.is_windows() and runas and cwd is None:
# Create a temp working directory
cwd = tempfile.mkdtemp(dir=__opts__['cachedir'])
win_cwd = True
salt.utils.win_dacl.set_permissions(obj_name=cwd,
principal=runas,
permissions='full_control')
path = salt.utils.files.mkstemp(dir=cwd, suffix=os.path.splitext(source)[1])
if template:
if 'pillarenv' in kwargs or 'pillar' in kwargs:
pillarenv = kwargs.get('pillarenv', __opts__.get('pillarenv'))
kwargs['pillar'] = _gather_pillar(pillarenv, kwargs.get('pillar'))
fn_ = __salt__['cp.get_template'](source,
path,
template,
saltenv,
**kwargs)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
else:
fn_ = __salt__['cp.cache_file'](source, saltenv)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {'pid': 0,
'retcode': 1,
'stdout': '',
'stderr': '',
'cache_error': True}
shutil.copyfile(fn_, path)
if not salt.utils.platform.is_windows():
os.chmod(path, 320)
os.chown(path, __salt__['file.user_to_uid'](runas), -1)
if salt.utils.platform.is_windows() and shell.lower() != 'powershell':
cmd_path = _cmd_quote(path, escape=False)
else:
cmd_path = _cmd_quote(path)
ret = _run(cmd_path + ' ' + six.text_type(args) if args else cmd_path,
cwd=cwd,
stdin=stdin,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def script_retcode(source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template='jinja',
umask=None,
timeout=None,
reset_system_locale=True,
saltenv='base',
output_encoding=None,
output_loglevel='debug',
log_callback=None,
use_vt=False,
password=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
The script can also be formatted as a template, the default is jinja.
Only evaluate the script return code and do not block for terminal output
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
"arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script_retcode 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh
salt '*' cmd.script_retcode salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script_retcode salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
'''
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
return script(source=source,
args=args,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)['retcode']
def which(cmd):
'''
Returns the path of an executable available on the minion, None otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.which cat
'''
return salt.utils.path.which(cmd)
def which_bin(cmds):
'''
Returns the first command found in a list of commands
CLI Example:
.. code-block:: bash
salt '*' cmd.which_bin '[pip2, pip, pip-python]'
'''
return salt.utils.path.which_bin(cmds)
def has_exec(cmd):
'''
Returns true if the executable is available on the minion, false otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.has_exec cat
'''
return which(cmd) is not None
def exec_code(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. The stdout will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code ruby 'puts "cheese"'
salt '*' cmd.exec_code ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
return exec_code_all(lang, code, cwd, args, **kwargs)['stdout']
def exec_code_all(lang, code, cwd=None, args=None, **kwargs):
'''
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid)
will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code_all ruby 'puts "cheese"'
salt '*' cmd.exec_code_all ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
'''
powershell = lang.lower().startswith("powershell")
if powershell:
codefile = salt.utils.files.mkstemp(suffix=".ps1")
else:
codefile = salt.utils.files.mkstemp()
with salt.utils.files.fopen(codefile, 'w+t', binary=False) as fp_:
fp_.write(salt.utils.stringutils.to_str(code))
if powershell:
cmd = [lang, "-File", codefile]
else:
cmd = [lang, codefile]
if isinstance(args, six.string_types):
cmd.append(args)
elif isinstance(args, list):
cmd += args
ret = run_all(cmd, cwd=cwd, python_shell=False, **kwargs)
os.remove(codefile)
return ret
def tty(device, echo=''):
'''
Echo a string to a specific tty
CLI Example:
.. code-block:: bash
salt '*' cmd.tty tty0 'This is a test'
salt '*' cmd.tty pts3 'This is a test'
'''
if device.startswith('tty'):
teletype = '/dev/{0}'.format(device)
elif device.startswith('pts'):
teletype = '/dev/{0}'.format(device.replace('pts', 'pts/'))
else:
return {'Error': 'The specified device is not a valid TTY'}
try:
with salt.utils.files.fopen(teletype, 'wb') as tty_device:
tty_device.write(salt.utils.stringutils.to_bytes(echo))
return {
'Success': 'Message was successfully echoed to {0}'.format(teletype)
}
except IOError:
return {
'Error': 'Echoing to {0} returned error'.format(teletype)
}
def run_chroot(root,
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=True,
binds=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='quiet',
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
bg=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
.. versionadded:: 2014.7.0
This function runs :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` wrapped
within a chroot, with dev and proc mounted in the chroot
:param str root: Path to the root of the jail to use.
:param str stdin: A string of standard input can be specified for
the command to be run using the ``stdin`` parameter. This can
be useful in cases where sensitive information must be read
from standard input.:
:param str runas: User to run script as.
:param str group: Group to run script as.
:param str shell: Shell to execute under. Defaults to the system
default shell.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:parar str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param list binds: List of directories that will be exported inside
the chroot with the bind option.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_chroot 'some command' env='{"FOO": "bar"}'
:param dict clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output
before it is returned.
:param str umask: The umask (in octal) to use when running the
command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout:
A timeout in seconds for the executed process to return.
:param bool use_vt:
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs. This is experimental.
:param success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' cmd.run_chroot /var/lib/lxc/container_name/rootfs 'sh /tmp/bootstrap.sh'
'''
__salt__['mount.mount'](
os.path.join(root, 'dev'),
'devtmpfs',
fstype='devtmpfs')
__salt__['mount.mount'](
os.path.join(root, 'proc'),
'proc',
fstype='proc')
__salt__['mount.mount'](
os.path.join(root, 'sys'),
'sysfs',
fstype='sysfs')
binds = binds if binds else []
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.mount'](
bind_exported_to,
bind_exported,
opts='default,bind')
# Execute chroot routine
sh_ = '/bin/sh'
if os.path.isfile(os.path.join(root, 'bin/bash')):
sh_ = '/bin/bash'
if isinstance(cmd, (list, tuple)):
cmd = ' '.join([six.text_type(i) for i in cmd])
cmd = 'chroot {0} {1} -c {2}'.format(root, sh_, _cmd_quote(cmd))
run_func = __context__.pop('cmd.run_chroot.func', run_all)
ret = run_func(cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
pillarenv=kwargs.get('pillarenv'),
pillar=kwargs.get('pillar'),
use_vt=use_vt,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
bg=bg)
# Kill processes running in the chroot
for i in range(6):
pids = _chroot_pids(root)
if not pids:
break
for pid in pids:
# use sig 15 (TERM) for first 3 attempts, then 9 (KILL)
sig = 15 if i < 3 else 9
os.kill(pid, sig)
if _chroot_pids(root):
log.error('Processes running in chroot could not be killed, '
'filesystem will remain mounted')
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__['mount.umount'](bind_exported_to)
__salt__['mount.umount'](os.path.join(root, 'sys'))
__salt__['mount.umount'](os.path.join(root, 'proc'))
__salt__['mount.umount'](os.path.join(root, 'dev'))
if hide_output:
ret['stdout'] = ret['stderr'] = ''
return ret
def _is_valid_shell(shell):
'''
Attempts to search for valid shells on a system and
see if a given shell is in the list
'''
if salt.utils.platform.is_windows():
return True # Don't even try this for Windows
shells = '/etc/shells'
available_shells = []
if os.path.exists(shells):
try:
with salt.utils.files.fopen(shells, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
if line.startswith('#'):
continue
else:
available_shells.append(line)
except OSError:
return True
else:
# No known method of determining available shells
return None
if shell in available_shells:
return True
else:
return False
def shells():
'''
Lists the valid shells on this system via the /etc/shells file
.. versionadded:: 2015.5.0
CLI Example::
salt '*' cmd.shells
'''
shells_fn = '/etc/shells'
ret = []
if os.path.exists(shells_fn):
try:
with salt.utils.files.fopen(shells_fn, 'r') as shell_fp:
lines = [salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()]
for line in lines:
line = line.strip()
if line.startswith('#'):
continue
elif not line:
continue
else:
ret.append(line)
except OSError:
log.error("File '%s' was not found", shells_fn)
return ret
def shell_info(shell, list_modules=False):
'''
.. versionadded:: 2016.11.0
Provides information about a shell or script languages which often use
``#!``. The values returned are dependent on the shell or scripting
languages all return the ``installed``, ``path``, ``version``,
``version_raw``
Args:
shell (str): Name of the shell. Support shells/script languages include
bash, cmd, perl, php, powershell, python, ruby and zsh
list_modules (bool): True to list modules available to the shell.
Currently only lists powershell modules.
Returns:
dict: A dictionary of information about the shell
.. code-block:: python
{'version': '<2 or 3 numeric components dot-separated>',
'version_raw': '<full version string>',
'path': '<full path to binary>',
'installed': <True, False or None>,
'<attribute>': '<attribute value>'}
.. note::
- ``installed`` is always returned, if ``None`` or ``False`` also
returns error and may also return ``stdout`` for diagnostics.
- ``version`` is for use in determine if a shell/script language has a
particular feature set, not for package management.
- The shell must be within the executable search path.
CLI Example:
.. code-block:: bash
salt '*' cmd.shell_info bash
salt '*' cmd.shell_info powershell
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
regex_shells = {
'bash': [r'version (\d\S*)', 'bash', '--version'],
'bash-test-error': [r'versioZ ([-\w.]+)', 'bash', '--version'], # used to test an error result
'bash-test-env': [r'(HOME=.*)', 'bash', '-c', 'declare'], # used to test an error result
'zsh': [r'^zsh (\d\S*)', 'zsh', '--version'],
'tcsh': [r'^tcsh (\d\S*)', 'tcsh', '--version'],
'cmd': [r'Version ([\d.]+)', 'cmd.exe', '/C', 'ver'],
'powershell': [r'PSVersion\s+(\d\S*)', 'powershell', '-NonInteractive', '$PSVersionTable'],
'perl': [r'^(\d\S*)', 'perl', '-e', 'printf "%vd\n", $^V;'],
'python': [r'^Python (\d\S*)', 'python', '-V'],
'ruby': [r'^ruby (\d\S*)', 'ruby', '-v'],
'php': [r'^PHP (\d\S*)', 'php', '-v']
}
# Ensure ret['installed'] always as a value of True, False or None (not sure)
ret = {'installed': False}
if salt.utils.platform.is_windows() and shell == 'powershell':
pw_keys = salt.utils.win_reg.list_keys(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell')
pw_keys.sort(key=int)
if not pw_keys:
return {
'error': 'Unable to locate \'powershell\' Reason: Cannot be '
'found in registry.',
'installed': False,
}
for reg_ver in pw_keys:
install_data = salt.utils.win_reg.read_value(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}'.format(reg_ver),
vname='Install')
if install_data.get('vtype') == 'REG_DWORD' and \
install_data.get('vdata') == 1:
details = salt.utils.win_reg.list_values(
hive='HKEY_LOCAL_MACHINE',
key='Software\\Microsoft\\PowerShell\\{0}\\'
'PowerShellEngine'.format(reg_ver))
# reset data, want the newest version details only as powershell
# is backwards compatible
ret = {}
# if all goes well this will become True
ret['installed'] = None
ret['path'] = which('powershell.exe')
for attribute in details:
if attribute['vname'].lower() == '(default)':
continue
elif attribute['vname'].lower() == 'powershellversion':
ret['psversion'] = attribute['vdata']
ret['version_raw'] = attribute['vdata']
elif attribute['vname'].lower() == 'runtimeversion':
ret['crlversion'] = attribute['vdata']
if ret['crlversion'][0].lower() == 'v':
ret['crlversion'] = ret['crlversion'][1::]
elif attribute['vname'].lower() == 'pscompatibleversion':
# reg attribute does not end in s, the powershell
# attribute does
ret['pscompatibleversions'] = \
attribute['vdata'].replace(' ', '').split(',')
else:
# keys are lower case as python is case sensitive the
# registry is not
ret[attribute['vname'].lower()] = attribute['vdata']
else:
if shell not in regex_shells:
return {
'error': 'Salt does not know how to get the version number for '
'{0}'.format(shell),
'installed': None
}
shell_data = regex_shells[shell]
pattern = shell_data.pop(0)
# We need to make sure HOME set, so shells work correctly
# salt-call will general have home set, the salt-minion service may not
# We need to assume ports of unix shells to windows will look after
# themselves in setting HOME as they do it in many different ways
newenv = os.environ
if ('HOME' not in newenv) and (not salt.utils.platform.is_windows()):
newenv['HOME'] = os.path.expanduser('~')
log.debug('HOME environment set to %s', newenv['HOME'])
try:
proc = salt.utils.timed_subprocess.TimedProc(
shell_data,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=10,
env=newenv
)
except (OSError, IOError) as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: {1}'.format(' '.join(shell_data), exc),
'installed': False,
}
try:
proc.run()
except TimedProcTimeoutError as exc:
return {
'error': 'Unable to run command \'{0}\' Reason: Timed out.'.format(' '.join(shell_data)),
'installed': False,
}
ret['path'] = which(shell_data[0])
pattern_result = re.search(pattern, proc.stdout, flags=re.IGNORECASE)
# only set version if we find it, so code later on can deal with it
if pattern_result:
ret['version_raw'] = pattern_result.group(1)
if 'version_raw' in ret:
version_results = re.match(r'(\d[\d.]*)', ret['version_raw'])
if version_results:
ret['installed'] = True
ver_list = version_results.group(1).split('.')[:3]
if len(ver_list) == 1:
ver_list.append('0')
ret['version'] = '.'.join(ver_list[:3])
else:
ret['installed'] = None # Have an unexpected result
# Get a list of the PowerShell modules which are potentially available
# to be imported
if shell == 'powershell' and ret['installed'] and list_modules:
ret['modules'] = salt.utils.powershell.get_modules()
if 'version' not in ret:
ret['error'] = 'The version regex pattern for shell {0}, could not ' \
'find the version string'.format(shell)
ret['stdout'] = proc.stdout # include stdout so they can see the issue
log.error(ret['error'])
return ret
def powershell(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return the output as a dictionary.
Other ``cmd.*`` functions (besides ``cmd.powershell_all``)
return the raw text output of the command. This
function appends ``| ConvertTo-JSON`` to the command and then parses the
JSON into a Python dictionary. If you want the raw textual result of your
PowerShell command you should use ``cmd.run`` with the ``shell=powershell``
option.
For example:
.. code-block:: bash
salt '*' cmd.run '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2016.3.0
.. warning::
This passes the cmd argument directly to PowerShell
without any further processing! Be absolutely sure that you
have properly sanitized the command passed to this function
and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in cases
where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
.. versionadded:: 2016.3.4
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:returns:
:dict: A dictionary of data returned by the powershell command.
CLI Example:
.. code-block:: powershell
salt '*' cmd.powershell "$PSVersionTable.CLRVersion"
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
# ConvertTo-JSON is only available on PowerShell 3.0 and later
psversion = shell_info('powershell')['psversion']
if salt.utils.versions.version_cmp(psversion, '2.0') == 1:
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Put the whole command inside a try / catch block
# Some errors in PowerShell are not "Terminating Errors" and will not be
# caught in a try/catch block. For example, the `Get-WmiObject` command will
# often return a "Non Terminating Error". To fix this, make sure
# `-ErrorAction Stop` is set in the powershell command
cmd = 'try {' + cmd + '} catch { "{}" }'
# Retrieve the response, while overriding shell with 'powershell'
response = run(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
try:
return salt.utils.json.loads(response)
except Exception:
log.error("Error converting PowerShell JSON return", exc_info=True)
return {}
def powershell_all(cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel='debug',
quiet=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
force_list=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Execute the passed PowerShell command and return a dictionary with a result
field representing the output of the command, as well as other fields
showing us what the PowerShell invocation wrote to ``stderr``, the process
id, and the exit code of the invocation.
This function appends ``| ConvertTo-JSON`` to the command before actually
invoking powershell.
An unquoted empty string is not valid JSON, but it's very normal for the
Powershell output to be exactly that. Therefore, we do not attempt to parse
empty Powershell output (which would result in an exception). Instead we
treat this as a special case and one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field of the return dictionary will be an empty list.
- If the value of the ``force_list`` parameter is ``False``, then the
return dictionary **will not have a result key added to it**. We aren't
setting ``result`` to ``None`` in this case, because ``None`` is the
Python representation of "null" in JSON. (We likewise can't use ``False``
for the equivalent reason.)
If Powershell's output is not an empty string and Python cannot parse its
content, then a ``CommandExecutionError`` exception will be raised.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is other than ``list``
then one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field will be a singleton list with the Python object as its
sole member.
- If the value of the ``force_list`` parameter is ``False``, then the value
of ``result`` will be the unmodified Python object.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is ``list``, then the
value of ``result`` will be the unmodified Python object. The
``force_list`` parameter has no effect in this case.
.. note::
An example of why the ``force_list`` parameter is useful is as
follows: The Powershell command ``dir x | Convert-ToJson`` results in
- no output when x is an empty directory.
- a dictionary object when x contains just one item.
- a list of dictionary objects when x contains multiple items.
By setting ``force_list`` to ``True`` we will always end up with a
list of dictionary items, representing files, no matter how many files
x contains. Conversely, if ``force_list`` is ``False``, we will end
up with no ``result`` key in our return dictionary when x is an empty
directory, and a dictionary object when x contains just one file.
If you want a similar function but with a raw textual result instead of a
Python dictionary, you should use ``cmd.run_all`` in combination with
``shell=powershell``.
The remaining fields in the return dictionary are described in more detail
in the ``Returns`` section.
Example:
.. code-block:: bash
salt '*' cmd.run_all '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run_all 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2018.3.0
.. warning::
This passes the cmd argument directly to PowerShell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param bool force_list: The purpose of this parameter is described in the
preamble of this function's documentation. Default value is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:return: A dictionary with the following entries:
result
For a complete description of this field, please refer to this
function's preamble. **This key will not be added to the dictionary
when force_list is False and Powershell's output is the empty
string.**
stderr
What the PowerShell invocation wrote to ``stderr``.
pid
The process id of the PowerShell invocation
retcode
This is the exit code of the invocation of PowerShell.
If the final execution status (in PowerShell) of our command
(with ``| ConvertTo-JSON`` appended) is ``False`` this should be non-0.
Likewise if PowerShell exited with ``$LASTEXITCODE`` set to some
non-0 value, then ``retcode`` will end up with this value.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "$PSVersionTable.CLRVersion"
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "dir mydirectory" force_list=True
'''
if 'python_shell' in kwargs:
python_shell = kwargs.pop('python_shell')
else:
python_shell = True
# Append PowerShell Object formatting
cmd += ' | ConvertTo-JSON'
if depth is not None:
cmd += ' -Depth {0}'.format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug('Encoding PowerShell command \'%s\'', cmd)
cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Retrieve the response, while overriding shell with 'powershell'
response = run_all(cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell='powershell',
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
quiet=quiet,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs)
stdoutput = response['stdout']
# if stdoutput is the empty string and force_list is True we return an empty list
# Otherwise we return response with no result key
if not stdoutput:
response.pop('stdout')
if force_list:
response['result'] = []
return response
# If we fail to parse stdoutput we will raise an exception
try:
result = salt.utils.json.loads(stdoutput)
except Exception:
err_msg = "cmd.powershell_all " + \
"cannot parse the Powershell output."
response["cmd"] = cmd
raise CommandExecutionError(
message=err_msg,
info=response
)
response.pop("stdout")
if type(result) is not list:
if force_list:
response['result'] = [result]
else:
response['result'] = result
else:
# result type is list so the force_list param has no effect
response['result'] = result
return response
def run_bg(cmd,
cwd=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
timeout=None,
output_encoding=None,
output_loglevel='debug',
log_callback=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv='base',
password=None,
prepend_path=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
r'''
.. versionadded: 2016.3.0
Execute the passed command in the background and return it's PID
.. note::
If the init system is systemd and the backgrounded task should run even
if the salt-minion process is restarted, prepend ``systemd-run
--scope`` to the command. This will reparent the process in its own
scope separate from salt-minion, and will not be affected by restarting
the minion service.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Shell to execute under. Defaults to the system default
shell.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_bg 'echo '\''h=\"baz\"'\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_bg 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param int timeout: A timeout in seconds for the executed process to return.
.. warning::
This function does not process commands through a shell unless the
``python_shell`` argument is set to ``True``. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or have the
python_shell=True flag set here.
The use of ``python_shell=True`` means that the shell will accept _any_
input including potentially malicious commands such as 'good_command;rm
-rf /'. Be absolutely certain that you have sanitized your input prior
to using ``python_shell=True``.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param list success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param list success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_bg "fstrim-all"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_bg template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run_bg "Get-ChildItem C:\\ " shell='powershell'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run_bg cmd='ls -lR / | sed -e s/=/:/g > /tmp/dontwait'
'''
python_shell = _python_shell_default(python_shell,
kwargs.get('__pub_jid', ''))
res = _run(cmd,
stdin=None,
stderr=None,
stdout=None,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
use_vt=None,
bg=True,
with_communicate=False,
rstrip=False,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
umask=umask,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
success_stdout=success_stdout,
success_stderr=success_stderr,
**kwargs
)
return {
'pid': res['pid']
}
|
saltstack/salt
|
salt/modules/zoneadm.py
|
_is_globalzone
|
python
|
def _is_globalzone():
'''
Check if we are running in the globalzone
'''
if not __grains__['kernel'] == 'SunOS':
return False
zonename = __salt__['cmd.run_all']('zonename')
if zonename['retcode']:
return False
if zonename['stdout'] == 'global':
return True
return False
|
Check if we are running in the globalzone
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zoneadm.py#L36-L49
| null |
# -*- coding: utf-8 -*-
'''
Module for Solaris 10's zoneadm
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:platform: OmniOS,OpenIndiana,SmartOS,OpenSolaris,Solaris 10
.. versionadded:: 2017.7.0
.. warning::
Oracle Solaris 11's zoneadm is not supported by this module!
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.decorators
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'zoneadm'
# Function aliases
__func_alias__ = {
'list_zones': 'list'
}
@salt.utils.decorators.memoize
def _is_uuid(zone):
'''
Check if zone is actually a UUID
'''
return len(zone) == 36 and zone.index('-') == 8
def __virtual__():
'''
We are available if we are have zoneadm and are the global zone on
Solaris 10, OmniOS, OpenIndiana, OpenSolaris, or Smartos.
'''
if _is_globalzone() and salt.utils.path.which('zoneadm'):
if __grains__['os'] in ['OpenSolaris', 'SmartOS', 'OmniOS', 'OpenIndiana']:
return __virtualname__
elif __grains__['os'] == 'Oracle Solaris' and int(__grains__['osmajorrelease']) == 10:
return __virtualname__
return (
False,
'{0} module can only be loaded in a solaris globalzone.'.format(
__virtualname__
)
)
def list_zones(verbose=True, installed=False, configured=False, hide_global=True):
'''
List all zones
verbose : boolean
display additional zone information
installed : boolean
include installed zones in output
configured : boolean
include configured zones in output
hide_global : boolean
do not include global zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.list
'''
zones = {}
## fetch zones
header = 'zoneid:zonename:state:zonepath:uuid:brand:ip-type'.split(':')
zone_data = __salt__['cmd.run_all']('zoneadm list -p -c')
if zone_data['retcode'] == 0:
for zone in zone_data['stdout'].splitlines():
zone = zone.split(':')
# create zone_t
zone_t = {}
for i in range(0, len(header)):
zone_t[header[i]] = zone[i]
# skip if global and hide_global
if hide_global and zone_t['zonename'] == 'global':
continue
# skip installed and configured
if not installed and zone_t['state'] == 'installed':
continue
if not configured and zone_t['state'] == 'configured':
continue
# update dict
zones[zone_t['zonename']] = zone_t
del zones[zone_t['zonename']]['zonename']
return zones if verbose else sorted(zones.keys())
def boot(zone, single=False, altinit=None, smf_options=None):
'''
Boot (or activate) the specified zone.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.boot clementine
salt '*' zoneadm.boot maeve single=True
salt '*' zoneadm.boot teddy single=True smf_options=verbose
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute boot
res = __salt__['cmd.run_all']('zoneadm {zone} boot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def reboot(zone, single=False, altinit=None, smf_options=None):
'''
Restart the zone. This is equivalent to a halt boot sequence.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.reboot dolores
salt '*' zoneadm.reboot teddy single=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute reboot
res = __salt__['cmd.run_all']('zoneadm {zone} reboot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def halt(zone):
'''
Halt the specified zone.
zone : string
name or uuid of the zone
.. note::
To cleanly shutdown the zone use the shutdown function.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.halt hector
'''
ret = {'status': True}
## halt zone
res = __salt__['cmd.run_all']('zoneadm {zone} halt'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def shutdown(zone, reboot=False, single=False, altinit=None, smf_options=None):
'''
Gracefully shutdown the specified zone.
zone : string
name or uuid of the zone
reboot : boolean
reboot zone after shutdown (equivalent of shutdown -i6 -g0 -y)
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.shutdown peter
salt '*' zoneadm.shutdown armistice reboot=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## shutdown zone
res = __salt__['cmd.run_all']('zoneadm {zone} shutdown{reboot}{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
reboot=' -r' if reboot else '',
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def detach(zone):
'''
Detach the specified zone.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.detach kissy
'''
ret = {'status': True}
## detach zone
res = __salt__['cmd.run_all']('zoneadm {zone} detach'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def attach(zone, force=False, brand_opts=None):
'''
Attach the specified zone.
zone : string
name of the zone
force : boolean
force the zone into the "installed" state with no validation
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.attach lawrence
salt '*' zoneadm.attach lawrence True
'''
ret = {'status': True}
## attach zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} attach{force}{brand_opts}'.format(
zone=zone,
force=' -F' if force else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def ready(zone):
'''
Prepares a zone for running applications.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.ready clementine
'''
ret = {'status': True}
## ready zone
res = __salt__['cmd.run_all']('zoneadm {zone} ready'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def verify(zone):
'''
Check to make sure the configuration of the specified
zone can safely be installed on the machine.
zone : string
name of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.verify dolores
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} verify'.format(
zone=zone,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def move(zone, zonepath):
'''
Move zone to new zonepath.
zone : string
name or uuid of the zone
zonepath : string
new zonepath
CLI Example:
.. code-block:: bash
salt '*' zoneadm.move meave /sweetwater/meave
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm {zone} move {path}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
path=zonepath,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def uninstall(zone):
'''
Uninstall the specified zone from the system.
zone : string
name or uuid of the zone
.. warning::
The -F flag is always used to avoid the prompts when uninstalling.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.uninstall teddy
'''
ret = {'status': True}
## uninstall zone
res = __salt__['cmd.run_all']('zoneadm {zone} uninstall -F'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def install(zone, nodataset=False, brand_opts=None):
'''
Install the specified zone from the system.
zone : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.install dolores
salt '*' zoneadm.install teddy True
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} install{nodataset}{brand_opts}'.format(
zone=zone,
nodataset=' -x nodataset' if nodataset else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def clone(zone, source, snapshot=None):
'''
Install a zone by copying an existing installed zone.
zone : string
name of the zone
source : string
zone to clone from
snapshot : string
optional name of snapshot to use as source
CLI Example:
.. code-block:: bash
salt '*' zoneadm.clone clementine dolores
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} clone {snapshot}{source}'.format(
zone=zone,
source=source,
snapshot='-s {0} '.format(snapshot) if snapshot else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/modules/zoneadm.py
|
list_zones
|
python
|
def list_zones(verbose=True, installed=False, configured=False, hide_global=True):
'''
List all zones
verbose : boolean
display additional zone information
installed : boolean
include installed zones in output
configured : boolean
include configured zones in output
hide_global : boolean
do not include global zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.list
'''
zones = {}
## fetch zones
header = 'zoneid:zonename:state:zonepath:uuid:brand:ip-type'.split(':')
zone_data = __salt__['cmd.run_all']('zoneadm list -p -c')
if zone_data['retcode'] == 0:
for zone in zone_data['stdout'].splitlines():
zone = zone.split(':')
# create zone_t
zone_t = {}
for i in range(0, len(header)):
zone_t[header[i]] = zone[i]
# skip if global and hide_global
if hide_global and zone_t['zonename'] == 'global':
continue
# skip installed and configured
if not installed and zone_t['state'] == 'installed':
continue
if not configured and zone_t['state'] == 'configured':
continue
# update dict
zones[zone_t['zonename']] = zone_t
del zones[zone_t['zonename']]['zonename']
return zones if verbose else sorted(zones.keys())
|
List all zones
verbose : boolean
display additional zone information
installed : boolean
include installed zones in output
configured : boolean
include configured zones in output
hide_global : boolean
do not include global zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zoneadm.py#L77-L124
| null |
# -*- coding: utf-8 -*-
'''
Module for Solaris 10's zoneadm
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:platform: OmniOS,OpenIndiana,SmartOS,OpenSolaris,Solaris 10
.. versionadded:: 2017.7.0
.. warning::
Oracle Solaris 11's zoneadm is not supported by this module!
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.decorators
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'zoneadm'
# Function aliases
__func_alias__ = {
'list_zones': 'list'
}
@salt.utils.decorators.memoize
def _is_globalzone():
'''
Check if we are running in the globalzone
'''
if not __grains__['kernel'] == 'SunOS':
return False
zonename = __salt__['cmd.run_all']('zonename')
if zonename['retcode']:
return False
if zonename['stdout'] == 'global':
return True
return False
def _is_uuid(zone):
'''
Check if zone is actually a UUID
'''
return len(zone) == 36 and zone.index('-') == 8
def __virtual__():
'''
We are available if we are have zoneadm and are the global zone on
Solaris 10, OmniOS, OpenIndiana, OpenSolaris, or Smartos.
'''
if _is_globalzone() and salt.utils.path.which('zoneadm'):
if __grains__['os'] in ['OpenSolaris', 'SmartOS', 'OmniOS', 'OpenIndiana']:
return __virtualname__
elif __grains__['os'] == 'Oracle Solaris' and int(__grains__['osmajorrelease']) == 10:
return __virtualname__
return (
False,
'{0} module can only be loaded in a solaris globalzone.'.format(
__virtualname__
)
)
def boot(zone, single=False, altinit=None, smf_options=None):
'''
Boot (or activate) the specified zone.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.boot clementine
salt '*' zoneadm.boot maeve single=True
salt '*' zoneadm.boot teddy single=True smf_options=verbose
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute boot
res = __salt__['cmd.run_all']('zoneadm {zone} boot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def reboot(zone, single=False, altinit=None, smf_options=None):
'''
Restart the zone. This is equivalent to a halt boot sequence.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.reboot dolores
salt '*' zoneadm.reboot teddy single=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute reboot
res = __salt__['cmd.run_all']('zoneadm {zone} reboot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def halt(zone):
'''
Halt the specified zone.
zone : string
name or uuid of the zone
.. note::
To cleanly shutdown the zone use the shutdown function.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.halt hector
'''
ret = {'status': True}
## halt zone
res = __salt__['cmd.run_all']('zoneadm {zone} halt'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def shutdown(zone, reboot=False, single=False, altinit=None, smf_options=None):
'''
Gracefully shutdown the specified zone.
zone : string
name or uuid of the zone
reboot : boolean
reboot zone after shutdown (equivalent of shutdown -i6 -g0 -y)
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.shutdown peter
salt '*' zoneadm.shutdown armistice reboot=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## shutdown zone
res = __salt__['cmd.run_all']('zoneadm {zone} shutdown{reboot}{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
reboot=' -r' if reboot else '',
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def detach(zone):
'''
Detach the specified zone.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.detach kissy
'''
ret = {'status': True}
## detach zone
res = __salt__['cmd.run_all']('zoneadm {zone} detach'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def attach(zone, force=False, brand_opts=None):
'''
Attach the specified zone.
zone : string
name of the zone
force : boolean
force the zone into the "installed" state with no validation
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.attach lawrence
salt '*' zoneadm.attach lawrence True
'''
ret = {'status': True}
## attach zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} attach{force}{brand_opts}'.format(
zone=zone,
force=' -F' if force else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def ready(zone):
'''
Prepares a zone for running applications.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.ready clementine
'''
ret = {'status': True}
## ready zone
res = __salt__['cmd.run_all']('zoneadm {zone} ready'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def verify(zone):
'''
Check to make sure the configuration of the specified
zone can safely be installed on the machine.
zone : string
name of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.verify dolores
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} verify'.format(
zone=zone,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def move(zone, zonepath):
'''
Move zone to new zonepath.
zone : string
name or uuid of the zone
zonepath : string
new zonepath
CLI Example:
.. code-block:: bash
salt '*' zoneadm.move meave /sweetwater/meave
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm {zone} move {path}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
path=zonepath,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def uninstall(zone):
'''
Uninstall the specified zone from the system.
zone : string
name or uuid of the zone
.. warning::
The -F flag is always used to avoid the prompts when uninstalling.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.uninstall teddy
'''
ret = {'status': True}
## uninstall zone
res = __salt__['cmd.run_all']('zoneadm {zone} uninstall -F'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def install(zone, nodataset=False, brand_opts=None):
'''
Install the specified zone from the system.
zone : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.install dolores
salt '*' zoneadm.install teddy True
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} install{nodataset}{brand_opts}'.format(
zone=zone,
nodataset=' -x nodataset' if nodataset else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def clone(zone, source, snapshot=None):
'''
Install a zone by copying an existing installed zone.
zone : string
name of the zone
source : string
zone to clone from
snapshot : string
optional name of snapshot to use as source
CLI Example:
.. code-block:: bash
salt '*' zoneadm.clone clementine dolores
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} clone {snapshot}{source}'.format(
zone=zone,
source=source,
snapshot='-s {0} '.format(snapshot) if snapshot else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/modules/zoneadm.py
|
boot
|
python
|
def boot(zone, single=False, altinit=None, smf_options=None):
'''
Boot (or activate) the specified zone.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.boot clementine
salt '*' zoneadm.boot maeve single=True
salt '*' zoneadm.boot teddy single=True smf_options=verbose
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute boot
res = __salt__['cmd.run_all']('zoneadm {zone} boot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
|
Boot (or activate) the specified zone.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.boot clementine
salt '*' zoneadm.boot maeve single=True
salt '*' zoneadm.boot teddy single=True smf_options=verbose
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zoneadm.py#L127-L173
|
[
"def _is_uuid(zone):\n '''\n Check if zone is actually a UUID\n '''\n return len(zone) == 36 and zone.index('-') == 8\n"
] |
# -*- coding: utf-8 -*-
'''
Module for Solaris 10's zoneadm
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:platform: OmniOS,OpenIndiana,SmartOS,OpenSolaris,Solaris 10
.. versionadded:: 2017.7.0
.. warning::
Oracle Solaris 11's zoneadm is not supported by this module!
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.decorators
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'zoneadm'
# Function aliases
__func_alias__ = {
'list_zones': 'list'
}
@salt.utils.decorators.memoize
def _is_globalzone():
'''
Check if we are running in the globalzone
'''
if not __grains__['kernel'] == 'SunOS':
return False
zonename = __salt__['cmd.run_all']('zonename')
if zonename['retcode']:
return False
if zonename['stdout'] == 'global':
return True
return False
def _is_uuid(zone):
'''
Check if zone is actually a UUID
'''
return len(zone) == 36 and zone.index('-') == 8
def __virtual__():
'''
We are available if we are have zoneadm and are the global zone on
Solaris 10, OmniOS, OpenIndiana, OpenSolaris, or Smartos.
'''
if _is_globalzone() and salt.utils.path.which('zoneadm'):
if __grains__['os'] in ['OpenSolaris', 'SmartOS', 'OmniOS', 'OpenIndiana']:
return __virtualname__
elif __grains__['os'] == 'Oracle Solaris' and int(__grains__['osmajorrelease']) == 10:
return __virtualname__
return (
False,
'{0} module can only be loaded in a solaris globalzone.'.format(
__virtualname__
)
)
def list_zones(verbose=True, installed=False, configured=False, hide_global=True):
'''
List all zones
verbose : boolean
display additional zone information
installed : boolean
include installed zones in output
configured : boolean
include configured zones in output
hide_global : boolean
do not include global zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.list
'''
zones = {}
## fetch zones
header = 'zoneid:zonename:state:zonepath:uuid:brand:ip-type'.split(':')
zone_data = __salt__['cmd.run_all']('zoneadm list -p -c')
if zone_data['retcode'] == 0:
for zone in zone_data['stdout'].splitlines():
zone = zone.split(':')
# create zone_t
zone_t = {}
for i in range(0, len(header)):
zone_t[header[i]] = zone[i]
# skip if global and hide_global
if hide_global and zone_t['zonename'] == 'global':
continue
# skip installed and configured
if not installed and zone_t['state'] == 'installed':
continue
if not configured and zone_t['state'] == 'configured':
continue
# update dict
zones[zone_t['zonename']] = zone_t
del zones[zone_t['zonename']]['zonename']
return zones if verbose else sorted(zones.keys())
def reboot(zone, single=False, altinit=None, smf_options=None):
'''
Restart the zone. This is equivalent to a halt boot sequence.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.reboot dolores
salt '*' zoneadm.reboot teddy single=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute reboot
res = __salt__['cmd.run_all']('zoneadm {zone} reboot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def halt(zone):
'''
Halt the specified zone.
zone : string
name or uuid of the zone
.. note::
To cleanly shutdown the zone use the shutdown function.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.halt hector
'''
ret = {'status': True}
## halt zone
res = __salt__['cmd.run_all']('zoneadm {zone} halt'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def shutdown(zone, reboot=False, single=False, altinit=None, smf_options=None):
'''
Gracefully shutdown the specified zone.
zone : string
name or uuid of the zone
reboot : boolean
reboot zone after shutdown (equivalent of shutdown -i6 -g0 -y)
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.shutdown peter
salt '*' zoneadm.shutdown armistice reboot=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## shutdown zone
res = __salt__['cmd.run_all']('zoneadm {zone} shutdown{reboot}{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
reboot=' -r' if reboot else '',
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def detach(zone):
'''
Detach the specified zone.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.detach kissy
'''
ret = {'status': True}
## detach zone
res = __salt__['cmd.run_all']('zoneadm {zone} detach'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def attach(zone, force=False, brand_opts=None):
'''
Attach the specified zone.
zone : string
name of the zone
force : boolean
force the zone into the "installed" state with no validation
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.attach lawrence
salt '*' zoneadm.attach lawrence True
'''
ret = {'status': True}
## attach zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} attach{force}{brand_opts}'.format(
zone=zone,
force=' -F' if force else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def ready(zone):
'''
Prepares a zone for running applications.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.ready clementine
'''
ret = {'status': True}
## ready zone
res = __salt__['cmd.run_all']('zoneadm {zone} ready'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def verify(zone):
'''
Check to make sure the configuration of the specified
zone can safely be installed on the machine.
zone : string
name of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.verify dolores
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} verify'.format(
zone=zone,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def move(zone, zonepath):
'''
Move zone to new zonepath.
zone : string
name or uuid of the zone
zonepath : string
new zonepath
CLI Example:
.. code-block:: bash
salt '*' zoneadm.move meave /sweetwater/meave
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm {zone} move {path}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
path=zonepath,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def uninstall(zone):
'''
Uninstall the specified zone from the system.
zone : string
name or uuid of the zone
.. warning::
The -F flag is always used to avoid the prompts when uninstalling.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.uninstall teddy
'''
ret = {'status': True}
## uninstall zone
res = __salt__['cmd.run_all']('zoneadm {zone} uninstall -F'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def install(zone, nodataset=False, brand_opts=None):
'''
Install the specified zone from the system.
zone : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.install dolores
salt '*' zoneadm.install teddy True
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} install{nodataset}{brand_opts}'.format(
zone=zone,
nodataset=' -x nodataset' if nodataset else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def clone(zone, source, snapshot=None):
'''
Install a zone by copying an existing installed zone.
zone : string
name of the zone
source : string
zone to clone from
snapshot : string
optional name of snapshot to use as source
CLI Example:
.. code-block:: bash
salt '*' zoneadm.clone clementine dolores
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} clone {snapshot}{source}'.format(
zone=zone,
source=source,
snapshot='-s {0} '.format(snapshot) if snapshot else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/modules/zoneadm.py
|
attach
|
python
|
def attach(zone, force=False, brand_opts=None):
'''
Attach the specified zone.
zone : string
name of the zone
force : boolean
force the zone into the "installed" state with no validation
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.attach lawrence
salt '*' zoneadm.attach lawrence True
'''
ret = {'status': True}
## attach zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} attach{force}{brand_opts}'.format(
zone=zone,
force=' -F' if force else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
|
Attach the specified zone.
zone : string
name of the zone
force : boolean
force the zone into the "installed" state with no validation
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.attach lawrence
salt '*' zoneadm.attach lawrence True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zoneadm.py#L334-L366
| null |
# -*- coding: utf-8 -*-
'''
Module for Solaris 10's zoneadm
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:platform: OmniOS,OpenIndiana,SmartOS,OpenSolaris,Solaris 10
.. versionadded:: 2017.7.0
.. warning::
Oracle Solaris 11's zoneadm is not supported by this module!
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.decorators
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'zoneadm'
# Function aliases
__func_alias__ = {
'list_zones': 'list'
}
@salt.utils.decorators.memoize
def _is_globalzone():
'''
Check if we are running in the globalzone
'''
if not __grains__['kernel'] == 'SunOS':
return False
zonename = __salt__['cmd.run_all']('zonename')
if zonename['retcode']:
return False
if zonename['stdout'] == 'global':
return True
return False
def _is_uuid(zone):
'''
Check if zone is actually a UUID
'''
return len(zone) == 36 and zone.index('-') == 8
def __virtual__():
'''
We are available if we are have zoneadm and are the global zone on
Solaris 10, OmniOS, OpenIndiana, OpenSolaris, or Smartos.
'''
if _is_globalzone() and salt.utils.path.which('zoneadm'):
if __grains__['os'] in ['OpenSolaris', 'SmartOS', 'OmniOS', 'OpenIndiana']:
return __virtualname__
elif __grains__['os'] == 'Oracle Solaris' and int(__grains__['osmajorrelease']) == 10:
return __virtualname__
return (
False,
'{0} module can only be loaded in a solaris globalzone.'.format(
__virtualname__
)
)
def list_zones(verbose=True, installed=False, configured=False, hide_global=True):
'''
List all zones
verbose : boolean
display additional zone information
installed : boolean
include installed zones in output
configured : boolean
include configured zones in output
hide_global : boolean
do not include global zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.list
'''
zones = {}
## fetch zones
header = 'zoneid:zonename:state:zonepath:uuid:brand:ip-type'.split(':')
zone_data = __salt__['cmd.run_all']('zoneadm list -p -c')
if zone_data['retcode'] == 0:
for zone in zone_data['stdout'].splitlines():
zone = zone.split(':')
# create zone_t
zone_t = {}
for i in range(0, len(header)):
zone_t[header[i]] = zone[i]
# skip if global and hide_global
if hide_global and zone_t['zonename'] == 'global':
continue
# skip installed and configured
if not installed and zone_t['state'] == 'installed':
continue
if not configured and zone_t['state'] == 'configured':
continue
# update dict
zones[zone_t['zonename']] = zone_t
del zones[zone_t['zonename']]['zonename']
return zones if verbose else sorted(zones.keys())
def boot(zone, single=False, altinit=None, smf_options=None):
'''
Boot (or activate) the specified zone.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.boot clementine
salt '*' zoneadm.boot maeve single=True
salt '*' zoneadm.boot teddy single=True smf_options=verbose
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute boot
res = __salt__['cmd.run_all']('zoneadm {zone} boot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def reboot(zone, single=False, altinit=None, smf_options=None):
'''
Restart the zone. This is equivalent to a halt boot sequence.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.reboot dolores
salt '*' zoneadm.reboot teddy single=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute reboot
res = __salt__['cmd.run_all']('zoneadm {zone} reboot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def halt(zone):
'''
Halt the specified zone.
zone : string
name or uuid of the zone
.. note::
To cleanly shutdown the zone use the shutdown function.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.halt hector
'''
ret = {'status': True}
## halt zone
res = __salt__['cmd.run_all']('zoneadm {zone} halt'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def shutdown(zone, reboot=False, single=False, altinit=None, smf_options=None):
'''
Gracefully shutdown the specified zone.
zone : string
name or uuid of the zone
reboot : boolean
reboot zone after shutdown (equivalent of shutdown -i6 -g0 -y)
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.shutdown peter
salt '*' zoneadm.shutdown armistice reboot=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## shutdown zone
res = __salt__['cmd.run_all']('zoneadm {zone} shutdown{reboot}{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
reboot=' -r' if reboot else '',
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def detach(zone):
'''
Detach the specified zone.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.detach kissy
'''
ret = {'status': True}
## detach zone
res = __salt__['cmd.run_all']('zoneadm {zone} detach'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def ready(zone):
'''
Prepares a zone for running applications.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.ready clementine
'''
ret = {'status': True}
## ready zone
res = __salt__['cmd.run_all']('zoneadm {zone} ready'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def verify(zone):
'''
Check to make sure the configuration of the specified
zone can safely be installed on the machine.
zone : string
name of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.verify dolores
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} verify'.format(
zone=zone,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def move(zone, zonepath):
'''
Move zone to new zonepath.
zone : string
name or uuid of the zone
zonepath : string
new zonepath
CLI Example:
.. code-block:: bash
salt '*' zoneadm.move meave /sweetwater/meave
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm {zone} move {path}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
path=zonepath,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def uninstall(zone):
'''
Uninstall the specified zone from the system.
zone : string
name or uuid of the zone
.. warning::
The -F flag is always used to avoid the prompts when uninstalling.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.uninstall teddy
'''
ret = {'status': True}
## uninstall zone
res = __salt__['cmd.run_all']('zoneadm {zone} uninstall -F'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def install(zone, nodataset=False, brand_opts=None):
'''
Install the specified zone from the system.
zone : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.install dolores
salt '*' zoneadm.install teddy True
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} install{nodataset}{brand_opts}'.format(
zone=zone,
nodataset=' -x nodataset' if nodataset else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def clone(zone, source, snapshot=None):
'''
Install a zone by copying an existing installed zone.
zone : string
name of the zone
source : string
zone to clone from
snapshot : string
optional name of snapshot to use as source
CLI Example:
.. code-block:: bash
salt '*' zoneadm.clone clementine dolores
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} clone {snapshot}{source}'.format(
zone=zone,
source=source,
snapshot='-s {0} '.format(snapshot) if snapshot else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/modules/zoneadm.py
|
ready
|
python
|
def ready(zone):
'''
Prepares a zone for running applications.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.ready clementine
'''
ret = {'status': True}
## ready zone
res = __salt__['cmd.run_all']('zoneadm {zone} ready'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
|
Prepares a zone for running applications.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.ready clementine
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zoneadm.py#L369-L394
|
[
"def _is_uuid(zone):\n '''\n Check if zone is actually a UUID\n '''\n return len(zone) == 36 and zone.index('-') == 8\n"
] |
# -*- coding: utf-8 -*-
'''
Module for Solaris 10's zoneadm
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:platform: OmniOS,OpenIndiana,SmartOS,OpenSolaris,Solaris 10
.. versionadded:: 2017.7.0
.. warning::
Oracle Solaris 11's zoneadm is not supported by this module!
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.decorators
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'zoneadm'
# Function aliases
__func_alias__ = {
'list_zones': 'list'
}
@salt.utils.decorators.memoize
def _is_globalzone():
'''
Check if we are running in the globalzone
'''
if not __grains__['kernel'] == 'SunOS':
return False
zonename = __salt__['cmd.run_all']('zonename')
if zonename['retcode']:
return False
if zonename['stdout'] == 'global':
return True
return False
def _is_uuid(zone):
'''
Check if zone is actually a UUID
'''
return len(zone) == 36 and zone.index('-') == 8
def __virtual__():
'''
We are available if we are have zoneadm and are the global zone on
Solaris 10, OmniOS, OpenIndiana, OpenSolaris, or Smartos.
'''
if _is_globalzone() and salt.utils.path.which('zoneadm'):
if __grains__['os'] in ['OpenSolaris', 'SmartOS', 'OmniOS', 'OpenIndiana']:
return __virtualname__
elif __grains__['os'] == 'Oracle Solaris' and int(__grains__['osmajorrelease']) == 10:
return __virtualname__
return (
False,
'{0} module can only be loaded in a solaris globalzone.'.format(
__virtualname__
)
)
def list_zones(verbose=True, installed=False, configured=False, hide_global=True):
'''
List all zones
verbose : boolean
display additional zone information
installed : boolean
include installed zones in output
configured : boolean
include configured zones in output
hide_global : boolean
do not include global zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.list
'''
zones = {}
## fetch zones
header = 'zoneid:zonename:state:zonepath:uuid:brand:ip-type'.split(':')
zone_data = __salt__['cmd.run_all']('zoneadm list -p -c')
if zone_data['retcode'] == 0:
for zone in zone_data['stdout'].splitlines():
zone = zone.split(':')
# create zone_t
zone_t = {}
for i in range(0, len(header)):
zone_t[header[i]] = zone[i]
# skip if global and hide_global
if hide_global and zone_t['zonename'] == 'global':
continue
# skip installed and configured
if not installed and zone_t['state'] == 'installed':
continue
if not configured and zone_t['state'] == 'configured':
continue
# update dict
zones[zone_t['zonename']] = zone_t
del zones[zone_t['zonename']]['zonename']
return zones if verbose else sorted(zones.keys())
def boot(zone, single=False, altinit=None, smf_options=None):
'''
Boot (or activate) the specified zone.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.boot clementine
salt '*' zoneadm.boot maeve single=True
salt '*' zoneadm.boot teddy single=True smf_options=verbose
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute boot
res = __salt__['cmd.run_all']('zoneadm {zone} boot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def reboot(zone, single=False, altinit=None, smf_options=None):
'''
Restart the zone. This is equivalent to a halt boot sequence.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.reboot dolores
salt '*' zoneadm.reboot teddy single=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute reboot
res = __salt__['cmd.run_all']('zoneadm {zone} reboot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def halt(zone):
'''
Halt the specified zone.
zone : string
name or uuid of the zone
.. note::
To cleanly shutdown the zone use the shutdown function.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.halt hector
'''
ret = {'status': True}
## halt zone
res = __salt__['cmd.run_all']('zoneadm {zone} halt'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def shutdown(zone, reboot=False, single=False, altinit=None, smf_options=None):
'''
Gracefully shutdown the specified zone.
zone : string
name or uuid of the zone
reboot : boolean
reboot zone after shutdown (equivalent of shutdown -i6 -g0 -y)
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.shutdown peter
salt '*' zoneadm.shutdown armistice reboot=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## shutdown zone
res = __salt__['cmd.run_all']('zoneadm {zone} shutdown{reboot}{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
reboot=' -r' if reboot else '',
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def detach(zone):
'''
Detach the specified zone.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.detach kissy
'''
ret = {'status': True}
## detach zone
res = __salt__['cmd.run_all']('zoneadm {zone} detach'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def attach(zone, force=False, brand_opts=None):
'''
Attach the specified zone.
zone : string
name of the zone
force : boolean
force the zone into the "installed" state with no validation
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.attach lawrence
salt '*' zoneadm.attach lawrence True
'''
ret = {'status': True}
## attach zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} attach{force}{brand_opts}'.format(
zone=zone,
force=' -F' if force else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def verify(zone):
'''
Check to make sure the configuration of the specified
zone can safely be installed on the machine.
zone : string
name of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.verify dolores
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} verify'.format(
zone=zone,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def move(zone, zonepath):
'''
Move zone to new zonepath.
zone : string
name or uuid of the zone
zonepath : string
new zonepath
CLI Example:
.. code-block:: bash
salt '*' zoneadm.move meave /sweetwater/meave
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm {zone} move {path}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
path=zonepath,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def uninstall(zone):
'''
Uninstall the specified zone from the system.
zone : string
name or uuid of the zone
.. warning::
The -F flag is always used to avoid the prompts when uninstalling.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.uninstall teddy
'''
ret = {'status': True}
## uninstall zone
res = __salt__['cmd.run_all']('zoneadm {zone} uninstall -F'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def install(zone, nodataset=False, brand_opts=None):
'''
Install the specified zone from the system.
zone : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.install dolores
salt '*' zoneadm.install teddy True
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} install{nodataset}{brand_opts}'.format(
zone=zone,
nodataset=' -x nodataset' if nodataset else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def clone(zone, source, snapshot=None):
'''
Install a zone by copying an existing installed zone.
zone : string
name of the zone
source : string
zone to clone from
snapshot : string
optional name of snapshot to use as source
CLI Example:
.. code-block:: bash
salt '*' zoneadm.clone clementine dolores
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} clone {snapshot}{source}'.format(
zone=zone,
source=source,
snapshot='-s {0} '.format(snapshot) if snapshot else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/modules/zoneadm.py
|
verify
|
python
|
def verify(zone):
'''
Check to make sure the configuration of the specified
zone can safely be installed on the machine.
zone : string
name of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.verify dolores
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} verify'.format(
zone=zone,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
|
Check to make sure the configuration of the specified
zone can safely be installed on the machine.
zone : string
name of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.verify dolores
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zoneadm.py#L397-L423
| null |
# -*- coding: utf-8 -*-
'''
Module for Solaris 10's zoneadm
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:platform: OmniOS,OpenIndiana,SmartOS,OpenSolaris,Solaris 10
.. versionadded:: 2017.7.0
.. warning::
Oracle Solaris 11's zoneadm is not supported by this module!
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.decorators
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'zoneadm'
# Function aliases
__func_alias__ = {
'list_zones': 'list'
}
@salt.utils.decorators.memoize
def _is_globalzone():
'''
Check if we are running in the globalzone
'''
if not __grains__['kernel'] == 'SunOS':
return False
zonename = __salt__['cmd.run_all']('zonename')
if zonename['retcode']:
return False
if zonename['stdout'] == 'global':
return True
return False
def _is_uuid(zone):
'''
Check if zone is actually a UUID
'''
return len(zone) == 36 and zone.index('-') == 8
def __virtual__():
'''
We are available if we are have zoneadm and are the global zone on
Solaris 10, OmniOS, OpenIndiana, OpenSolaris, or Smartos.
'''
if _is_globalzone() and salt.utils.path.which('zoneadm'):
if __grains__['os'] in ['OpenSolaris', 'SmartOS', 'OmniOS', 'OpenIndiana']:
return __virtualname__
elif __grains__['os'] == 'Oracle Solaris' and int(__grains__['osmajorrelease']) == 10:
return __virtualname__
return (
False,
'{0} module can only be loaded in a solaris globalzone.'.format(
__virtualname__
)
)
def list_zones(verbose=True, installed=False, configured=False, hide_global=True):
'''
List all zones
verbose : boolean
display additional zone information
installed : boolean
include installed zones in output
configured : boolean
include configured zones in output
hide_global : boolean
do not include global zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.list
'''
zones = {}
## fetch zones
header = 'zoneid:zonename:state:zonepath:uuid:brand:ip-type'.split(':')
zone_data = __salt__['cmd.run_all']('zoneadm list -p -c')
if zone_data['retcode'] == 0:
for zone in zone_data['stdout'].splitlines():
zone = zone.split(':')
# create zone_t
zone_t = {}
for i in range(0, len(header)):
zone_t[header[i]] = zone[i]
# skip if global and hide_global
if hide_global and zone_t['zonename'] == 'global':
continue
# skip installed and configured
if not installed and zone_t['state'] == 'installed':
continue
if not configured and zone_t['state'] == 'configured':
continue
# update dict
zones[zone_t['zonename']] = zone_t
del zones[zone_t['zonename']]['zonename']
return zones if verbose else sorted(zones.keys())
def boot(zone, single=False, altinit=None, smf_options=None):
'''
Boot (or activate) the specified zone.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.boot clementine
salt '*' zoneadm.boot maeve single=True
salt '*' zoneadm.boot teddy single=True smf_options=verbose
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute boot
res = __salt__['cmd.run_all']('zoneadm {zone} boot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def reboot(zone, single=False, altinit=None, smf_options=None):
'''
Restart the zone. This is equivalent to a halt boot sequence.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.reboot dolores
salt '*' zoneadm.reboot teddy single=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute reboot
res = __salt__['cmd.run_all']('zoneadm {zone} reboot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def halt(zone):
'''
Halt the specified zone.
zone : string
name or uuid of the zone
.. note::
To cleanly shutdown the zone use the shutdown function.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.halt hector
'''
ret = {'status': True}
## halt zone
res = __salt__['cmd.run_all']('zoneadm {zone} halt'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def shutdown(zone, reboot=False, single=False, altinit=None, smf_options=None):
'''
Gracefully shutdown the specified zone.
zone : string
name or uuid of the zone
reboot : boolean
reboot zone after shutdown (equivalent of shutdown -i6 -g0 -y)
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.shutdown peter
salt '*' zoneadm.shutdown armistice reboot=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## shutdown zone
res = __salt__['cmd.run_all']('zoneadm {zone} shutdown{reboot}{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
reboot=' -r' if reboot else '',
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def detach(zone):
'''
Detach the specified zone.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.detach kissy
'''
ret = {'status': True}
## detach zone
res = __salt__['cmd.run_all']('zoneadm {zone} detach'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def attach(zone, force=False, brand_opts=None):
'''
Attach the specified zone.
zone : string
name of the zone
force : boolean
force the zone into the "installed" state with no validation
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.attach lawrence
salt '*' zoneadm.attach lawrence True
'''
ret = {'status': True}
## attach zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} attach{force}{brand_opts}'.format(
zone=zone,
force=' -F' if force else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def ready(zone):
'''
Prepares a zone for running applications.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.ready clementine
'''
ret = {'status': True}
## ready zone
res = __salt__['cmd.run_all']('zoneadm {zone} ready'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def move(zone, zonepath):
'''
Move zone to new zonepath.
zone : string
name or uuid of the zone
zonepath : string
new zonepath
CLI Example:
.. code-block:: bash
salt '*' zoneadm.move meave /sweetwater/meave
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm {zone} move {path}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
path=zonepath,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def uninstall(zone):
'''
Uninstall the specified zone from the system.
zone : string
name or uuid of the zone
.. warning::
The -F flag is always used to avoid the prompts when uninstalling.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.uninstall teddy
'''
ret = {'status': True}
## uninstall zone
res = __salt__['cmd.run_all']('zoneadm {zone} uninstall -F'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def install(zone, nodataset=False, brand_opts=None):
'''
Install the specified zone from the system.
zone : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.install dolores
salt '*' zoneadm.install teddy True
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} install{nodataset}{brand_opts}'.format(
zone=zone,
nodataset=' -x nodataset' if nodataset else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def clone(zone, source, snapshot=None):
'''
Install a zone by copying an existing installed zone.
zone : string
name of the zone
source : string
zone to clone from
snapshot : string
optional name of snapshot to use as source
CLI Example:
.. code-block:: bash
salt '*' zoneadm.clone clementine dolores
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} clone {snapshot}{source}'.format(
zone=zone,
source=source,
snapshot='-s {0} '.format(snapshot) if snapshot else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/modules/zoneadm.py
|
move
|
python
|
def move(zone, zonepath):
'''
Move zone to new zonepath.
zone : string
name or uuid of the zone
zonepath : string
new zonepath
CLI Example:
.. code-block:: bash
salt '*' zoneadm.move meave /sweetwater/meave
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm {zone} move {path}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
path=zonepath,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
|
Move zone to new zonepath.
zone : string
name or uuid of the zone
zonepath : string
new zonepath
CLI Example:
.. code-block:: bash
salt '*' zoneadm.move meave /sweetwater/meave
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zoneadm.py#L426-L454
|
[
"def _is_uuid(zone):\n '''\n Check if zone is actually a UUID\n '''\n return len(zone) == 36 and zone.index('-') == 8\n"
] |
# -*- coding: utf-8 -*-
'''
Module for Solaris 10's zoneadm
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:platform: OmniOS,OpenIndiana,SmartOS,OpenSolaris,Solaris 10
.. versionadded:: 2017.7.0
.. warning::
Oracle Solaris 11's zoneadm is not supported by this module!
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.decorators
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'zoneadm'
# Function aliases
__func_alias__ = {
'list_zones': 'list'
}
@salt.utils.decorators.memoize
def _is_globalzone():
'''
Check if we are running in the globalzone
'''
if not __grains__['kernel'] == 'SunOS':
return False
zonename = __salt__['cmd.run_all']('zonename')
if zonename['retcode']:
return False
if zonename['stdout'] == 'global':
return True
return False
def _is_uuid(zone):
'''
Check if zone is actually a UUID
'''
return len(zone) == 36 and zone.index('-') == 8
def __virtual__():
'''
We are available if we are have zoneadm and are the global zone on
Solaris 10, OmniOS, OpenIndiana, OpenSolaris, or Smartos.
'''
if _is_globalzone() and salt.utils.path.which('zoneadm'):
if __grains__['os'] in ['OpenSolaris', 'SmartOS', 'OmniOS', 'OpenIndiana']:
return __virtualname__
elif __grains__['os'] == 'Oracle Solaris' and int(__grains__['osmajorrelease']) == 10:
return __virtualname__
return (
False,
'{0} module can only be loaded in a solaris globalzone.'.format(
__virtualname__
)
)
def list_zones(verbose=True, installed=False, configured=False, hide_global=True):
'''
List all zones
verbose : boolean
display additional zone information
installed : boolean
include installed zones in output
configured : boolean
include configured zones in output
hide_global : boolean
do not include global zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.list
'''
zones = {}
## fetch zones
header = 'zoneid:zonename:state:zonepath:uuid:brand:ip-type'.split(':')
zone_data = __salt__['cmd.run_all']('zoneadm list -p -c')
if zone_data['retcode'] == 0:
for zone in zone_data['stdout'].splitlines():
zone = zone.split(':')
# create zone_t
zone_t = {}
for i in range(0, len(header)):
zone_t[header[i]] = zone[i]
# skip if global and hide_global
if hide_global and zone_t['zonename'] == 'global':
continue
# skip installed and configured
if not installed and zone_t['state'] == 'installed':
continue
if not configured and zone_t['state'] == 'configured':
continue
# update dict
zones[zone_t['zonename']] = zone_t
del zones[zone_t['zonename']]['zonename']
return zones if verbose else sorted(zones.keys())
def boot(zone, single=False, altinit=None, smf_options=None):
'''
Boot (or activate) the specified zone.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.boot clementine
salt '*' zoneadm.boot maeve single=True
salt '*' zoneadm.boot teddy single=True smf_options=verbose
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute boot
res = __salt__['cmd.run_all']('zoneadm {zone} boot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def reboot(zone, single=False, altinit=None, smf_options=None):
'''
Restart the zone. This is equivalent to a halt boot sequence.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.reboot dolores
salt '*' zoneadm.reboot teddy single=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute reboot
res = __salt__['cmd.run_all']('zoneadm {zone} reboot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def halt(zone):
'''
Halt the specified zone.
zone : string
name or uuid of the zone
.. note::
To cleanly shutdown the zone use the shutdown function.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.halt hector
'''
ret = {'status': True}
## halt zone
res = __salt__['cmd.run_all']('zoneadm {zone} halt'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def shutdown(zone, reboot=False, single=False, altinit=None, smf_options=None):
'''
Gracefully shutdown the specified zone.
zone : string
name or uuid of the zone
reboot : boolean
reboot zone after shutdown (equivalent of shutdown -i6 -g0 -y)
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.shutdown peter
salt '*' zoneadm.shutdown armistice reboot=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## shutdown zone
res = __salt__['cmd.run_all']('zoneadm {zone} shutdown{reboot}{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
reboot=' -r' if reboot else '',
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def detach(zone):
'''
Detach the specified zone.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.detach kissy
'''
ret = {'status': True}
## detach zone
res = __salt__['cmd.run_all']('zoneadm {zone} detach'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def attach(zone, force=False, brand_opts=None):
'''
Attach the specified zone.
zone : string
name of the zone
force : boolean
force the zone into the "installed" state with no validation
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.attach lawrence
salt '*' zoneadm.attach lawrence True
'''
ret = {'status': True}
## attach zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} attach{force}{brand_opts}'.format(
zone=zone,
force=' -F' if force else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def ready(zone):
'''
Prepares a zone for running applications.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.ready clementine
'''
ret = {'status': True}
## ready zone
res = __salt__['cmd.run_all']('zoneadm {zone} ready'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def verify(zone):
'''
Check to make sure the configuration of the specified
zone can safely be installed on the machine.
zone : string
name of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.verify dolores
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} verify'.format(
zone=zone,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def uninstall(zone):
'''
Uninstall the specified zone from the system.
zone : string
name or uuid of the zone
.. warning::
The -F flag is always used to avoid the prompts when uninstalling.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.uninstall teddy
'''
ret = {'status': True}
## uninstall zone
res = __salt__['cmd.run_all']('zoneadm {zone} uninstall -F'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def install(zone, nodataset=False, brand_opts=None):
'''
Install the specified zone from the system.
zone : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.install dolores
salt '*' zoneadm.install teddy True
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} install{nodataset}{brand_opts}'.format(
zone=zone,
nodataset=' -x nodataset' if nodataset else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def clone(zone, source, snapshot=None):
'''
Install a zone by copying an existing installed zone.
zone : string
name of the zone
source : string
zone to clone from
snapshot : string
optional name of snapshot to use as source
CLI Example:
.. code-block:: bash
salt '*' zoneadm.clone clementine dolores
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} clone {snapshot}{source}'.format(
zone=zone,
source=source,
snapshot='-s {0} '.format(snapshot) if snapshot else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/modules/zoneadm.py
|
install
|
python
|
def install(zone, nodataset=False, brand_opts=None):
'''
Install the specified zone from the system.
zone : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.install dolores
salt '*' zoneadm.install teddy True
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} install{nodataset}{brand_opts}'.format(
zone=zone,
nodataset=' -x nodataset' if nodataset else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
|
Install the specified zone from the system.
zone : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.install dolores
salt '*' zoneadm.install teddy True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zoneadm.py#L488-L520
| null |
# -*- coding: utf-8 -*-
'''
Module for Solaris 10's zoneadm
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:platform: OmniOS,OpenIndiana,SmartOS,OpenSolaris,Solaris 10
.. versionadded:: 2017.7.0
.. warning::
Oracle Solaris 11's zoneadm is not supported by this module!
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.decorators
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'zoneadm'
# Function aliases
__func_alias__ = {
'list_zones': 'list'
}
@salt.utils.decorators.memoize
def _is_globalzone():
'''
Check if we are running in the globalzone
'''
if not __grains__['kernel'] == 'SunOS':
return False
zonename = __salt__['cmd.run_all']('zonename')
if zonename['retcode']:
return False
if zonename['stdout'] == 'global':
return True
return False
def _is_uuid(zone):
'''
Check if zone is actually a UUID
'''
return len(zone) == 36 and zone.index('-') == 8
def __virtual__():
'''
We are available if we are have zoneadm and are the global zone on
Solaris 10, OmniOS, OpenIndiana, OpenSolaris, or Smartos.
'''
if _is_globalzone() and salt.utils.path.which('zoneadm'):
if __grains__['os'] in ['OpenSolaris', 'SmartOS', 'OmniOS', 'OpenIndiana']:
return __virtualname__
elif __grains__['os'] == 'Oracle Solaris' and int(__grains__['osmajorrelease']) == 10:
return __virtualname__
return (
False,
'{0} module can only be loaded in a solaris globalzone.'.format(
__virtualname__
)
)
def list_zones(verbose=True, installed=False, configured=False, hide_global=True):
'''
List all zones
verbose : boolean
display additional zone information
installed : boolean
include installed zones in output
configured : boolean
include configured zones in output
hide_global : boolean
do not include global zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.list
'''
zones = {}
## fetch zones
header = 'zoneid:zonename:state:zonepath:uuid:brand:ip-type'.split(':')
zone_data = __salt__['cmd.run_all']('zoneadm list -p -c')
if zone_data['retcode'] == 0:
for zone in zone_data['stdout'].splitlines():
zone = zone.split(':')
# create zone_t
zone_t = {}
for i in range(0, len(header)):
zone_t[header[i]] = zone[i]
# skip if global and hide_global
if hide_global and zone_t['zonename'] == 'global':
continue
# skip installed and configured
if not installed and zone_t['state'] == 'installed':
continue
if not configured and zone_t['state'] == 'configured':
continue
# update dict
zones[zone_t['zonename']] = zone_t
del zones[zone_t['zonename']]['zonename']
return zones if verbose else sorted(zones.keys())
def boot(zone, single=False, altinit=None, smf_options=None):
'''
Boot (or activate) the specified zone.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.boot clementine
salt '*' zoneadm.boot maeve single=True
salt '*' zoneadm.boot teddy single=True smf_options=verbose
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute boot
res = __salt__['cmd.run_all']('zoneadm {zone} boot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def reboot(zone, single=False, altinit=None, smf_options=None):
'''
Restart the zone. This is equivalent to a halt boot sequence.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.reboot dolores
salt '*' zoneadm.reboot teddy single=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute reboot
res = __salt__['cmd.run_all']('zoneadm {zone} reboot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def halt(zone):
'''
Halt the specified zone.
zone : string
name or uuid of the zone
.. note::
To cleanly shutdown the zone use the shutdown function.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.halt hector
'''
ret = {'status': True}
## halt zone
res = __salt__['cmd.run_all']('zoneadm {zone} halt'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def shutdown(zone, reboot=False, single=False, altinit=None, smf_options=None):
'''
Gracefully shutdown the specified zone.
zone : string
name or uuid of the zone
reboot : boolean
reboot zone after shutdown (equivalent of shutdown -i6 -g0 -y)
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.shutdown peter
salt '*' zoneadm.shutdown armistice reboot=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## shutdown zone
res = __salt__['cmd.run_all']('zoneadm {zone} shutdown{reboot}{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
reboot=' -r' if reboot else '',
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def detach(zone):
'''
Detach the specified zone.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.detach kissy
'''
ret = {'status': True}
## detach zone
res = __salt__['cmd.run_all']('zoneadm {zone} detach'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def attach(zone, force=False, brand_opts=None):
'''
Attach the specified zone.
zone : string
name of the zone
force : boolean
force the zone into the "installed" state with no validation
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.attach lawrence
salt '*' zoneadm.attach lawrence True
'''
ret = {'status': True}
## attach zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} attach{force}{brand_opts}'.format(
zone=zone,
force=' -F' if force else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def ready(zone):
'''
Prepares a zone for running applications.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.ready clementine
'''
ret = {'status': True}
## ready zone
res = __salt__['cmd.run_all']('zoneadm {zone} ready'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def verify(zone):
'''
Check to make sure the configuration of the specified
zone can safely be installed on the machine.
zone : string
name of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.verify dolores
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} verify'.format(
zone=zone,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def move(zone, zonepath):
'''
Move zone to new zonepath.
zone : string
name or uuid of the zone
zonepath : string
new zonepath
CLI Example:
.. code-block:: bash
salt '*' zoneadm.move meave /sweetwater/meave
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm {zone} move {path}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
path=zonepath,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def uninstall(zone):
'''
Uninstall the specified zone from the system.
zone : string
name or uuid of the zone
.. warning::
The -F flag is always used to avoid the prompts when uninstalling.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.uninstall teddy
'''
ret = {'status': True}
## uninstall zone
res = __salt__['cmd.run_all']('zoneadm {zone} uninstall -F'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def clone(zone, source, snapshot=None):
'''
Install a zone by copying an existing installed zone.
zone : string
name of the zone
source : string
zone to clone from
snapshot : string
optional name of snapshot to use as source
CLI Example:
.. code-block:: bash
salt '*' zoneadm.clone clementine dolores
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} clone {snapshot}{source}'.format(
zone=zone,
source=source,
snapshot='-s {0} '.format(snapshot) if snapshot else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/modules/zoneadm.py
|
clone
|
python
|
def clone(zone, source, snapshot=None):
'''
Install a zone by copying an existing installed zone.
zone : string
name of the zone
source : string
zone to clone from
snapshot : string
optional name of snapshot to use as source
CLI Example:
.. code-block:: bash
salt '*' zoneadm.clone clementine dolores
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} clone {snapshot}{source}'.format(
zone=zone,
source=source,
snapshot='-s {0} '.format(snapshot) if snapshot else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
|
Install a zone by copying an existing installed zone.
zone : string
name of the zone
source : string
zone to clone from
snapshot : string
optional name of snapshot to use as source
CLI Example:
.. code-block:: bash
salt '*' zoneadm.clone clementine dolores
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zoneadm.py#L523-L554
| null |
# -*- coding: utf-8 -*-
'''
Module for Solaris 10's zoneadm
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:platform: OmniOS,OpenIndiana,SmartOS,OpenSolaris,Solaris 10
.. versionadded:: 2017.7.0
.. warning::
Oracle Solaris 11's zoneadm is not supported by this module!
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.decorators
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'zoneadm'
# Function aliases
__func_alias__ = {
'list_zones': 'list'
}
@salt.utils.decorators.memoize
def _is_globalzone():
'''
Check if we are running in the globalzone
'''
if not __grains__['kernel'] == 'SunOS':
return False
zonename = __salt__['cmd.run_all']('zonename')
if zonename['retcode']:
return False
if zonename['stdout'] == 'global':
return True
return False
def _is_uuid(zone):
'''
Check if zone is actually a UUID
'''
return len(zone) == 36 and zone.index('-') == 8
def __virtual__():
'''
We are available if we are have zoneadm and are the global zone on
Solaris 10, OmniOS, OpenIndiana, OpenSolaris, or Smartos.
'''
if _is_globalzone() and salt.utils.path.which('zoneadm'):
if __grains__['os'] in ['OpenSolaris', 'SmartOS', 'OmniOS', 'OpenIndiana']:
return __virtualname__
elif __grains__['os'] == 'Oracle Solaris' and int(__grains__['osmajorrelease']) == 10:
return __virtualname__
return (
False,
'{0} module can only be loaded in a solaris globalzone.'.format(
__virtualname__
)
)
def list_zones(verbose=True, installed=False, configured=False, hide_global=True):
'''
List all zones
verbose : boolean
display additional zone information
installed : boolean
include installed zones in output
configured : boolean
include configured zones in output
hide_global : boolean
do not include global zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.list
'''
zones = {}
## fetch zones
header = 'zoneid:zonename:state:zonepath:uuid:brand:ip-type'.split(':')
zone_data = __salt__['cmd.run_all']('zoneadm list -p -c')
if zone_data['retcode'] == 0:
for zone in zone_data['stdout'].splitlines():
zone = zone.split(':')
# create zone_t
zone_t = {}
for i in range(0, len(header)):
zone_t[header[i]] = zone[i]
# skip if global and hide_global
if hide_global and zone_t['zonename'] == 'global':
continue
# skip installed and configured
if not installed and zone_t['state'] == 'installed':
continue
if not configured and zone_t['state'] == 'configured':
continue
# update dict
zones[zone_t['zonename']] = zone_t
del zones[zone_t['zonename']]['zonename']
return zones if verbose else sorted(zones.keys())
def boot(zone, single=False, altinit=None, smf_options=None):
'''
Boot (or activate) the specified zone.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.boot clementine
salt '*' zoneadm.boot maeve single=True
salt '*' zoneadm.boot teddy single=True smf_options=verbose
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute boot
res = __salt__['cmd.run_all']('zoneadm {zone} boot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def reboot(zone, single=False, altinit=None, smf_options=None):
'''
Restart the zone. This is equivalent to a halt boot sequence.
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.reboot dolores
salt '*' zoneadm.reboot teddy single=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## execute reboot
res = __salt__['cmd.run_all']('zoneadm {zone} reboot{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def halt(zone):
'''
Halt the specified zone.
zone : string
name or uuid of the zone
.. note::
To cleanly shutdown the zone use the shutdown function.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.halt hector
'''
ret = {'status': True}
## halt zone
res = __salt__['cmd.run_all']('zoneadm {zone} halt'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def shutdown(zone, reboot=False, single=False, altinit=None, smf_options=None):
'''
Gracefully shutdown the specified zone.
zone : string
name or uuid of the zone
reboot : boolean
reboot zone after shutdown (equivalent of shutdown -i6 -g0 -y)
single : boolean
boots only to milestone svc:/milestone/single-user:default.
altinit : string
valid path to an alternative executable to be the primordial process.
smf_options : string
include two categories of options to control booting behavior of
the service management facility: recovery options and messages options.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.shutdown peter
salt '*' zoneadm.shutdown armistice reboot=True
'''
ret = {'status': True}
## build boot_options
boot_options = ''
if single:
boot_options = '-s {0}'.format(boot_options)
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = '-i {0} {1}'.format(altinit, boot_options)
if smf_options:
boot_options = '-m {0} {1}'.format(smf_options, boot_options)
if boot_options != '':
boot_options = ' -- {0}'.format(boot_options.strip())
## shutdown zone
res = __salt__['cmd.run_all']('zoneadm {zone} shutdown{reboot}{boot_opts}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
reboot=' -r' if reboot else '',
boot_opts=boot_options,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def detach(zone):
'''
Detach the specified zone.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.detach kissy
'''
ret = {'status': True}
## detach zone
res = __salt__['cmd.run_all']('zoneadm {zone} detach'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def attach(zone, force=False, brand_opts=None):
'''
Attach the specified zone.
zone : string
name of the zone
force : boolean
force the zone into the "installed" state with no validation
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.attach lawrence
salt '*' zoneadm.attach lawrence True
'''
ret = {'status': True}
## attach zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} attach{force}{brand_opts}'.format(
zone=zone,
force=' -F' if force else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def ready(zone):
'''
Prepares a zone for running applications.
zone : string
name or uuid of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.ready clementine
'''
ret = {'status': True}
## ready zone
res = __salt__['cmd.run_all']('zoneadm {zone} ready'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def verify(zone):
'''
Check to make sure the configuration of the specified
zone can safely be installed on the machine.
zone : string
name of the zone
CLI Example:
.. code-block:: bash
salt '*' zoneadm.verify dolores
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} verify'.format(
zone=zone,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def move(zone, zonepath):
'''
Move zone to new zonepath.
zone : string
name or uuid of the zone
zonepath : string
new zonepath
CLI Example:
.. code-block:: bash
salt '*' zoneadm.move meave /sweetwater/meave
'''
ret = {'status': True}
## verify zone
res = __salt__['cmd.run_all']('zoneadm {zone} move {path}'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
path=zonepath,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def uninstall(zone):
'''
Uninstall the specified zone from the system.
zone : string
name or uuid of the zone
.. warning::
The -F flag is always used to avoid the prompts when uninstalling.
CLI Example:
.. code-block:: bash
salt '*' zoneadm.uninstall teddy
'''
ret = {'status': True}
## uninstall zone
res = __salt__['cmd.run_all']('zoneadm {zone} uninstall -F'.format(
zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
def install(zone, nodataset=False, brand_opts=None):
'''
Install the specified zone from the system.
zone : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : string
brand specific options to pass
CLI Example:
.. code-block:: bash
salt '*' zoneadm.install dolores
salt '*' zoneadm.install teddy True
'''
ret = {'status': True}
## install zone
res = __salt__['cmd.run_all']('zoneadm -z {zone} install{nodataset}{brand_opts}'.format(
zone=zone,
nodataset=' -x nodataset' if nodataset else '',
brand_opts=' {0}'.format(brand_opts) if brand_opts else '',
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
ret['message'] = ret['message'].replace('zoneadm: ', '')
if ret['message'] == '':
del ret['message']
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/fileserver/azurefs.py
|
find_file
|
python
|
def find_file(path, saltenv='base', **kwargs):
'''
Search the environment for the relative path
'''
fnd = {'path': '',
'rel': ''}
for container in __opts__.get('azurefs', []):
if container.get('saltenv', 'base') != saltenv:
continue
full = os.path.join(_get_container_path(container), path)
if os.path.isfile(full) and not salt.fileserver.is_file_ignored(
__opts__, path):
fnd['path'] = full
fnd['rel'] = path
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(full))
except Exception:
pass
return fnd
return fnd
|
Search the environment for the relative path
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/azurefs.py#L102-L133
|
[
"def is_file_ignored(opts, fname):\n '''\n If file_ignore_regex or file_ignore_glob were given in config,\n compare the given file path against all of them and return True\n on the first match.\n '''\n if opts['file_ignore_regex']:\n for regex in opts['file_ignore_regex']:\n if re.search(regex, fname):\n log.debug(\n 'File matching file_ignore_regex. Skipping: %s',\n fname\n )\n return True\n\n if opts['file_ignore_glob']:\n for glob in opts['file_ignore_glob']:\n if fnmatch.fnmatch(fname, glob):\n log.debug(\n 'File matching file_ignore_glob. Skipping: %s',\n fname\n )\n return True\n return False\n",
"def _get_container_path(container):\n '''\n Get the cache path for the container in question\n\n Cache paths are generate by combining the account name, container name,\n and saltenv, separated by underscores\n '''\n root = os.path.join(__opts__['cachedir'], 'azurefs')\n container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),\n container.get('container_name', ''),\n container.get('saltenv', 'base'))\n return os.path.join(root, container_dir)\n"
] |
# -*- coding: utf-8 -*-
'''
The backend for serving files from the Azure blob storage service.
.. versionadded:: 2015.8.0
To enable, add ``azurefs`` to the :conf_master:`fileserver_backend` option in
the Master config file.
.. code-block:: yaml
fileserver_backend:
- azurefs
Starting in Salt 2018.3.0, this fileserver requires the standalone Azure
Storage SDK for Python. Theoretically any version >= v0.20.0 should work, but
it was developed against the v0.33.0 version.
Each storage container will be mapped to an environment. By default, containers
will be mapped to the ``base`` environment. You can override this behavior with
the ``saltenv`` configuration option. You can have an unlimited number of
storage containers, and can have a storage container serve multiple
environments, or have multiple storage containers mapped to the same
environment. Normal first-found rules apply, and storage containers are
searched in the order they are defined.
You must have either an account_key or a sas_token defined for each container,
if it is private. If you use a sas_token, it must have READ and LIST
permissions.
.. code-block:: yaml
azurefs:
- account_name: my_storage
account_key: 'fNH9cRp0+qVIVYZ+5rnZAhHc9ycOUcJnHtzpfOr0W0sxrtL2KVLuMe1xDfLwmfed+JJInZaEdWVCPHD4d/oqeA=='
container_name: my_container
- account_name: my_storage
sas_token: 'ss=b&sp=&sv=2015-07-08&sig=cohxXabx8FQdXsSEHyUXMjsSfNH2tZ2OB97Ou44pkRE%3D&srt=co&se=2017-04-18T21%3A38%3A01Z'
container_name: my_dev_container
saltenv: dev
- account_name: my_storage
container_name: my_public_container
.. note::
Do not include the leading ? for sas_token if generated from the web
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import logging
import os
import shutil
# Import salt libs
import salt.fileserver
import salt.utils.files
import salt.utils.gzip_util
import salt.utils.hashutils
import salt.utils.json
import salt.utils.path
import salt.utils.stringutils
from salt.utils.versions import LooseVersion
try:
import azure.storage
if LooseVersion(azure.storage.__version__) < LooseVersion('0.20.0'):
raise ImportError('azure.storage.__version__ must be >= 0.20.0')
HAS_AZURE = True
except (ImportError, AttributeError):
HAS_AZURE = False
# Import third party libs
from salt.ext import six
__virtualname__ = 'azurefs'
log = logging.getLogger()
def __virtual__():
'''
Only load if defined in fileserver_backend and azure.storage is present
'''
if __virtualname__ not in __opts__['fileserver_backend']:
return False
if not HAS_AZURE:
return False
if 'azurefs' not in __opts__:
return False
if not _validate_config():
return False
return True
def envs():
'''
Each container configuration can have an environment setting, or defaults
to base
'''
saltenvs = []
for container in __opts__.get('azurefs', []):
saltenvs.append(container.get('saltenv', 'base'))
# Remove duplicates
return list(set(saltenvs))
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
ret = {'data': '',
'dest': ''}
required_load_keys = ('path', 'loc', 'saltenv')
if not all(x in load for x in required_load_keys):
log.debug(
'Not all of the required keys present in payload. Missing: %s',
', '.join(required_load_keys.difference(load))
)
return ret
if not fnd['path']:
return ret
ret['dest'] = fnd['rel']
gzip = load.get('gzip', None)
fpath = os.path.normpath(fnd['path'])
with salt.utils.files.fopen(fpath, 'rb') as fp_:
fp_.seek(load['loc'])
data = fp_.read(__opts__['file_buffer_size'])
if data and six.PY3 and not salt.utils.files.is_binary(fpath):
data = data.decode(__salt_system_encoding__)
if gzip and data:
data = salt.utils.gzip_util.compress(data, gzip)
ret['gzip'] = gzip
ret['data'] = data
return ret
def update():
'''
Update caches of the storage containers.
Compares the md5 of the files on disk to the md5 of the blobs in the
container, and only updates if necessary.
Also processes deletions by walking the container caches and comparing
with the list of blobs in the container
'''
for container in __opts__['azurefs']:
path = _get_container_path(container)
try:
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
shutil.rmtree(path)
os.makedirs(path)
except Exception as exc:
log.exception('Error occurred creating cache directory for azurefs')
continue
blob_service = _get_container_service(container)
name = container['container_name']
try:
blob_list = blob_service.list_blobs(name)
except Exception as exc:
log.exception('Error occurred fetching blob list for azurefs')
continue
# Walk the cache directory searching for deletions
blob_names = [blob.name for blob in blob_list]
blob_set = set(blob_names)
for root, dirs, files in salt.utils.path.os_walk(path):
for f in files:
fname = os.path.join(root, f)
relpath = os.path.relpath(fname, path)
if relpath not in blob_set:
salt.fileserver.wait_lock(fname + '.lk', fname)
try:
os.unlink(fname)
except Exception:
pass
if not dirs and not files:
shutil.rmtree(root)
for blob in blob_list:
fname = os.path.join(path, blob.name)
update = False
if os.path.exists(fname):
# File exists, check the hashes
source_md5 = blob.properties.content_settings.content_md5
local_md5 = base64.b64encode(salt.utils.hashutils.get_hash(fname, 'md5').decode('hex'))
if local_md5 != source_md5:
update = True
else:
update = True
if update:
if not os.path.exists(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
# Lock writes
lk_fn = fname + '.lk'
salt.fileserver.wait_lock(lk_fn, fname)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
try:
blob_service.get_blob_to_path(name, blob.name, fname)
except Exception as exc:
log.exception('Error occurred fetching blob from azurefs')
continue
# Unlock writes
try:
os.unlink(lk_fn)
except Exception:
pass
# Write out file list
container_list = path + '.list'
lk_fn = container_list + '.lk'
salt.fileserver.wait_lock(lk_fn, container_list)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
with salt.utils.files.fopen(container_list, 'w') as fp_:
salt.utils.json.dump(blob_names, fp_)
try:
os.unlink(lk_fn)
except Exception:
pass
try:
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
shutil.rmtree(hash_cachedir)
except Exception:
log.exception('Problem occurred trying to invalidate hash cach for azurefs')
def file_hash(load, fnd):
'''
Return a file hash based on the hash type set in the master config
'''
if not all(x in load for x in ('path', 'saltenv')):
return '', None
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
hashdest = salt.utils.path.join(hash_cachedir,
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
if not os.path.exists(os.path.dirname(hashdest)):
os.makedirs(os.path.dirname(hashdest))
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(ret['hsum']))
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret
def file_list(load):
'''
Return a list of all files in a specified environment
'''
ret = set()
try:
for container in __opts__['azurefs']:
if container.get('saltenv', 'base') != load['saltenv']:
continue
container_list = _get_container_path(container) + '.list'
lk = container_list + '.lk'
salt.fileserver.wait_lock(lk, container_list, 5)
if not os.path.exists(container_list):
continue
with salt.utils.files.fopen(container_list, 'r') as fp_:
ret.update(set(salt.utils.json.load(fp_)))
except Exception as exc:
log.error('azurefs: an error ocurred retrieving file lists. '
'It should be resolved next time the fileserver '
'updates. Please do not manually modify the azurefs '
'cache directory.')
return list(ret)
def dir_list(load):
'''
Return a list of all directories in a specified environment
'''
ret = set()
files = file_list(load)
for f in files:
dirname = f
while dirname:
dirname = os.path.dirname(dirname)
if dirname:
ret.add(dirname)
return list(ret)
def _get_container_path(container):
'''
Get the cache path for the container in question
Cache paths are generate by combining the account name, container name,
and saltenv, separated by underscores
'''
root = os.path.join(__opts__['cachedir'], 'azurefs')
container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),
container.get('container_name', ''),
container.get('saltenv', 'base'))
return os.path.join(root, container_dir)
def _get_container_service(container):
'''
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order
'''
if 'account_key' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])
elif 'sas_token' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])
else:
account = azure.storage.CloudStorageAccount(container['account_name'])
blob_service = account.create_block_blob_service()
return blob_service
def _validate_config():
'''
Validate azurefs config, return False if it doesn't validate
'''
if not isinstance(__opts__['azurefs'], list):
log.error('azurefs configuration is not formed as a list, skipping azurefs')
return False
for container in __opts__['azurefs']:
if not isinstance(container, dict):
log.error(
'One or more entries in the azurefs configuration list are '
'not formed as a dict. Skipping azurefs: %s', container
)
return False
if 'account_name' not in container or 'container_name' not in container:
log.error(
'An azurefs container configuration is missing either an '
'account_name or a container_name: %s', container
)
return False
return True
|
saltstack/salt
|
salt/fileserver/azurefs.py
|
envs
|
python
|
def envs():
'''
Each container configuration can have an environment setting, or defaults
to base
'''
saltenvs = []
for container in __opts__.get('azurefs', []):
saltenvs.append(container.get('saltenv', 'base'))
# Remove duplicates
return list(set(saltenvs))
|
Each container configuration can have an environment setting, or defaults
to base
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/azurefs.py#L136-L145
| null |
# -*- coding: utf-8 -*-
'''
The backend for serving files from the Azure blob storage service.
.. versionadded:: 2015.8.0
To enable, add ``azurefs`` to the :conf_master:`fileserver_backend` option in
the Master config file.
.. code-block:: yaml
fileserver_backend:
- azurefs
Starting in Salt 2018.3.0, this fileserver requires the standalone Azure
Storage SDK for Python. Theoretically any version >= v0.20.0 should work, but
it was developed against the v0.33.0 version.
Each storage container will be mapped to an environment. By default, containers
will be mapped to the ``base`` environment. You can override this behavior with
the ``saltenv`` configuration option. You can have an unlimited number of
storage containers, and can have a storage container serve multiple
environments, or have multiple storage containers mapped to the same
environment. Normal first-found rules apply, and storage containers are
searched in the order they are defined.
You must have either an account_key or a sas_token defined for each container,
if it is private. If you use a sas_token, it must have READ and LIST
permissions.
.. code-block:: yaml
azurefs:
- account_name: my_storage
account_key: 'fNH9cRp0+qVIVYZ+5rnZAhHc9ycOUcJnHtzpfOr0W0sxrtL2KVLuMe1xDfLwmfed+JJInZaEdWVCPHD4d/oqeA=='
container_name: my_container
- account_name: my_storage
sas_token: 'ss=b&sp=&sv=2015-07-08&sig=cohxXabx8FQdXsSEHyUXMjsSfNH2tZ2OB97Ou44pkRE%3D&srt=co&se=2017-04-18T21%3A38%3A01Z'
container_name: my_dev_container
saltenv: dev
- account_name: my_storage
container_name: my_public_container
.. note::
Do not include the leading ? for sas_token if generated from the web
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import logging
import os
import shutil
# Import salt libs
import salt.fileserver
import salt.utils.files
import salt.utils.gzip_util
import salt.utils.hashutils
import salt.utils.json
import salt.utils.path
import salt.utils.stringutils
from salt.utils.versions import LooseVersion
try:
import azure.storage
if LooseVersion(azure.storage.__version__) < LooseVersion('0.20.0'):
raise ImportError('azure.storage.__version__ must be >= 0.20.0')
HAS_AZURE = True
except (ImportError, AttributeError):
HAS_AZURE = False
# Import third party libs
from salt.ext import six
__virtualname__ = 'azurefs'
log = logging.getLogger()
def __virtual__():
'''
Only load if defined in fileserver_backend and azure.storage is present
'''
if __virtualname__ not in __opts__['fileserver_backend']:
return False
if not HAS_AZURE:
return False
if 'azurefs' not in __opts__:
return False
if not _validate_config():
return False
return True
def find_file(path, saltenv='base', **kwargs):
'''
Search the environment for the relative path
'''
fnd = {'path': '',
'rel': ''}
for container in __opts__.get('azurefs', []):
if container.get('saltenv', 'base') != saltenv:
continue
full = os.path.join(_get_container_path(container), path)
if os.path.isfile(full) and not salt.fileserver.is_file_ignored(
__opts__, path):
fnd['path'] = full
fnd['rel'] = path
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(full))
except Exception:
pass
return fnd
return fnd
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
ret = {'data': '',
'dest': ''}
required_load_keys = ('path', 'loc', 'saltenv')
if not all(x in load for x in required_load_keys):
log.debug(
'Not all of the required keys present in payload. Missing: %s',
', '.join(required_load_keys.difference(load))
)
return ret
if not fnd['path']:
return ret
ret['dest'] = fnd['rel']
gzip = load.get('gzip', None)
fpath = os.path.normpath(fnd['path'])
with salt.utils.files.fopen(fpath, 'rb') as fp_:
fp_.seek(load['loc'])
data = fp_.read(__opts__['file_buffer_size'])
if data and six.PY3 and not salt.utils.files.is_binary(fpath):
data = data.decode(__salt_system_encoding__)
if gzip and data:
data = salt.utils.gzip_util.compress(data, gzip)
ret['gzip'] = gzip
ret['data'] = data
return ret
def update():
'''
Update caches of the storage containers.
Compares the md5 of the files on disk to the md5 of the blobs in the
container, and only updates if necessary.
Also processes deletions by walking the container caches and comparing
with the list of blobs in the container
'''
for container in __opts__['azurefs']:
path = _get_container_path(container)
try:
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
shutil.rmtree(path)
os.makedirs(path)
except Exception as exc:
log.exception('Error occurred creating cache directory for azurefs')
continue
blob_service = _get_container_service(container)
name = container['container_name']
try:
blob_list = blob_service.list_blobs(name)
except Exception as exc:
log.exception('Error occurred fetching blob list for azurefs')
continue
# Walk the cache directory searching for deletions
blob_names = [blob.name for blob in blob_list]
blob_set = set(blob_names)
for root, dirs, files in salt.utils.path.os_walk(path):
for f in files:
fname = os.path.join(root, f)
relpath = os.path.relpath(fname, path)
if relpath not in blob_set:
salt.fileserver.wait_lock(fname + '.lk', fname)
try:
os.unlink(fname)
except Exception:
pass
if not dirs and not files:
shutil.rmtree(root)
for blob in blob_list:
fname = os.path.join(path, blob.name)
update = False
if os.path.exists(fname):
# File exists, check the hashes
source_md5 = blob.properties.content_settings.content_md5
local_md5 = base64.b64encode(salt.utils.hashutils.get_hash(fname, 'md5').decode('hex'))
if local_md5 != source_md5:
update = True
else:
update = True
if update:
if not os.path.exists(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
# Lock writes
lk_fn = fname + '.lk'
salt.fileserver.wait_lock(lk_fn, fname)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
try:
blob_service.get_blob_to_path(name, blob.name, fname)
except Exception as exc:
log.exception('Error occurred fetching blob from azurefs')
continue
# Unlock writes
try:
os.unlink(lk_fn)
except Exception:
pass
# Write out file list
container_list = path + '.list'
lk_fn = container_list + '.lk'
salt.fileserver.wait_lock(lk_fn, container_list)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
with salt.utils.files.fopen(container_list, 'w') as fp_:
salt.utils.json.dump(blob_names, fp_)
try:
os.unlink(lk_fn)
except Exception:
pass
try:
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
shutil.rmtree(hash_cachedir)
except Exception:
log.exception('Problem occurred trying to invalidate hash cach for azurefs')
def file_hash(load, fnd):
'''
Return a file hash based on the hash type set in the master config
'''
if not all(x in load for x in ('path', 'saltenv')):
return '', None
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
hashdest = salt.utils.path.join(hash_cachedir,
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
if not os.path.exists(os.path.dirname(hashdest)):
os.makedirs(os.path.dirname(hashdest))
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(ret['hsum']))
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret
def file_list(load):
'''
Return a list of all files in a specified environment
'''
ret = set()
try:
for container in __opts__['azurefs']:
if container.get('saltenv', 'base') != load['saltenv']:
continue
container_list = _get_container_path(container) + '.list'
lk = container_list + '.lk'
salt.fileserver.wait_lock(lk, container_list, 5)
if not os.path.exists(container_list):
continue
with salt.utils.files.fopen(container_list, 'r') as fp_:
ret.update(set(salt.utils.json.load(fp_)))
except Exception as exc:
log.error('azurefs: an error ocurred retrieving file lists. '
'It should be resolved next time the fileserver '
'updates. Please do not manually modify the azurefs '
'cache directory.')
return list(ret)
def dir_list(load):
'''
Return a list of all directories in a specified environment
'''
ret = set()
files = file_list(load)
for f in files:
dirname = f
while dirname:
dirname = os.path.dirname(dirname)
if dirname:
ret.add(dirname)
return list(ret)
def _get_container_path(container):
'''
Get the cache path for the container in question
Cache paths are generate by combining the account name, container name,
and saltenv, separated by underscores
'''
root = os.path.join(__opts__['cachedir'], 'azurefs')
container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),
container.get('container_name', ''),
container.get('saltenv', 'base'))
return os.path.join(root, container_dir)
def _get_container_service(container):
'''
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order
'''
if 'account_key' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])
elif 'sas_token' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])
else:
account = azure.storage.CloudStorageAccount(container['account_name'])
blob_service = account.create_block_blob_service()
return blob_service
def _validate_config():
'''
Validate azurefs config, return False if it doesn't validate
'''
if not isinstance(__opts__['azurefs'], list):
log.error('azurefs configuration is not formed as a list, skipping azurefs')
return False
for container in __opts__['azurefs']:
if not isinstance(container, dict):
log.error(
'One or more entries in the azurefs configuration list are '
'not formed as a dict. Skipping azurefs: %s', container
)
return False
if 'account_name' not in container or 'container_name' not in container:
log.error(
'An azurefs container configuration is missing either an '
'account_name or a container_name: %s', container
)
return False
return True
|
saltstack/salt
|
salt/fileserver/azurefs.py
|
serve_file
|
python
|
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
ret = {'data': '',
'dest': ''}
required_load_keys = ('path', 'loc', 'saltenv')
if not all(x in load for x in required_load_keys):
log.debug(
'Not all of the required keys present in payload. Missing: %s',
', '.join(required_load_keys.difference(load))
)
return ret
if not fnd['path']:
return ret
ret['dest'] = fnd['rel']
gzip = load.get('gzip', None)
fpath = os.path.normpath(fnd['path'])
with salt.utils.files.fopen(fpath, 'rb') as fp_:
fp_.seek(load['loc'])
data = fp_.read(__opts__['file_buffer_size'])
if data and six.PY3 and not salt.utils.files.is_binary(fpath):
data = data.decode(__salt_system_encoding__)
if gzip and data:
data = salt.utils.gzip_util.compress(data, gzip)
ret['gzip'] = gzip
ret['data'] = data
return ret
|
Return a chunk from a file based on the data received
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/azurefs.py#L148-L175
|
[
"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"
] |
# -*- coding: utf-8 -*-
'''
The backend for serving files from the Azure blob storage service.
.. versionadded:: 2015.8.0
To enable, add ``azurefs`` to the :conf_master:`fileserver_backend` option in
the Master config file.
.. code-block:: yaml
fileserver_backend:
- azurefs
Starting in Salt 2018.3.0, this fileserver requires the standalone Azure
Storage SDK for Python. Theoretically any version >= v0.20.0 should work, but
it was developed against the v0.33.0 version.
Each storage container will be mapped to an environment. By default, containers
will be mapped to the ``base`` environment. You can override this behavior with
the ``saltenv`` configuration option. You can have an unlimited number of
storage containers, and can have a storage container serve multiple
environments, or have multiple storage containers mapped to the same
environment. Normal first-found rules apply, and storage containers are
searched in the order they are defined.
You must have either an account_key or a sas_token defined for each container,
if it is private. If you use a sas_token, it must have READ and LIST
permissions.
.. code-block:: yaml
azurefs:
- account_name: my_storage
account_key: 'fNH9cRp0+qVIVYZ+5rnZAhHc9ycOUcJnHtzpfOr0W0sxrtL2KVLuMe1xDfLwmfed+JJInZaEdWVCPHD4d/oqeA=='
container_name: my_container
- account_name: my_storage
sas_token: 'ss=b&sp=&sv=2015-07-08&sig=cohxXabx8FQdXsSEHyUXMjsSfNH2tZ2OB97Ou44pkRE%3D&srt=co&se=2017-04-18T21%3A38%3A01Z'
container_name: my_dev_container
saltenv: dev
- account_name: my_storage
container_name: my_public_container
.. note::
Do not include the leading ? for sas_token if generated from the web
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import logging
import os
import shutil
# Import salt libs
import salt.fileserver
import salt.utils.files
import salt.utils.gzip_util
import salt.utils.hashutils
import salt.utils.json
import salt.utils.path
import salt.utils.stringutils
from salt.utils.versions import LooseVersion
try:
import azure.storage
if LooseVersion(azure.storage.__version__) < LooseVersion('0.20.0'):
raise ImportError('azure.storage.__version__ must be >= 0.20.0')
HAS_AZURE = True
except (ImportError, AttributeError):
HAS_AZURE = False
# Import third party libs
from salt.ext import six
__virtualname__ = 'azurefs'
log = logging.getLogger()
def __virtual__():
'''
Only load if defined in fileserver_backend and azure.storage is present
'''
if __virtualname__ not in __opts__['fileserver_backend']:
return False
if not HAS_AZURE:
return False
if 'azurefs' not in __opts__:
return False
if not _validate_config():
return False
return True
def find_file(path, saltenv='base', **kwargs):
'''
Search the environment for the relative path
'''
fnd = {'path': '',
'rel': ''}
for container in __opts__.get('azurefs', []):
if container.get('saltenv', 'base') != saltenv:
continue
full = os.path.join(_get_container_path(container), path)
if os.path.isfile(full) and not salt.fileserver.is_file_ignored(
__opts__, path):
fnd['path'] = full
fnd['rel'] = path
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(full))
except Exception:
pass
return fnd
return fnd
def envs():
'''
Each container configuration can have an environment setting, or defaults
to base
'''
saltenvs = []
for container in __opts__.get('azurefs', []):
saltenvs.append(container.get('saltenv', 'base'))
# Remove duplicates
return list(set(saltenvs))
def update():
'''
Update caches of the storage containers.
Compares the md5 of the files on disk to the md5 of the blobs in the
container, and only updates if necessary.
Also processes deletions by walking the container caches and comparing
with the list of blobs in the container
'''
for container in __opts__['azurefs']:
path = _get_container_path(container)
try:
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
shutil.rmtree(path)
os.makedirs(path)
except Exception as exc:
log.exception('Error occurred creating cache directory for azurefs')
continue
blob_service = _get_container_service(container)
name = container['container_name']
try:
blob_list = blob_service.list_blobs(name)
except Exception as exc:
log.exception('Error occurred fetching blob list for azurefs')
continue
# Walk the cache directory searching for deletions
blob_names = [blob.name for blob in blob_list]
blob_set = set(blob_names)
for root, dirs, files in salt.utils.path.os_walk(path):
for f in files:
fname = os.path.join(root, f)
relpath = os.path.relpath(fname, path)
if relpath not in blob_set:
salt.fileserver.wait_lock(fname + '.lk', fname)
try:
os.unlink(fname)
except Exception:
pass
if not dirs and not files:
shutil.rmtree(root)
for blob in blob_list:
fname = os.path.join(path, blob.name)
update = False
if os.path.exists(fname):
# File exists, check the hashes
source_md5 = blob.properties.content_settings.content_md5
local_md5 = base64.b64encode(salt.utils.hashutils.get_hash(fname, 'md5').decode('hex'))
if local_md5 != source_md5:
update = True
else:
update = True
if update:
if not os.path.exists(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
# Lock writes
lk_fn = fname + '.lk'
salt.fileserver.wait_lock(lk_fn, fname)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
try:
blob_service.get_blob_to_path(name, blob.name, fname)
except Exception as exc:
log.exception('Error occurred fetching blob from azurefs')
continue
# Unlock writes
try:
os.unlink(lk_fn)
except Exception:
pass
# Write out file list
container_list = path + '.list'
lk_fn = container_list + '.lk'
salt.fileserver.wait_lock(lk_fn, container_list)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
with salt.utils.files.fopen(container_list, 'w') as fp_:
salt.utils.json.dump(blob_names, fp_)
try:
os.unlink(lk_fn)
except Exception:
pass
try:
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
shutil.rmtree(hash_cachedir)
except Exception:
log.exception('Problem occurred trying to invalidate hash cach for azurefs')
def file_hash(load, fnd):
'''
Return a file hash based on the hash type set in the master config
'''
if not all(x in load for x in ('path', 'saltenv')):
return '', None
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
hashdest = salt.utils.path.join(hash_cachedir,
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
if not os.path.exists(os.path.dirname(hashdest)):
os.makedirs(os.path.dirname(hashdest))
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(ret['hsum']))
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret
def file_list(load):
'''
Return a list of all files in a specified environment
'''
ret = set()
try:
for container in __opts__['azurefs']:
if container.get('saltenv', 'base') != load['saltenv']:
continue
container_list = _get_container_path(container) + '.list'
lk = container_list + '.lk'
salt.fileserver.wait_lock(lk, container_list, 5)
if not os.path.exists(container_list):
continue
with salt.utils.files.fopen(container_list, 'r') as fp_:
ret.update(set(salt.utils.json.load(fp_)))
except Exception as exc:
log.error('azurefs: an error ocurred retrieving file lists. '
'It should be resolved next time the fileserver '
'updates. Please do not manually modify the azurefs '
'cache directory.')
return list(ret)
def dir_list(load):
'''
Return a list of all directories in a specified environment
'''
ret = set()
files = file_list(load)
for f in files:
dirname = f
while dirname:
dirname = os.path.dirname(dirname)
if dirname:
ret.add(dirname)
return list(ret)
def _get_container_path(container):
'''
Get the cache path for the container in question
Cache paths are generate by combining the account name, container name,
and saltenv, separated by underscores
'''
root = os.path.join(__opts__['cachedir'], 'azurefs')
container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),
container.get('container_name', ''),
container.get('saltenv', 'base'))
return os.path.join(root, container_dir)
def _get_container_service(container):
'''
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order
'''
if 'account_key' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])
elif 'sas_token' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])
else:
account = azure.storage.CloudStorageAccount(container['account_name'])
blob_service = account.create_block_blob_service()
return blob_service
def _validate_config():
'''
Validate azurefs config, return False if it doesn't validate
'''
if not isinstance(__opts__['azurefs'], list):
log.error('azurefs configuration is not formed as a list, skipping azurefs')
return False
for container in __opts__['azurefs']:
if not isinstance(container, dict):
log.error(
'One or more entries in the azurefs configuration list are '
'not formed as a dict. Skipping azurefs: %s', container
)
return False
if 'account_name' not in container or 'container_name' not in container:
log.error(
'An azurefs container configuration is missing either an '
'account_name or a container_name: %s', container
)
return False
return True
|
saltstack/salt
|
salt/fileserver/azurefs.py
|
update
|
python
|
def update():
'''
Update caches of the storage containers.
Compares the md5 of the files on disk to the md5 of the blobs in the
container, and only updates if necessary.
Also processes deletions by walking the container caches and comparing
with the list of blobs in the container
'''
for container in __opts__['azurefs']:
path = _get_container_path(container)
try:
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
shutil.rmtree(path)
os.makedirs(path)
except Exception as exc:
log.exception('Error occurred creating cache directory for azurefs')
continue
blob_service = _get_container_service(container)
name = container['container_name']
try:
blob_list = blob_service.list_blobs(name)
except Exception as exc:
log.exception('Error occurred fetching blob list for azurefs')
continue
# Walk the cache directory searching for deletions
blob_names = [blob.name for blob in blob_list]
blob_set = set(blob_names)
for root, dirs, files in salt.utils.path.os_walk(path):
for f in files:
fname = os.path.join(root, f)
relpath = os.path.relpath(fname, path)
if relpath not in blob_set:
salt.fileserver.wait_lock(fname + '.lk', fname)
try:
os.unlink(fname)
except Exception:
pass
if not dirs and not files:
shutil.rmtree(root)
for blob in blob_list:
fname = os.path.join(path, blob.name)
update = False
if os.path.exists(fname):
# File exists, check the hashes
source_md5 = blob.properties.content_settings.content_md5
local_md5 = base64.b64encode(salt.utils.hashutils.get_hash(fname, 'md5').decode('hex'))
if local_md5 != source_md5:
update = True
else:
update = True
if update:
if not os.path.exists(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
# Lock writes
lk_fn = fname + '.lk'
salt.fileserver.wait_lock(lk_fn, fname)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
try:
blob_service.get_blob_to_path(name, blob.name, fname)
except Exception as exc:
log.exception('Error occurred fetching blob from azurefs')
continue
# Unlock writes
try:
os.unlink(lk_fn)
except Exception:
pass
# Write out file list
container_list = path + '.list'
lk_fn = container_list + '.lk'
salt.fileserver.wait_lock(lk_fn, container_list)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
with salt.utils.files.fopen(container_list, 'w') as fp_:
salt.utils.json.dump(blob_names, fp_)
try:
os.unlink(lk_fn)
except Exception:
pass
try:
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
shutil.rmtree(hash_cachedir)
except Exception:
log.exception('Problem occurred trying to invalidate hash cach for azurefs')
|
Update caches of the storage containers.
Compares the md5 of the files on disk to the md5 of the blobs in the
container, and only updates if necessary.
Also processes deletions by walking the container caches and comparing
with the list of blobs in the container
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/azurefs.py#L178-L272
|
[
"def dump(obj, fp, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dump, 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.dump 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.dump(obj, fp, default=_enc_func, **kwargs) # future lint: blacklisted-function\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 os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n",
"def wait_lock(lk_fn, dest, wait_timeout=0):\n '''\n If the write lock is there, check to see if the file is actually being\n written. If there is no change in the file size after a short sleep,\n remove the lock and move forward.\n '''\n if not os.path.exists(lk_fn):\n return False\n if not os.path.exists(dest):\n # The dest is not here, sleep for a bit, if the dest is not here yet\n # kill the lockfile and start the write\n time.sleep(1)\n if not os.path.isfile(dest):\n _unlock_cache(lk_fn)\n return False\n timeout = None\n if wait_timeout:\n timeout = time.time() + wait_timeout\n # There is a lock file, the dest is there, stat the dest, sleep and check\n # that the dest is being written, if it is not being written kill the lock\n # file and continue. Also check if the lock file is gone.\n s_count = 0\n s_size = os.stat(dest).st_size\n while True:\n time.sleep(1)\n if not os.path.exists(lk_fn):\n return False\n size = os.stat(dest).st_size\n if size == s_size:\n s_count += 1\n if s_count >= 3:\n # The file is not being written to, kill the lock and proceed\n _unlock_cache(lk_fn)\n return False\n else:\n s_size = size\n if timeout:\n if time.time() > timeout:\n raise ValueError(\n 'Timeout({0}s) for {1} (lock: {2}) elapsed'.format(\n wait_timeout, dest, lk_fn\n )\n )\n return False\n",
"def _get_container_path(container):\n '''\n Get the cache path for the container in question\n\n Cache paths are generate by combining the account name, container name,\n and saltenv, separated by underscores\n '''\n root = os.path.join(__opts__['cachedir'], 'azurefs')\n container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),\n container.get('container_name', ''),\n container.get('saltenv', 'base'))\n return os.path.join(root, container_dir)\n",
"def _get_container_service(container):\n '''\n Get the azure block blob service for the container in question\n\n Try account_key, sas_token, and no auth in that order\n '''\n if 'account_key' in container:\n account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])\n elif 'sas_token' in container:\n account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])\n else:\n account = azure.storage.CloudStorageAccount(container['account_name'])\n blob_service = account.create_block_blob_service()\n return blob_service\n"
] |
# -*- coding: utf-8 -*-
'''
The backend for serving files from the Azure blob storage service.
.. versionadded:: 2015.8.0
To enable, add ``azurefs`` to the :conf_master:`fileserver_backend` option in
the Master config file.
.. code-block:: yaml
fileserver_backend:
- azurefs
Starting in Salt 2018.3.0, this fileserver requires the standalone Azure
Storage SDK for Python. Theoretically any version >= v0.20.0 should work, but
it was developed against the v0.33.0 version.
Each storage container will be mapped to an environment. By default, containers
will be mapped to the ``base`` environment. You can override this behavior with
the ``saltenv`` configuration option. You can have an unlimited number of
storage containers, and can have a storage container serve multiple
environments, or have multiple storage containers mapped to the same
environment. Normal first-found rules apply, and storage containers are
searched in the order they are defined.
You must have either an account_key or a sas_token defined for each container,
if it is private. If you use a sas_token, it must have READ and LIST
permissions.
.. code-block:: yaml
azurefs:
- account_name: my_storage
account_key: 'fNH9cRp0+qVIVYZ+5rnZAhHc9ycOUcJnHtzpfOr0W0sxrtL2KVLuMe1xDfLwmfed+JJInZaEdWVCPHD4d/oqeA=='
container_name: my_container
- account_name: my_storage
sas_token: 'ss=b&sp=&sv=2015-07-08&sig=cohxXabx8FQdXsSEHyUXMjsSfNH2tZ2OB97Ou44pkRE%3D&srt=co&se=2017-04-18T21%3A38%3A01Z'
container_name: my_dev_container
saltenv: dev
- account_name: my_storage
container_name: my_public_container
.. note::
Do not include the leading ? for sas_token if generated from the web
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import logging
import os
import shutil
# Import salt libs
import salt.fileserver
import salt.utils.files
import salt.utils.gzip_util
import salt.utils.hashutils
import salt.utils.json
import salt.utils.path
import salt.utils.stringutils
from salt.utils.versions import LooseVersion
try:
import azure.storage
if LooseVersion(azure.storage.__version__) < LooseVersion('0.20.0'):
raise ImportError('azure.storage.__version__ must be >= 0.20.0')
HAS_AZURE = True
except (ImportError, AttributeError):
HAS_AZURE = False
# Import third party libs
from salt.ext import six
__virtualname__ = 'azurefs'
log = logging.getLogger()
def __virtual__():
'''
Only load if defined in fileserver_backend and azure.storage is present
'''
if __virtualname__ not in __opts__['fileserver_backend']:
return False
if not HAS_AZURE:
return False
if 'azurefs' not in __opts__:
return False
if not _validate_config():
return False
return True
def find_file(path, saltenv='base', **kwargs):
'''
Search the environment for the relative path
'''
fnd = {'path': '',
'rel': ''}
for container in __opts__.get('azurefs', []):
if container.get('saltenv', 'base') != saltenv:
continue
full = os.path.join(_get_container_path(container), path)
if os.path.isfile(full) and not salt.fileserver.is_file_ignored(
__opts__, path):
fnd['path'] = full
fnd['rel'] = path
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(full))
except Exception:
pass
return fnd
return fnd
def envs():
'''
Each container configuration can have an environment setting, or defaults
to base
'''
saltenvs = []
for container in __opts__.get('azurefs', []):
saltenvs.append(container.get('saltenv', 'base'))
# Remove duplicates
return list(set(saltenvs))
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
ret = {'data': '',
'dest': ''}
required_load_keys = ('path', 'loc', 'saltenv')
if not all(x in load for x in required_load_keys):
log.debug(
'Not all of the required keys present in payload. Missing: %s',
', '.join(required_load_keys.difference(load))
)
return ret
if not fnd['path']:
return ret
ret['dest'] = fnd['rel']
gzip = load.get('gzip', None)
fpath = os.path.normpath(fnd['path'])
with salt.utils.files.fopen(fpath, 'rb') as fp_:
fp_.seek(load['loc'])
data = fp_.read(__opts__['file_buffer_size'])
if data and six.PY3 and not salt.utils.files.is_binary(fpath):
data = data.decode(__salt_system_encoding__)
if gzip and data:
data = salt.utils.gzip_util.compress(data, gzip)
ret['gzip'] = gzip
ret['data'] = data
return ret
def file_hash(load, fnd):
'''
Return a file hash based on the hash type set in the master config
'''
if not all(x in load for x in ('path', 'saltenv')):
return '', None
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
hashdest = salt.utils.path.join(hash_cachedir,
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
if not os.path.exists(os.path.dirname(hashdest)):
os.makedirs(os.path.dirname(hashdest))
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(ret['hsum']))
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret
def file_list(load):
'''
Return a list of all files in a specified environment
'''
ret = set()
try:
for container in __opts__['azurefs']:
if container.get('saltenv', 'base') != load['saltenv']:
continue
container_list = _get_container_path(container) + '.list'
lk = container_list + '.lk'
salt.fileserver.wait_lock(lk, container_list, 5)
if not os.path.exists(container_list):
continue
with salt.utils.files.fopen(container_list, 'r') as fp_:
ret.update(set(salt.utils.json.load(fp_)))
except Exception as exc:
log.error('azurefs: an error ocurred retrieving file lists. '
'It should be resolved next time the fileserver '
'updates. Please do not manually modify the azurefs '
'cache directory.')
return list(ret)
def dir_list(load):
'''
Return a list of all directories in a specified environment
'''
ret = set()
files = file_list(load)
for f in files:
dirname = f
while dirname:
dirname = os.path.dirname(dirname)
if dirname:
ret.add(dirname)
return list(ret)
def _get_container_path(container):
'''
Get the cache path for the container in question
Cache paths are generate by combining the account name, container name,
and saltenv, separated by underscores
'''
root = os.path.join(__opts__['cachedir'], 'azurefs')
container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),
container.get('container_name', ''),
container.get('saltenv', 'base'))
return os.path.join(root, container_dir)
def _get_container_service(container):
'''
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order
'''
if 'account_key' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])
elif 'sas_token' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])
else:
account = azure.storage.CloudStorageAccount(container['account_name'])
blob_service = account.create_block_blob_service()
return blob_service
def _validate_config():
'''
Validate azurefs config, return False if it doesn't validate
'''
if not isinstance(__opts__['azurefs'], list):
log.error('azurefs configuration is not formed as a list, skipping azurefs')
return False
for container in __opts__['azurefs']:
if not isinstance(container, dict):
log.error(
'One or more entries in the azurefs configuration list are '
'not formed as a dict. Skipping azurefs: %s', container
)
return False
if 'account_name' not in container or 'container_name' not in container:
log.error(
'An azurefs container configuration is missing either an '
'account_name or a container_name: %s', container
)
return False
return True
|
saltstack/salt
|
salt/fileserver/azurefs.py
|
file_hash
|
python
|
def file_hash(load, fnd):
'''
Return a file hash based on the hash type set in the master config
'''
if not all(x in load for x in ('path', 'saltenv')):
return '', None
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
hashdest = salt.utils.path.join(hash_cachedir,
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
if not os.path.exists(os.path.dirname(hashdest)):
os.makedirs(os.path.dirname(hashdest))
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(ret['hsum']))
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret
|
Return a file hash based on the hash type set in the master config
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/azurefs.py#L275-L299
|
[
"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 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"
] |
# -*- coding: utf-8 -*-
'''
The backend for serving files from the Azure blob storage service.
.. versionadded:: 2015.8.0
To enable, add ``azurefs`` to the :conf_master:`fileserver_backend` option in
the Master config file.
.. code-block:: yaml
fileserver_backend:
- azurefs
Starting in Salt 2018.3.0, this fileserver requires the standalone Azure
Storage SDK for Python. Theoretically any version >= v0.20.0 should work, but
it was developed against the v0.33.0 version.
Each storage container will be mapped to an environment. By default, containers
will be mapped to the ``base`` environment. You can override this behavior with
the ``saltenv`` configuration option. You can have an unlimited number of
storage containers, and can have a storage container serve multiple
environments, or have multiple storage containers mapped to the same
environment. Normal first-found rules apply, and storage containers are
searched in the order they are defined.
You must have either an account_key or a sas_token defined for each container,
if it is private. If you use a sas_token, it must have READ and LIST
permissions.
.. code-block:: yaml
azurefs:
- account_name: my_storage
account_key: 'fNH9cRp0+qVIVYZ+5rnZAhHc9ycOUcJnHtzpfOr0W0sxrtL2KVLuMe1xDfLwmfed+JJInZaEdWVCPHD4d/oqeA=='
container_name: my_container
- account_name: my_storage
sas_token: 'ss=b&sp=&sv=2015-07-08&sig=cohxXabx8FQdXsSEHyUXMjsSfNH2tZ2OB97Ou44pkRE%3D&srt=co&se=2017-04-18T21%3A38%3A01Z'
container_name: my_dev_container
saltenv: dev
- account_name: my_storage
container_name: my_public_container
.. note::
Do not include the leading ? for sas_token if generated from the web
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import logging
import os
import shutil
# Import salt libs
import salt.fileserver
import salt.utils.files
import salt.utils.gzip_util
import salt.utils.hashutils
import salt.utils.json
import salt.utils.path
import salt.utils.stringutils
from salt.utils.versions import LooseVersion
try:
import azure.storage
if LooseVersion(azure.storage.__version__) < LooseVersion('0.20.0'):
raise ImportError('azure.storage.__version__ must be >= 0.20.0')
HAS_AZURE = True
except (ImportError, AttributeError):
HAS_AZURE = False
# Import third party libs
from salt.ext import six
__virtualname__ = 'azurefs'
log = logging.getLogger()
def __virtual__():
'''
Only load if defined in fileserver_backend and azure.storage is present
'''
if __virtualname__ not in __opts__['fileserver_backend']:
return False
if not HAS_AZURE:
return False
if 'azurefs' not in __opts__:
return False
if not _validate_config():
return False
return True
def find_file(path, saltenv='base', **kwargs):
'''
Search the environment for the relative path
'''
fnd = {'path': '',
'rel': ''}
for container in __opts__.get('azurefs', []):
if container.get('saltenv', 'base') != saltenv:
continue
full = os.path.join(_get_container_path(container), path)
if os.path.isfile(full) and not salt.fileserver.is_file_ignored(
__opts__, path):
fnd['path'] = full
fnd['rel'] = path
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(full))
except Exception:
pass
return fnd
return fnd
def envs():
'''
Each container configuration can have an environment setting, or defaults
to base
'''
saltenvs = []
for container in __opts__.get('azurefs', []):
saltenvs.append(container.get('saltenv', 'base'))
# Remove duplicates
return list(set(saltenvs))
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
ret = {'data': '',
'dest': ''}
required_load_keys = ('path', 'loc', 'saltenv')
if not all(x in load for x in required_load_keys):
log.debug(
'Not all of the required keys present in payload. Missing: %s',
', '.join(required_load_keys.difference(load))
)
return ret
if not fnd['path']:
return ret
ret['dest'] = fnd['rel']
gzip = load.get('gzip', None)
fpath = os.path.normpath(fnd['path'])
with salt.utils.files.fopen(fpath, 'rb') as fp_:
fp_.seek(load['loc'])
data = fp_.read(__opts__['file_buffer_size'])
if data and six.PY3 and not salt.utils.files.is_binary(fpath):
data = data.decode(__salt_system_encoding__)
if gzip and data:
data = salt.utils.gzip_util.compress(data, gzip)
ret['gzip'] = gzip
ret['data'] = data
return ret
def update():
'''
Update caches of the storage containers.
Compares the md5 of the files on disk to the md5 of the blobs in the
container, and only updates if necessary.
Also processes deletions by walking the container caches and comparing
with the list of blobs in the container
'''
for container in __opts__['azurefs']:
path = _get_container_path(container)
try:
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
shutil.rmtree(path)
os.makedirs(path)
except Exception as exc:
log.exception('Error occurred creating cache directory for azurefs')
continue
blob_service = _get_container_service(container)
name = container['container_name']
try:
blob_list = blob_service.list_blobs(name)
except Exception as exc:
log.exception('Error occurred fetching blob list for azurefs')
continue
# Walk the cache directory searching for deletions
blob_names = [blob.name for blob in blob_list]
blob_set = set(blob_names)
for root, dirs, files in salt.utils.path.os_walk(path):
for f in files:
fname = os.path.join(root, f)
relpath = os.path.relpath(fname, path)
if relpath not in blob_set:
salt.fileserver.wait_lock(fname + '.lk', fname)
try:
os.unlink(fname)
except Exception:
pass
if not dirs and not files:
shutil.rmtree(root)
for blob in blob_list:
fname = os.path.join(path, blob.name)
update = False
if os.path.exists(fname):
# File exists, check the hashes
source_md5 = blob.properties.content_settings.content_md5
local_md5 = base64.b64encode(salt.utils.hashutils.get_hash(fname, 'md5').decode('hex'))
if local_md5 != source_md5:
update = True
else:
update = True
if update:
if not os.path.exists(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
# Lock writes
lk_fn = fname + '.lk'
salt.fileserver.wait_lock(lk_fn, fname)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
try:
blob_service.get_blob_to_path(name, blob.name, fname)
except Exception as exc:
log.exception('Error occurred fetching blob from azurefs')
continue
# Unlock writes
try:
os.unlink(lk_fn)
except Exception:
pass
# Write out file list
container_list = path + '.list'
lk_fn = container_list + '.lk'
salt.fileserver.wait_lock(lk_fn, container_list)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
with salt.utils.files.fopen(container_list, 'w') as fp_:
salt.utils.json.dump(blob_names, fp_)
try:
os.unlink(lk_fn)
except Exception:
pass
try:
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
shutil.rmtree(hash_cachedir)
except Exception:
log.exception('Problem occurred trying to invalidate hash cach for azurefs')
def file_list(load):
'''
Return a list of all files in a specified environment
'''
ret = set()
try:
for container in __opts__['azurefs']:
if container.get('saltenv', 'base') != load['saltenv']:
continue
container_list = _get_container_path(container) + '.list'
lk = container_list + '.lk'
salt.fileserver.wait_lock(lk, container_list, 5)
if not os.path.exists(container_list):
continue
with salt.utils.files.fopen(container_list, 'r') as fp_:
ret.update(set(salt.utils.json.load(fp_)))
except Exception as exc:
log.error('azurefs: an error ocurred retrieving file lists. '
'It should be resolved next time the fileserver '
'updates. Please do not manually modify the azurefs '
'cache directory.')
return list(ret)
def dir_list(load):
'''
Return a list of all directories in a specified environment
'''
ret = set()
files = file_list(load)
for f in files:
dirname = f
while dirname:
dirname = os.path.dirname(dirname)
if dirname:
ret.add(dirname)
return list(ret)
def _get_container_path(container):
'''
Get the cache path for the container in question
Cache paths are generate by combining the account name, container name,
and saltenv, separated by underscores
'''
root = os.path.join(__opts__['cachedir'], 'azurefs')
container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),
container.get('container_name', ''),
container.get('saltenv', 'base'))
return os.path.join(root, container_dir)
def _get_container_service(container):
'''
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order
'''
if 'account_key' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])
elif 'sas_token' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])
else:
account = azure.storage.CloudStorageAccount(container['account_name'])
blob_service = account.create_block_blob_service()
return blob_service
def _validate_config():
'''
Validate azurefs config, return False if it doesn't validate
'''
if not isinstance(__opts__['azurefs'], list):
log.error('azurefs configuration is not formed as a list, skipping azurefs')
return False
for container in __opts__['azurefs']:
if not isinstance(container, dict):
log.error(
'One or more entries in the azurefs configuration list are '
'not formed as a dict. Skipping azurefs: %s', container
)
return False
if 'account_name' not in container or 'container_name' not in container:
log.error(
'An azurefs container configuration is missing either an '
'account_name or a container_name: %s', container
)
return False
return True
|
saltstack/salt
|
salt/fileserver/azurefs.py
|
file_list
|
python
|
def file_list(load):
'''
Return a list of all files in a specified environment
'''
ret = set()
try:
for container in __opts__['azurefs']:
if container.get('saltenv', 'base') != load['saltenv']:
continue
container_list = _get_container_path(container) + '.list'
lk = container_list + '.lk'
salt.fileserver.wait_lock(lk, container_list, 5)
if not os.path.exists(container_list):
continue
with salt.utils.files.fopen(container_list, 'r') as fp_:
ret.update(set(salt.utils.json.load(fp_)))
except Exception as exc:
log.error('azurefs: an error ocurred retrieving file lists. '
'It should be resolved next time the fileserver '
'updates. Please do not manually modify the azurefs '
'cache directory.')
return list(ret)
|
Return a list of all files in a specified environment
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/azurefs.py#L302-L323
|
[
"def load(fp, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.load\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n return kwargs.pop('_json_module', json).load(fp, **kwargs)\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 wait_lock(lk_fn, dest, wait_timeout=0):\n '''\n If the write lock is there, check to see if the file is actually being\n written. If there is no change in the file size after a short sleep,\n remove the lock and move forward.\n '''\n if not os.path.exists(lk_fn):\n return False\n if not os.path.exists(dest):\n # The dest is not here, sleep for a bit, if the dest is not here yet\n # kill the lockfile and start the write\n time.sleep(1)\n if not os.path.isfile(dest):\n _unlock_cache(lk_fn)\n return False\n timeout = None\n if wait_timeout:\n timeout = time.time() + wait_timeout\n # There is a lock file, the dest is there, stat the dest, sleep and check\n # that the dest is being written, if it is not being written kill the lock\n # file and continue. Also check if the lock file is gone.\n s_count = 0\n s_size = os.stat(dest).st_size\n while True:\n time.sleep(1)\n if not os.path.exists(lk_fn):\n return False\n size = os.stat(dest).st_size\n if size == s_size:\n s_count += 1\n if s_count >= 3:\n # The file is not being written to, kill the lock and proceed\n _unlock_cache(lk_fn)\n return False\n else:\n s_size = size\n if timeout:\n if time.time() > timeout:\n raise ValueError(\n 'Timeout({0}s) for {1} (lock: {2}) elapsed'.format(\n wait_timeout, dest, lk_fn\n )\n )\n return False\n",
"def _get_container_path(container):\n '''\n Get the cache path for the container in question\n\n Cache paths are generate by combining the account name, container name,\n and saltenv, separated by underscores\n '''\n root = os.path.join(__opts__['cachedir'], 'azurefs')\n container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),\n container.get('container_name', ''),\n container.get('saltenv', 'base'))\n return os.path.join(root, container_dir)\n"
] |
# -*- coding: utf-8 -*-
'''
The backend for serving files from the Azure blob storage service.
.. versionadded:: 2015.8.0
To enable, add ``azurefs`` to the :conf_master:`fileserver_backend` option in
the Master config file.
.. code-block:: yaml
fileserver_backend:
- azurefs
Starting in Salt 2018.3.0, this fileserver requires the standalone Azure
Storage SDK for Python. Theoretically any version >= v0.20.0 should work, but
it was developed against the v0.33.0 version.
Each storage container will be mapped to an environment. By default, containers
will be mapped to the ``base`` environment. You can override this behavior with
the ``saltenv`` configuration option. You can have an unlimited number of
storage containers, and can have a storage container serve multiple
environments, or have multiple storage containers mapped to the same
environment. Normal first-found rules apply, and storage containers are
searched in the order they are defined.
You must have either an account_key or a sas_token defined for each container,
if it is private. If you use a sas_token, it must have READ and LIST
permissions.
.. code-block:: yaml
azurefs:
- account_name: my_storage
account_key: 'fNH9cRp0+qVIVYZ+5rnZAhHc9ycOUcJnHtzpfOr0W0sxrtL2KVLuMe1xDfLwmfed+JJInZaEdWVCPHD4d/oqeA=='
container_name: my_container
- account_name: my_storage
sas_token: 'ss=b&sp=&sv=2015-07-08&sig=cohxXabx8FQdXsSEHyUXMjsSfNH2tZ2OB97Ou44pkRE%3D&srt=co&se=2017-04-18T21%3A38%3A01Z'
container_name: my_dev_container
saltenv: dev
- account_name: my_storage
container_name: my_public_container
.. note::
Do not include the leading ? for sas_token if generated from the web
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import logging
import os
import shutil
# Import salt libs
import salt.fileserver
import salt.utils.files
import salt.utils.gzip_util
import salt.utils.hashutils
import salt.utils.json
import salt.utils.path
import salt.utils.stringutils
from salt.utils.versions import LooseVersion
try:
import azure.storage
if LooseVersion(azure.storage.__version__) < LooseVersion('0.20.0'):
raise ImportError('azure.storage.__version__ must be >= 0.20.0')
HAS_AZURE = True
except (ImportError, AttributeError):
HAS_AZURE = False
# Import third party libs
from salt.ext import six
__virtualname__ = 'azurefs'
log = logging.getLogger()
def __virtual__():
'''
Only load if defined in fileserver_backend and azure.storage is present
'''
if __virtualname__ not in __opts__['fileserver_backend']:
return False
if not HAS_AZURE:
return False
if 'azurefs' not in __opts__:
return False
if not _validate_config():
return False
return True
def find_file(path, saltenv='base', **kwargs):
'''
Search the environment for the relative path
'''
fnd = {'path': '',
'rel': ''}
for container in __opts__.get('azurefs', []):
if container.get('saltenv', 'base') != saltenv:
continue
full = os.path.join(_get_container_path(container), path)
if os.path.isfile(full) and not salt.fileserver.is_file_ignored(
__opts__, path):
fnd['path'] = full
fnd['rel'] = path
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(full))
except Exception:
pass
return fnd
return fnd
def envs():
'''
Each container configuration can have an environment setting, or defaults
to base
'''
saltenvs = []
for container in __opts__.get('azurefs', []):
saltenvs.append(container.get('saltenv', 'base'))
# Remove duplicates
return list(set(saltenvs))
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
ret = {'data': '',
'dest': ''}
required_load_keys = ('path', 'loc', 'saltenv')
if not all(x in load for x in required_load_keys):
log.debug(
'Not all of the required keys present in payload. Missing: %s',
', '.join(required_load_keys.difference(load))
)
return ret
if not fnd['path']:
return ret
ret['dest'] = fnd['rel']
gzip = load.get('gzip', None)
fpath = os.path.normpath(fnd['path'])
with salt.utils.files.fopen(fpath, 'rb') as fp_:
fp_.seek(load['loc'])
data = fp_.read(__opts__['file_buffer_size'])
if data and six.PY3 and not salt.utils.files.is_binary(fpath):
data = data.decode(__salt_system_encoding__)
if gzip and data:
data = salt.utils.gzip_util.compress(data, gzip)
ret['gzip'] = gzip
ret['data'] = data
return ret
def update():
'''
Update caches of the storage containers.
Compares the md5 of the files on disk to the md5 of the blobs in the
container, and only updates if necessary.
Also processes deletions by walking the container caches and comparing
with the list of blobs in the container
'''
for container in __opts__['azurefs']:
path = _get_container_path(container)
try:
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
shutil.rmtree(path)
os.makedirs(path)
except Exception as exc:
log.exception('Error occurred creating cache directory for azurefs')
continue
blob_service = _get_container_service(container)
name = container['container_name']
try:
blob_list = blob_service.list_blobs(name)
except Exception as exc:
log.exception('Error occurred fetching blob list for azurefs')
continue
# Walk the cache directory searching for deletions
blob_names = [blob.name for blob in blob_list]
blob_set = set(blob_names)
for root, dirs, files in salt.utils.path.os_walk(path):
for f in files:
fname = os.path.join(root, f)
relpath = os.path.relpath(fname, path)
if relpath not in blob_set:
salt.fileserver.wait_lock(fname + '.lk', fname)
try:
os.unlink(fname)
except Exception:
pass
if not dirs and not files:
shutil.rmtree(root)
for blob in blob_list:
fname = os.path.join(path, blob.name)
update = False
if os.path.exists(fname):
# File exists, check the hashes
source_md5 = blob.properties.content_settings.content_md5
local_md5 = base64.b64encode(salt.utils.hashutils.get_hash(fname, 'md5').decode('hex'))
if local_md5 != source_md5:
update = True
else:
update = True
if update:
if not os.path.exists(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
# Lock writes
lk_fn = fname + '.lk'
salt.fileserver.wait_lock(lk_fn, fname)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
try:
blob_service.get_blob_to_path(name, blob.name, fname)
except Exception as exc:
log.exception('Error occurred fetching blob from azurefs')
continue
# Unlock writes
try:
os.unlink(lk_fn)
except Exception:
pass
# Write out file list
container_list = path + '.list'
lk_fn = container_list + '.lk'
salt.fileserver.wait_lock(lk_fn, container_list)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
with salt.utils.files.fopen(container_list, 'w') as fp_:
salt.utils.json.dump(blob_names, fp_)
try:
os.unlink(lk_fn)
except Exception:
pass
try:
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
shutil.rmtree(hash_cachedir)
except Exception:
log.exception('Problem occurred trying to invalidate hash cach for azurefs')
def file_hash(load, fnd):
'''
Return a file hash based on the hash type set in the master config
'''
if not all(x in load for x in ('path', 'saltenv')):
return '', None
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
hashdest = salt.utils.path.join(hash_cachedir,
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
if not os.path.exists(os.path.dirname(hashdest)):
os.makedirs(os.path.dirname(hashdest))
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(ret['hsum']))
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret
def dir_list(load):
'''
Return a list of all directories in a specified environment
'''
ret = set()
files = file_list(load)
for f in files:
dirname = f
while dirname:
dirname = os.path.dirname(dirname)
if dirname:
ret.add(dirname)
return list(ret)
def _get_container_path(container):
'''
Get the cache path for the container in question
Cache paths are generate by combining the account name, container name,
and saltenv, separated by underscores
'''
root = os.path.join(__opts__['cachedir'], 'azurefs')
container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),
container.get('container_name', ''),
container.get('saltenv', 'base'))
return os.path.join(root, container_dir)
def _get_container_service(container):
'''
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order
'''
if 'account_key' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])
elif 'sas_token' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])
else:
account = azure.storage.CloudStorageAccount(container['account_name'])
blob_service = account.create_block_blob_service()
return blob_service
def _validate_config():
'''
Validate azurefs config, return False if it doesn't validate
'''
if not isinstance(__opts__['azurefs'], list):
log.error('azurefs configuration is not formed as a list, skipping azurefs')
return False
for container in __opts__['azurefs']:
if not isinstance(container, dict):
log.error(
'One or more entries in the azurefs configuration list are '
'not formed as a dict. Skipping azurefs: %s', container
)
return False
if 'account_name' not in container or 'container_name' not in container:
log.error(
'An azurefs container configuration is missing either an '
'account_name or a container_name: %s', container
)
return False
return True
|
saltstack/salt
|
salt/fileserver/azurefs.py
|
dir_list
|
python
|
def dir_list(load):
'''
Return a list of all directories in a specified environment
'''
ret = set()
files = file_list(load)
for f in files:
dirname = f
while dirname:
dirname = os.path.dirname(dirname)
if dirname:
ret.add(dirname)
return list(ret)
|
Return a list of all directories in a specified environment
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/azurefs.py#L326-L338
|
[
"def file_list(load):\n '''\n Return a list of all files in a specified environment\n '''\n ret = set()\n try:\n for container in __opts__['azurefs']:\n if container.get('saltenv', 'base') != load['saltenv']:\n continue\n container_list = _get_container_path(container) + '.list'\n lk = container_list + '.lk'\n salt.fileserver.wait_lock(lk, container_list, 5)\n if not os.path.exists(container_list):\n continue\n with salt.utils.files.fopen(container_list, 'r') as fp_:\n ret.update(set(salt.utils.json.load(fp_)))\n except Exception as exc:\n log.error('azurefs: an error ocurred retrieving file lists. '\n 'It should be resolved next time the fileserver '\n 'updates. Please do not manually modify the azurefs '\n 'cache directory.')\n return list(ret)\n"
] |
# -*- coding: utf-8 -*-
'''
The backend for serving files from the Azure blob storage service.
.. versionadded:: 2015.8.0
To enable, add ``azurefs`` to the :conf_master:`fileserver_backend` option in
the Master config file.
.. code-block:: yaml
fileserver_backend:
- azurefs
Starting in Salt 2018.3.0, this fileserver requires the standalone Azure
Storage SDK for Python. Theoretically any version >= v0.20.0 should work, but
it was developed against the v0.33.0 version.
Each storage container will be mapped to an environment. By default, containers
will be mapped to the ``base`` environment. You can override this behavior with
the ``saltenv`` configuration option. You can have an unlimited number of
storage containers, and can have a storage container serve multiple
environments, or have multiple storage containers mapped to the same
environment. Normal first-found rules apply, and storage containers are
searched in the order they are defined.
You must have either an account_key or a sas_token defined for each container,
if it is private. If you use a sas_token, it must have READ and LIST
permissions.
.. code-block:: yaml
azurefs:
- account_name: my_storage
account_key: 'fNH9cRp0+qVIVYZ+5rnZAhHc9ycOUcJnHtzpfOr0W0sxrtL2KVLuMe1xDfLwmfed+JJInZaEdWVCPHD4d/oqeA=='
container_name: my_container
- account_name: my_storage
sas_token: 'ss=b&sp=&sv=2015-07-08&sig=cohxXabx8FQdXsSEHyUXMjsSfNH2tZ2OB97Ou44pkRE%3D&srt=co&se=2017-04-18T21%3A38%3A01Z'
container_name: my_dev_container
saltenv: dev
- account_name: my_storage
container_name: my_public_container
.. note::
Do not include the leading ? for sas_token if generated from the web
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import logging
import os
import shutil
# Import salt libs
import salt.fileserver
import salt.utils.files
import salt.utils.gzip_util
import salt.utils.hashutils
import salt.utils.json
import salt.utils.path
import salt.utils.stringutils
from salt.utils.versions import LooseVersion
try:
import azure.storage
if LooseVersion(azure.storage.__version__) < LooseVersion('0.20.0'):
raise ImportError('azure.storage.__version__ must be >= 0.20.0')
HAS_AZURE = True
except (ImportError, AttributeError):
HAS_AZURE = False
# Import third party libs
from salt.ext import six
__virtualname__ = 'azurefs'
log = logging.getLogger()
def __virtual__():
'''
Only load if defined in fileserver_backend and azure.storage is present
'''
if __virtualname__ not in __opts__['fileserver_backend']:
return False
if not HAS_AZURE:
return False
if 'azurefs' not in __opts__:
return False
if not _validate_config():
return False
return True
def find_file(path, saltenv='base', **kwargs):
'''
Search the environment for the relative path
'''
fnd = {'path': '',
'rel': ''}
for container in __opts__.get('azurefs', []):
if container.get('saltenv', 'base') != saltenv:
continue
full = os.path.join(_get_container_path(container), path)
if os.path.isfile(full) and not salt.fileserver.is_file_ignored(
__opts__, path):
fnd['path'] = full
fnd['rel'] = path
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(full))
except Exception:
pass
return fnd
return fnd
def envs():
'''
Each container configuration can have an environment setting, or defaults
to base
'''
saltenvs = []
for container in __opts__.get('azurefs', []):
saltenvs.append(container.get('saltenv', 'base'))
# Remove duplicates
return list(set(saltenvs))
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
ret = {'data': '',
'dest': ''}
required_load_keys = ('path', 'loc', 'saltenv')
if not all(x in load for x in required_load_keys):
log.debug(
'Not all of the required keys present in payload. Missing: %s',
', '.join(required_load_keys.difference(load))
)
return ret
if not fnd['path']:
return ret
ret['dest'] = fnd['rel']
gzip = load.get('gzip', None)
fpath = os.path.normpath(fnd['path'])
with salt.utils.files.fopen(fpath, 'rb') as fp_:
fp_.seek(load['loc'])
data = fp_.read(__opts__['file_buffer_size'])
if data and six.PY3 and not salt.utils.files.is_binary(fpath):
data = data.decode(__salt_system_encoding__)
if gzip and data:
data = salt.utils.gzip_util.compress(data, gzip)
ret['gzip'] = gzip
ret['data'] = data
return ret
def update():
'''
Update caches of the storage containers.
Compares the md5 of the files on disk to the md5 of the blobs in the
container, and only updates if necessary.
Also processes deletions by walking the container caches and comparing
with the list of blobs in the container
'''
for container in __opts__['azurefs']:
path = _get_container_path(container)
try:
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
shutil.rmtree(path)
os.makedirs(path)
except Exception as exc:
log.exception('Error occurred creating cache directory for azurefs')
continue
blob_service = _get_container_service(container)
name = container['container_name']
try:
blob_list = blob_service.list_blobs(name)
except Exception as exc:
log.exception('Error occurred fetching blob list for azurefs')
continue
# Walk the cache directory searching for deletions
blob_names = [blob.name for blob in blob_list]
blob_set = set(blob_names)
for root, dirs, files in salt.utils.path.os_walk(path):
for f in files:
fname = os.path.join(root, f)
relpath = os.path.relpath(fname, path)
if relpath not in blob_set:
salt.fileserver.wait_lock(fname + '.lk', fname)
try:
os.unlink(fname)
except Exception:
pass
if not dirs and not files:
shutil.rmtree(root)
for blob in blob_list:
fname = os.path.join(path, blob.name)
update = False
if os.path.exists(fname):
# File exists, check the hashes
source_md5 = blob.properties.content_settings.content_md5
local_md5 = base64.b64encode(salt.utils.hashutils.get_hash(fname, 'md5').decode('hex'))
if local_md5 != source_md5:
update = True
else:
update = True
if update:
if not os.path.exists(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
# Lock writes
lk_fn = fname + '.lk'
salt.fileserver.wait_lock(lk_fn, fname)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
try:
blob_service.get_blob_to_path(name, blob.name, fname)
except Exception as exc:
log.exception('Error occurred fetching blob from azurefs')
continue
# Unlock writes
try:
os.unlink(lk_fn)
except Exception:
pass
# Write out file list
container_list = path + '.list'
lk_fn = container_list + '.lk'
salt.fileserver.wait_lock(lk_fn, container_list)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
with salt.utils.files.fopen(container_list, 'w') as fp_:
salt.utils.json.dump(blob_names, fp_)
try:
os.unlink(lk_fn)
except Exception:
pass
try:
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
shutil.rmtree(hash_cachedir)
except Exception:
log.exception('Problem occurred trying to invalidate hash cach for azurefs')
def file_hash(load, fnd):
'''
Return a file hash based on the hash type set in the master config
'''
if not all(x in load for x in ('path', 'saltenv')):
return '', None
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
hashdest = salt.utils.path.join(hash_cachedir,
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
if not os.path.exists(os.path.dirname(hashdest)):
os.makedirs(os.path.dirname(hashdest))
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(ret['hsum']))
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret
def file_list(load):
'''
Return a list of all files in a specified environment
'''
ret = set()
try:
for container in __opts__['azurefs']:
if container.get('saltenv', 'base') != load['saltenv']:
continue
container_list = _get_container_path(container) + '.list'
lk = container_list + '.lk'
salt.fileserver.wait_lock(lk, container_list, 5)
if not os.path.exists(container_list):
continue
with salt.utils.files.fopen(container_list, 'r') as fp_:
ret.update(set(salt.utils.json.load(fp_)))
except Exception as exc:
log.error('azurefs: an error ocurred retrieving file lists. '
'It should be resolved next time the fileserver '
'updates. Please do not manually modify the azurefs '
'cache directory.')
return list(ret)
def _get_container_path(container):
'''
Get the cache path for the container in question
Cache paths are generate by combining the account name, container name,
and saltenv, separated by underscores
'''
root = os.path.join(__opts__['cachedir'], 'azurefs')
container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),
container.get('container_name', ''),
container.get('saltenv', 'base'))
return os.path.join(root, container_dir)
def _get_container_service(container):
'''
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order
'''
if 'account_key' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])
elif 'sas_token' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])
else:
account = azure.storage.CloudStorageAccount(container['account_name'])
blob_service = account.create_block_blob_service()
return blob_service
def _validate_config():
'''
Validate azurefs config, return False if it doesn't validate
'''
if not isinstance(__opts__['azurefs'], list):
log.error('azurefs configuration is not formed as a list, skipping azurefs')
return False
for container in __opts__['azurefs']:
if not isinstance(container, dict):
log.error(
'One or more entries in the azurefs configuration list are '
'not formed as a dict. Skipping azurefs: %s', container
)
return False
if 'account_name' not in container or 'container_name' not in container:
log.error(
'An azurefs container configuration is missing either an '
'account_name or a container_name: %s', container
)
return False
return True
|
saltstack/salt
|
salt/fileserver/azurefs.py
|
_get_container_path
|
python
|
def _get_container_path(container):
'''
Get the cache path for the container in question
Cache paths are generate by combining the account name, container name,
and saltenv, separated by underscores
'''
root = os.path.join(__opts__['cachedir'], 'azurefs')
container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),
container.get('container_name', ''),
container.get('saltenv', 'base'))
return os.path.join(root, container_dir)
|
Get the cache path for the container in question
Cache paths are generate by combining the account name, container name,
and saltenv, separated by underscores
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/azurefs.py#L341-L352
| null |
# -*- coding: utf-8 -*-
'''
The backend for serving files from the Azure blob storage service.
.. versionadded:: 2015.8.0
To enable, add ``azurefs`` to the :conf_master:`fileserver_backend` option in
the Master config file.
.. code-block:: yaml
fileserver_backend:
- azurefs
Starting in Salt 2018.3.0, this fileserver requires the standalone Azure
Storage SDK for Python. Theoretically any version >= v0.20.0 should work, but
it was developed against the v0.33.0 version.
Each storage container will be mapped to an environment. By default, containers
will be mapped to the ``base`` environment. You can override this behavior with
the ``saltenv`` configuration option. You can have an unlimited number of
storage containers, and can have a storage container serve multiple
environments, or have multiple storage containers mapped to the same
environment. Normal first-found rules apply, and storage containers are
searched in the order they are defined.
You must have either an account_key or a sas_token defined for each container,
if it is private. If you use a sas_token, it must have READ and LIST
permissions.
.. code-block:: yaml
azurefs:
- account_name: my_storage
account_key: 'fNH9cRp0+qVIVYZ+5rnZAhHc9ycOUcJnHtzpfOr0W0sxrtL2KVLuMe1xDfLwmfed+JJInZaEdWVCPHD4d/oqeA=='
container_name: my_container
- account_name: my_storage
sas_token: 'ss=b&sp=&sv=2015-07-08&sig=cohxXabx8FQdXsSEHyUXMjsSfNH2tZ2OB97Ou44pkRE%3D&srt=co&se=2017-04-18T21%3A38%3A01Z'
container_name: my_dev_container
saltenv: dev
- account_name: my_storage
container_name: my_public_container
.. note::
Do not include the leading ? for sas_token if generated from the web
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import logging
import os
import shutil
# Import salt libs
import salt.fileserver
import salt.utils.files
import salt.utils.gzip_util
import salt.utils.hashutils
import salt.utils.json
import salt.utils.path
import salt.utils.stringutils
from salt.utils.versions import LooseVersion
try:
import azure.storage
if LooseVersion(azure.storage.__version__) < LooseVersion('0.20.0'):
raise ImportError('azure.storage.__version__ must be >= 0.20.0')
HAS_AZURE = True
except (ImportError, AttributeError):
HAS_AZURE = False
# Import third party libs
from salt.ext import six
__virtualname__ = 'azurefs'
log = logging.getLogger()
def __virtual__():
'''
Only load if defined in fileserver_backend and azure.storage is present
'''
if __virtualname__ not in __opts__['fileserver_backend']:
return False
if not HAS_AZURE:
return False
if 'azurefs' not in __opts__:
return False
if not _validate_config():
return False
return True
def find_file(path, saltenv='base', **kwargs):
'''
Search the environment for the relative path
'''
fnd = {'path': '',
'rel': ''}
for container in __opts__.get('azurefs', []):
if container.get('saltenv', 'base') != saltenv:
continue
full = os.path.join(_get_container_path(container), path)
if os.path.isfile(full) and not salt.fileserver.is_file_ignored(
__opts__, path):
fnd['path'] = full
fnd['rel'] = path
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(full))
except Exception:
pass
return fnd
return fnd
def envs():
'''
Each container configuration can have an environment setting, or defaults
to base
'''
saltenvs = []
for container in __opts__.get('azurefs', []):
saltenvs.append(container.get('saltenv', 'base'))
# Remove duplicates
return list(set(saltenvs))
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
ret = {'data': '',
'dest': ''}
required_load_keys = ('path', 'loc', 'saltenv')
if not all(x in load for x in required_load_keys):
log.debug(
'Not all of the required keys present in payload. Missing: %s',
', '.join(required_load_keys.difference(load))
)
return ret
if not fnd['path']:
return ret
ret['dest'] = fnd['rel']
gzip = load.get('gzip', None)
fpath = os.path.normpath(fnd['path'])
with salt.utils.files.fopen(fpath, 'rb') as fp_:
fp_.seek(load['loc'])
data = fp_.read(__opts__['file_buffer_size'])
if data and six.PY3 and not salt.utils.files.is_binary(fpath):
data = data.decode(__salt_system_encoding__)
if gzip and data:
data = salt.utils.gzip_util.compress(data, gzip)
ret['gzip'] = gzip
ret['data'] = data
return ret
def update():
'''
Update caches of the storage containers.
Compares the md5 of the files on disk to the md5 of the blobs in the
container, and only updates if necessary.
Also processes deletions by walking the container caches and comparing
with the list of blobs in the container
'''
for container in __opts__['azurefs']:
path = _get_container_path(container)
try:
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
shutil.rmtree(path)
os.makedirs(path)
except Exception as exc:
log.exception('Error occurred creating cache directory for azurefs')
continue
blob_service = _get_container_service(container)
name = container['container_name']
try:
blob_list = blob_service.list_blobs(name)
except Exception as exc:
log.exception('Error occurred fetching blob list for azurefs')
continue
# Walk the cache directory searching for deletions
blob_names = [blob.name for blob in blob_list]
blob_set = set(blob_names)
for root, dirs, files in salt.utils.path.os_walk(path):
for f in files:
fname = os.path.join(root, f)
relpath = os.path.relpath(fname, path)
if relpath not in blob_set:
salt.fileserver.wait_lock(fname + '.lk', fname)
try:
os.unlink(fname)
except Exception:
pass
if not dirs and not files:
shutil.rmtree(root)
for blob in blob_list:
fname = os.path.join(path, blob.name)
update = False
if os.path.exists(fname):
# File exists, check the hashes
source_md5 = blob.properties.content_settings.content_md5
local_md5 = base64.b64encode(salt.utils.hashutils.get_hash(fname, 'md5').decode('hex'))
if local_md5 != source_md5:
update = True
else:
update = True
if update:
if not os.path.exists(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
# Lock writes
lk_fn = fname + '.lk'
salt.fileserver.wait_lock(lk_fn, fname)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
try:
blob_service.get_blob_to_path(name, blob.name, fname)
except Exception as exc:
log.exception('Error occurred fetching blob from azurefs')
continue
# Unlock writes
try:
os.unlink(lk_fn)
except Exception:
pass
# Write out file list
container_list = path + '.list'
lk_fn = container_list + '.lk'
salt.fileserver.wait_lock(lk_fn, container_list)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
with salt.utils.files.fopen(container_list, 'w') as fp_:
salt.utils.json.dump(blob_names, fp_)
try:
os.unlink(lk_fn)
except Exception:
pass
try:
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
shutil.rmtree(hash_cachedir)
except Exception:
log.exception('Problem occurred trying to invalidate hash cach for azurefs')
def file_hash(load, fnd):
'''
Return a file hash based on the hash type set in the master config
'''
if not all(x in load for x in ('path', 'saltenv')):
return '', None
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
hashdest = salt.utils.path.join(hash_cachedir,
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
if not os.path.exists(os.path.dirname(hashdest)):
os.makedirs(os.path.dirname(hashdest))
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(ret['hsum']))
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret
def file_list(load):
'''
Return a list of all files in a specified environment
'''
ret = set()
try:
for container in __opts__['azurefs']:
if container.get('saltenv', 'base') != load['saltenv']:
continue
container_list = _get_container_path(container) + '.list'
lk = container_list + '.lk'
salt.fileserver.wait_lock(lk, container_list, 5)
if not os.path.exists(container_list):
continue
with salt.utils.files.fopen(container_list, 'r') as fp_:
ret.update(set(salt.utils.json.load(fp_)))
except Exception as exc:
log.error('azurefs: an error ocurred retrieving file lists. '
'It should be resolved next time the fileserver '
'updates. Please do not manually modify the azurefs '
'cache directory.')
return list(ret)
def dir_list(load):
'''
Return a list of all directories in a specified environment
'''
ret = set()
files = file_list(load)
for f in files:
dirname = f
while dirname:
dirname = os.path.dirname(dirname)
if dirname:
ret.add(dirname)
return list(ret)
def _get_container_service(container):
'''
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order
'''
if 'account_key' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])
elif 'sas_token' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])
else:
account = azure.storage.CloudStorageAccount(container['account_name'])
blob_service = account.create_block_blob_service()
return blob_service
def _validate_config():
'''
Validate azurefs config, return False if it doesn't validate
'''
if not isinstance(__opts__['azurefs'], list):
log.error('azurefs configuration is not formed as a list, skipping azurefs')
return False
for container in __opts__['azurefs']:
if not isinstance(container, dict):
log.error(
'One or more entries in the azurefs configuration list are '
'not formed as a dict. Skipping azurefs: %s', container
)
return False
if 'account_name' not in container or 'container_name' not in container:
log.error(
'An azurefs container configuration is missing either an '
'account_name or a container_name: %s', container
)
return False
return True
|
saltstack/salt
|
salt/fileserver/azurefs.py
|
_get_container_service
|
python
|
def _get_container_service(container):
'''
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order
'''
if 'account_key' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])
elif 'sas_token' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])
else:
account = azure.storage.CloudStorageAccount(container['account_name'])
blob_service = account.create_block_blob_service()
return blob_service
|
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/azurefs.py#L355-L368
| null |
# -*- coding: utf-8 -*-
'''
The backend for serving files from the Azure blob storage service.
.. versionadded:: 2015.8.0
To enable, add ``azurefs`` to the :conf_master:`fileserver_backend` option in
the Master config file.
.. code-block:: yaml
fileserver_backend:
- azurefs
Starting in Salt 2018.3.0, this fileserver requires the standalone Azure
Storage SDK for Python. Theoretically any version >= v0.20.0 should work, but
it was developed against the v0.33.0 version.
Each storage container will be mapped to an environment. By default, containers
will be mapped to the ``base`` environment. You can override this behavior with
the ``saltenv`` configuration option. You can have an unlimited number of
storage containers, and can have a storage container serve multiple
environments, or have multiple storage containers mapped to the same
environment. Normal first-found rules apply, and storage containers are
searched in the order they are defined.
You must have either an account_key or a sas_token defined for each container,
if it is private. If you use a sas_token, it must have READ and LIST
permissions.
.. code-block:: yaml
azurefs:
- account_name: my_storage
account_key: 'fNH9cRp0+qVIVYZ+5rnZAhHc9ycOUcJnHtzpfOr0W0sxrtL2KVLuMe1xDfLwmfed+JJInZaEdWVCPHD4d/oqeA=='
container_name: my_container
- account_name: my_storage
sas_token: 'ss=b&sp=&sv=2015-07-08&sig=cohxXabx8FQdXsSEHyUXMjsSfNH2tZ2OB97Ou44pkRE%3D&srt=co&se=2017-04-18T21%3A38%3A01Z'
container_name: my_dev_container
saltenv: dev
- account_name: my_storage
container_name: my_public_container
.. note::
Do not include the leading ? for sas_token if generated from the web
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import logging
import os
import shutil
# Import salt libs
import salt.fileserver
import salt.utils.files
import salt.utils.gzip_util
import salt.utils.hashutils
import salt.utils.json
import salt.utils.path
import salt.utils.stringutils
from salt.utils.versions import LooseVersion
try:
import azure.storage
if LooseVersion(azure.storage.__version__) < LooseVersion('0.20.0'):
raise ImportError('azure.storage.__version__ must be >= 0.20.0')
HAS_AZURE = True
except (ImportError, AttributeError):
HAS_AZURE = False
# Import third party libs
from salt.ext import six
__virtualname__ = 'azurefs'
log = logging.getLogger()
def __virtual__():
'''
Only load if defined in fileserver_backend and azure.storage is present
'''
if __virtualname__ not in __opts__['fileserver_backend']:
return False
if not HAS_AZURE:
return False
if 'azurefs' not in __opts__:
return False
if not _validate_config():
return False
return True
def find_file(path, saltenv='base', **kwargs):
'''
Search the environment for the relative path
'''
fnd = {'path': '',
'rel': ''}
for container in __opts__.get('azurefs', []):
if container.get('saltenv', 'base') != saltenv:
continue
full = os.path.join(_get_container_path(container), path)
if os.path.isfile(full) and not salt.fileserver.is_file_ignored(
__opts__, path):
fnd['path'] = full
fnd['rel'] = path
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(full))
except Exception:
pass
return fnd
return fnd
def envs():
'''
Each container configuration can have an environment setting, or defaults
to base
'''
saltenvs = []
for container in __opts__.get('azurefs', []):
saltenvs.append(container.get('saltenv', 'base'))
# Remove duplicates
return list(set(saltenvs))
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
ret = {'data': '',
'dest': ''}
required_load_keys = ('path', 'loc', 'saltenv')
if not all(x in load for x in required_load_keys):
log.debug(
'Not all of the required keys present in payload. Missing: %s',
', '.join(required_load_keys.difference(load))
)
return ret
if not fnd['path']:
return ret
ret['dest'] = fnd['rel']
gzip = load.get('gzip', None)
fpath = os.path.normpath(fnd['path'])
with salt.utils.files.fopen(fpath, 'rb') as fp_:
fp_.seek(load['loc'])
data = fp_.read(__opts__['file_buffer_size'])
if data and six.PY3 and not salt.utils.files.is_binary(fpath):
data = data.decode(__salt_system_encoding__)
if gzip and data:
data = salt.utils.gzip_util.compress(data, gzip)
ret['gzip'] = gzip
ret['data'] = data
return ret
def update():
'''
Update caches of the storage containers.
Compares the md5 of the files on disk to the md5 of the blobs in the
container, and only updates if necessary.
Also processes deletions by walking the container caches and comparing
with the list of blobs in the container
'''
for container in __opts__['azurefs']:
path = _get_container_path(container)
try:
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
shutil.rmtree(path)
os.makedirs(path)
except Exception as exc:
log.exception('Error occurred creating cache directory for azurefs')
continue
blob_service = _get_container_service(container)
name = container['container_name']
try:
blob_list = blob_service.list_blobs(name)
except Exception as exc:
log.exception('Error occurred fetching blob list for azurefs')
continue
# Walk the cache directory searching for deletions
blob_names = [blob.name for blob in blob_list]
blob_set = set(blob_names)
for root, dirs, files in salt.utils.path.os_walk(path):
for f in files:
fname = os.path.join(root, f)
relpath = os.path.relpath(fname, path)
if relpath not in blob_set:
salt.fileserver.wait_lock(fname + '.lk', fname)
try:
os.unlink(fname)
except Exception:
pass
if not dirs and not files:
shutil.rmtree(root)
for blob in blob_list:
fname = os.path.join(path, blob.name)
update = False
if os.path.exists(fname):
# File exists, check the hashes
source_md5 = blob.properties.content_settings.content_md5
local_md5 = base64.b64encode(salt.utils.hashutils.get_hash(fname, 'md5').decode('hex'))
if local_md5 != source_md5:
update = True
else:
update = True
if update:
if not os.path.exists(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
# Lock writes
lk_fn = fname + '.lk'
salt.fileserver.wait_lock(lk_fn, fname)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
try:
blob_service.get_blob_to_path(name, blob.name, fname)
except Exception as exc:
log.exception('Error occurred fetching blob from azurefs')
continue
# Unlock writes
try:
os.unlink(lk_fn)
except Exception:
pass
# Write out file list
container_list = path + '.list'
lk_fn = container_list + '.lk'
salt.fileserver.wait_lock(lk_fn, container_list)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
with salt.utils.files.fopen(container_list, 'w') as fp_:
salt.utils.json.dump(blob_names, fp_)
try:
os.unlink(lk_fn)
except Exception:
pass
try:
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
shutil.rmtree(hash_cachedir)
except Exception:
log.exception('Problem occurred trying to invalidate hash cach for azurefs')
def file_hash(load, fnd):
'''
Return a file hash based on the hash type set in the master config
'''
if not all(x in load for x in ('path', 'saltenv')):
return '', None
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
hashdest = salt.utils.path.join(hash_cachedir,
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
if not os.path.exists(os.path.dirname(hashdest)):
os.makedirs(os.path.dirname(hashdest))
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(ret['hsum']))
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret
def file_list(load):
'''
Return a list of all files in a specified environment
'''
ret = set()
try:
for container in __opts__['azurefs']:
if container.get('saltenv', 'base') != load['saltenv']:
continue
container_list = _get_container_path(container) + '.list'
lk = container_list + '.lk'
salt.fileserver.wait_lock(lk, container_list, 5)
if not os.path.exists(container_list):
continue
with salt.utils.files.fopen(container_list, 'r') as fp_:
ret.update(set(salt.utils.json.load(fp_)))
except Exception as exc:
log.error('azurefs: an error ocurred retrieving file lists. '
'It should be resolved next time the fileserver '
'updates. Please do not manually modify the azurefs '
'cache directory.')
return list(ret)
def dir_list(load):
'''
Return a list of all directories in a specified environment
'''
ret = set()
files = file_list(load)
for f in files:
dirname = f
while dirname:
dirname = os.path.dirname(dirname)
if dirname:
ret.add(dirname)
return list(ret)
def _get_container_path(container):
'''
Get the cache path for the container in question
Cache paths are generate by combining the account name, container name,
and saltenv, separated by underscores
'''
root = os.path.join(__opts__['cachedir'], 'azurefs')
container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),
container.get('container_name', ''),
container.get('saltenv', 'base'))
return os.path.join(root, container_dir)
def _validate_config():
'''
Validate azurefs config, return False if it doesn't validate
'''
if not isinstance(__opts__['azurefs'], list):
log.error('azurefs configuration is not formed as a list, skipping azurefs')
return False
for container in __opts__['azurefs']:
if not isinstance(container, dict):
log.error(
'One or more entries in the azurefs configuration list are '
'not formed as a dict. Skipping azurefs: %s', container
)
return False
if 'account_name' not in container or 'container_name' not in container:
log.error(
'An azurefs container configuration is missing either an '
'account_name or a container_name: %s', container
)
return False
return True
|
saltstack/salt
|
salt/fileserver/azurefs.py
|
_validate_config
|
python
|
def _validate_config():
'''
Validate azurefs config, return False if it doesn't validate
'''
if not isinstance(__opts__['azurefs'], list):
log.error('azurefs configuration is not formed as a list, skipping azurefs')
return False
for container in __opts__['azurefs']:
if not isinstance(container, dict):
log.error(
'One or more entries in the azurefs configuration list are '
'not formed as a dict. Skipping azurefs: %s', container
)
return False
if 'account_name' not in container or 'container_name' not in container:
log.error(
'An azurefs container configuration is missing either an '
'account_name or a container_name: %s', container
)
return False
return True
|
Validate azurefs config, return False if it doesn't validate
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/azurefs.py#L371-L391
| null |
# -*- coding: utf-8 -*-
'''
The backend for serving files from the Azure blob storage service.
.. versionadded:: 2015.8.0
To enable, add ``azurefs`` to the :conf_master:`fileserver_backend` option in
the Master config file.
.. code-block:: yaml
fileserver_backend:
- azurefs
Starting in Salt 2018.3.0, this fileserver requires the standalone Azure
Storage SDK for Python. Theoretically any version >= v0.20.0 should work, but
it was developed against the v0.33.0 version.
Each storage container will be mapped to an environment. By default, containers
will be mapped to the ``base`` environment. You can override this behavior with
the ``saltenv`` configuration option. You can have an unlimited number of
storage containers, and can have a storage container serve multiple
environments, or have multiple storage containers mapped to the same
environment. Normal first-found rules apply, and storage containers are
searched in the order they are defined.
You must have either an account_key or a sas_token defined for each container,
if it is private. If you use a sas_token, it must have READ and LIST
permissions.
.. code-block:: yaml
azurefs:
- account_name: my_storage
account_key: 'fNH9cRp0+qVIVYZ+5rnZAhHc9ycOUcJnHtzpfOr0W0sxrtL2KVLuMe1xDfLwmfed+JJInZaEdWVCPHD4d/oqeA=='
container_name: my_container
- account_name: my_storage
sas_token: 'ss=b&sp=&sv=2015-07-08&sig=cohxXabx8FQdXsSEHyUXMjsSfNH2tZ2OB97Ou44pkRE%3D&srt=co&se=2017-04-18T21%3A38%3A01Z'
container_name: my_dev_container
saltenv: dev
- account_name: my_storage
container_name: my_public_container
.. note::
Do not include the leading ? for sas_token if generated from the web
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import logging
import os
import shutil
# Import salt libs
import salt.fileserver
import salt.utils.files
import salt.utils.gzip_util
import salt.utils.hashutils
import salt.utils.json
import salt.utils.path
import salt.utils.stringutils
from salt.utils.versions import LooseVersion
try:
import azure.storage
if LooseVersion(azure.storage.__version__) < LooseVersion('0.20.0'):
raise ImportError('azure.storage.__version__ must be >= 0.20.0')
HAS_AZURE = True
except (ImportError, AttributeError):
HAS_AZURE = False
# Import third party libs
from salt.ext import six
__virtualname__ = 'azurefs'
log = logging.getLogger()
def __virtual__():
'''
Only load if defined in fileserver_backend and azure.storage is present
'''
if __virtualname__ not in __opts__['fileserver_backend']:
return False
if not HAS_AZURE:
return False
if 'azurefs' not in __opts__:
return False
if not _validate_config():
return False
return True
def find_file(path, saltenv='base', **kwargs):
'''
Search the environment for the relative path
'''
fnd = {'path': '',
'rel': ''}
for container in __opts__.get('azurefs', []):
if container.get('saltenv', 'base') != saltenv:
continue
full = os.path.join(_get_container_path(container), path)
if os.path.isfile(full) and not salt.fileserver.is_file_ignored(
__opts__, path):
fnd['path'] = full
fnd['rel'] = path
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(full))
except Exception:
pass
return fnd
return fnd
def envs():
'''
Each container configuration can have an environment setting, or defaults
to base
'''
saltenvs = []
for container in __opts__.get('azurefs', []):
saltenvs.append(container.get('saltenv', 'base'))
# Remove duplicates
return list(set(saltenvs))
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
ret = {'data': '',
'dest': ''}
required_load_keys = ('path', 'loc', 'saltenv')
if not all(x in load for x in required_load_keys):
log.debug(
'Not all of the required keys present in payload. Missing: %s',
', '.join(required_load_keys.difference(load))
)
return ret
if not fnd['path']:
return ret
ret['dest'] = fnd['rel']
gzip = load.get('gzip', None)
fpath = os.path.normpath(fnd['path'])
with salt.utils.files.fopen(fpath, 'rb') as fp_:
fp_.seek(load['loc'])
data = fp_.read(__opts__['file_buffer_size'])
if data and six.PY3 and not salt.utils.files.is_binary(fpath):
data = data.decode(__salt_system_encoding__)
if gzip and data:
data = salt.utils.gzip_util.compress(data, gzip)
ret['gzip'] = gzip
ret['data'] = data
return ret
def update():
'''
Update caches of the storage containers.
Compares the md5 of the files on disk to the md5 of the blobs in the
container, and only updates if necessary.
Also processes deletions by walking the container caches and comparing
with the list of blobs in the container
'''
for container in __opts__['azurefs']:
path = _get_container_path(container)
try:
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
shutil.rmtree(path)
os.makedirs(path)
except Exception as exc:
log.exception('Error occurred creating cache directory for azurefs')
continue
blob_service = _get_container_service(container)
name = container['container_name']
try:
blob_list = blob_service.list_blobs(name)
except Exception as exc:
log.exception('Error occurred fetching blob list for azurefs')
continue
# Walk the cache directory searching for deletions
blob_names = [blob.name for blob in blob_list]
blob_set = set(blob_names)
for root, dirs, files in salt.utils.path.os_walk(path):
for f in files:
fname = os.path.join(root, f)
relpath = os.path.relpath(fname, path)
if relpath not in blob_set:
salt.fileserver.wait_lock(fname + '.lk', fname)
try:
os.unlink(fname)
except Exception:
pass
if not dirs and not files:
shutil.rmtree(root)
for blob in blob_list:
fname = os.path.join(path, blob.name)
update = False
if os.path.exists(fname):
# File exists, check the hashes
source_md5 = blob.properties.content_settings.content_md5
local_md5 = base64.b64encode(salt.utils.hashutils.get_hash(fname, 'md5').decode('hex'))
if local_md5 != source_md5:
update = True
else:
update = True
if update:
if not os.path.exists(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
# Lock writes
lk_fn = fname + '.lk'
salt.fileserver.wait_lock(lk_fn, fname)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
try:
blob_service.get_blob_to_path(name, blob.name, fname)
except Exception as exc:
log.exception('Error occurred fetching blob from azurefs')
continue
# Unlock writes
try:
os.unlink(lk_fn)
except Exception:
pass
# Write out file list
container_list = path + '.list'
lk_fn = container_list + '.lk'
salt.fileserver.wait_lock(lk_fn, container_list)
with salt.utils.files.fopen(lk_fn, 'w'):
pass
with salt.utils.files.fopen(container_list, 'w') as fp_:
salt.utils.json.dump(blob_names, fp_)
try:
os.unlink(lk_fn)
except Exception:
pass
try:
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
shutil.rmtree(hash_cachedir)
except Exception:
log.exception('Problem occurred trying to invalidate hash cach for azurefs')
def file_hash(load, fnd):
'''
Return a file hash based on the hash type set in the master config
'''
if not all(x in load for x in ('path', 'saltenv')):
return '', None
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
hashdest = salt.utils.path.join(hash_cachedir,
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
if not os.path.exists(os.path.dirname(hashdest)):
os.makedirs(os.path.dirname(hashdest))
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(ret['hsum']))
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret
def file_list(load):
'''
Return a list of all files in a specified environment
'''
ret = set()
try:
for container in __opts__['azurefs']:
if container.get('saltenv', 'base') != load['saltenv']:
continue
container_list = _get_container_path(container) + '.list'
lk = container_list + '.lk'
salt.fileserver.wait_lock(lk, container_list, 5)
if not os.path.exists(container_list):
continue
with salt.utils.files.fopen(container_list, 'r') as fp_:
ret.update(set(salt.utils.json.load(fp_)))
except Exception as exc:
log.error('azurefs: an error ocurred retrieving file lists. '
'It should be resolved next time the fileserver '
'updates. Please do not manually modify the azurefs '
'cache directory.')
return list(ret)
def dir_list(load):
'''
Return a list of all directories in a specified environment
'''
ret = set()
files = file_list(load)
for f in files:
dirname = f
while dirname:
dirname = os.path.dirname(dirname)
if dirname:
ret.add(dirname)
return list(ret)
def _get_container_path(container):
'''
Get the cache path for the container in question
Cache paths are generate by combining the account name, container name,
and saltenv, separated by underscores
'''
root = os.path.join(__opts__['cachedir'], 'azurefs')
container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),
container.get('container_name', ''),
container.get('saltenv', 'base'))
return os.path.join(root, container_dir)
def _get_container_service(container):
'''
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order
'''
if 'account_key' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])
elif 'sas_token' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])
else:
account = azure.storage.CloudStorageAccount(container['account_name'])
blob_service = account.create_block_blob_service()
return blob_service
|
saltstack/salt
|
salt/grains/smartos.py
|
_smartos_computenode_data
|
python
|
def _smartos_computenode_data():
'''
Return useful information from a SmartOS compute node
'''
# Provides:
# vms_total
# vms_running
# vms_stopped
# vms_type
# sdc_version
# vm_capable
# vm_hw_virt
grains = {}
# collect vm data
vms = {}
for vm in __salt__['cmd.run']('vmadm list -p -o uuid,alias,state,type').split("\n"):
vm = dict(list(zip(['uuid', 'alias', 'state', 'type'], vm.split(':'))))
vms[vm['uuid']] = vm
del vms[vm['uuid']]['uuid']
# set vm grains
grains['computenode_vms_total'] = len(vms)
grains['computenode_vms_running'] = 0
grains['computenode_vms_stopped'] = 0
grains['computenode_vms_type'] = {'KVM': 0, 'LX': 0, 'OS': 0}
for vm in vms:
if vms[vm]['state'].lower() == 'running':
grains['computenode_vms_running'] += 1
elif vms[vm]['state'].lower() == 'stopped':
grains['computenode_vms_stopped'] += 1
if vms[vm]['type'] not in grains['computenode_vms_type']:
# NOTE: be prepared for when bhyve gets its own type
grains['computenode_vms_type'][vms[vm]['type']] = 0
grains['computenode_vms_type'][vms[vm]['type']] += 1
# sysinfo derived grains
sysinfo = salt.utils.json.loads(__salt__['cmd.run']('sysinfo'))
grains['computenode_sdc_version'] = sysinfo['SDC Version']
grains['computenode_vm_capable'] = sysinfo['VM Capable']
if sysinfo['VM Capable']:
grains['computenode_vm_hw_virt'] = sysinfo['CPU Virtualization']
# sysinfo derived smbios grains
grains['manufacturer'] = sysinfo['Manufacturer']
grains['productname'] = sysinfo['Product']
grains['uuid'] = sysinfo['UUID']
return grains
|
Return useful information from a SmartOS compute node
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/smartos.py#L49-L99
| null |
# -*- coding: utf-8 -*-
'''
SmartOS grain provider
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.utils, salt.ext.six, salt.module.cmdmod
:platform: SmartOS
.. versionadded:: nitrogen
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import re
import logging
# Import salt libs
import salt.utils.dictupdate
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
__virtualname__ = 'smartos'
__salt__ = {
'cmd.run': salt.modules.cmdmod.run,
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load when we are on SmartOS
'''
if salt.utils.platform.is_smartos():
return __virtualname__
return False
def _smartos_zone_data():
'''
Return useful information from a SmartOS zone
'''
# Provides:
# zoneid
# zonename
# imageversion
grains = {
'zoneid': __salt__['cmd.run']('zoneadm list -p | awk -F: \'{ print $1 }\'', python_shell=True),
'zonename': __salt__['cmd.run']('zonename'),
'imageversion': 'Unknown',
}
imageversion = re.compile('Image:\\s(.+)')
if os.path.isfile('/etc/product'):
with salt.utils.files.fopen('/etc/product', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = imageversion.match(line)
if match:
grains['imageversion'] = match.group(1)
return grains
def _smartos_zone_pkgsrc_data():
'''
SmartOS zone pkgsrc information
'''
# Provides:
# pkgsrcversion
# pkgsrcpath
grains = {
'pkgsrcversion': 'Unknown',
'pkgsrcpath': 'Unknown',
}
pkgsrcversion = re.compile('^release:\\s(.+)')
if os.path.isfile('/etc/pkgsrc_version'):
with salt.utils.files.fopen('/etc/pkgsrc_version', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = pkgsrcversion.match(line)
if match:
grains['pkgsrcversion'] = match.group(1)
pkgsrcpath = re.compile('PKG_PATH=(.+)')
if os.path.isfile('/opt/local/etc/pkg_install.conf'):
with salt.utils.files.fopen('/opt/local/etc/pkg_install.conf', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = pkgsrcpath.match(line)
if match:
grains['pkgsrcpath'] = match.group(1)
return grains
def _smartos_zone_pkgin_data():
'''
SmartOS zone pkgsrc information
'''
# Provides:
# pkgin_repositories
grains = {
'pkgin_repositories': [],
}
pkginrepo = re.compile('^(?:https|http|ftp|file)://.*$')
if os.path.isfile('/opt/local/etc/pkgin/repositories.conf'):
with salt.utils.files.fopen('/opt/local/etc/pkgin/repositories.conf', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if pkginrepo.match(line):
grains['pkgin_repositories'].append(line)
return grains
def smartos():
'''
Provide grains for SmartOS
'''
grains = {}
if salt.utils.platform.is_smartos_zone():
grains = salt.utils.dictupdate.update(grains, _smartos_zone_data(), merge_lists=True)
grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgsrc_data(), merge_lists=True)
grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgin_data(), merge_lists=True)
elif salt.utils.platform.is_smartos_globalzone():
grains = salt.utils.dictupdate.update(grains, _smartos_computenode_data(), merge_lists=True)
return grains
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/grains/smartos.py
|
_smartos_zone_data
|
python
|
def _smartos_zone_data():
'''
Return useful information from a SmartOS zone
'''
# Provides:
# zoneid
# zonename
# imageversion
grains = {
'zoneid': __salt__['cmd.run']('zoneadm list -p | awk -F: \'{ print $1 }\'', python_shell=True),
'zonename': __salt__['cmd.run']('zonename'),
'imageversion': 'Unknown',
}
imageversion = re.compile('Image:\\s(.+)')
if os.path.isfile('/etc/product'):
with salt.utils.files.fopen('/etc/product', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = imageversion.match(line)
if match:
grains['imageversion'] = match.group(1)
return grains
|
Return useful information from a SmartOS zone
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/smartos.py#L102-L126
|
[
"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"
] |
# -*- coding: utf-8 -*-
'''
SmartOS grain provider
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.utils, salt.ext.six, salt.module.cmdmod
:platform: SmartOS
.. versionadded:: nitrogen
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import re
import logging
# Import salt libs
import salt.utils.dictupdate
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
__virtualname__ = 'smartos'
__salt__ = {
'cmd.run': salt.modules.cmdmod.run,
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load when we are on SmartOS
'''
if salt.utils.platform.is_smartos():
return __virtualname__
return False
def _smartos_computenode_data():
'''
Return useful information from a SmartOS compute node
'''
# Provides:
# vms_total
# vms_running
# vms_stopped
# vms_type
# sdc_version
# vm_capable
# vm_hw_virt
grains = {}
# collect vm data
vms = {}
for vm in __salt__['cmd.run']('vmadm list -p -o uuid,alias,state,type').split("\n"):
vm = dict(list(zip(['uuid', 'alias', 'state', 'type'], vm.split(':'))))
vms[vm['uuid']] = vm
del vms[vm['uuid']]['uuid']
# set vm grains
grains['computenode_vms_total'] = len(vms)
grains['computenode_vms_running'] = 0
grains['computenode_vms_stopped'] = 0
grains['computenode_vms_type'] = {'KVM': 0, 'LX': 0, 'OS': 0}
for vm in vms:
if vms[vm]['state'].lower() == 'running':
grains['computenode_vms_running'] += 1
elif vms[vm]['state'].lower() == 'stopped':
grains['computenode_vms_stopped'] += 1
if vms[vm]['type'] not in grains['computenode_vms_type']:
# NOTE: be prepared for when bhyve gets its own type
grains['computenode_vms_type'][vms[vm]['type']] = 0
grains['computenode_vms_type'][vms[vm]['type']] += 1
# sysinfo derived grains
sysinfo = salt.utils.json.loads(__salt__['cmd.run']('sysinfo'))
grains['computenode_sdc_version'] = sysinfo['SDC Version']
grains['computenode_vm_capable'] = sysinfo['VM Capable']
if sysinfo['VM Capable']:
grains['computenode_vm_hw_virt'] = sysinfo['CPU Virtualization']
# sysinfo derived smbios grains
grains['manufacturer'] = sysinfo['Manufacturer']
grains['productname'] = sysinfo['Product']
grains['uuid'] = sysinfo['UUID']
return grains
def _smartos_zone_pkgsrc_data():
'''
SmartOS zone pkgsrc information
'''
# Provides:
# pkgsrcversion
# pkgsrcpath
grains = {
'pkgsrcversion': 'Unknown',
'pkgsrcpath': 'Unknown',
}
pkgsrcversion = re.compile('^release:\\s(.+)')
if os.path.isfile('/etc/pkgsrc_version'):
with salt.utils.files.fopen('/etc/pkgsrc_version', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = pkgsrcversion.match(line)
if match:
grains['pkgsrcversion'] = match.group(1)
pkgsrcpath = re.compile('PKG_PATH=(.+)')
if os.path.isfile('/opt/local/etc/pkg_install.conf'):
with salt.utils.files.fopen('/opt/local/etc/pkg_install.conf', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = pkgsrcpath.match(line)
if match:
grains['pkgsrcpath'] = match.group(1)
return grains
def _smartos_zone_pkgin_data():
'''
SmartOS zone pkgsrc information
'''
# Provides:
# pkgin_repositories
grains = {
'pkgin_repositories': [],
}
pkginrepo = re.compile('^(?:https|http|ftp|file)://.*$')
if os.path.isfile('/opt/local/etc/pkgin/repositories.conf'):
with salt.utils.files.fopen('/opt/local/etc/pkgin/repositories.conf', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if pkginrepo.match(line):
grains['pkgin_repositories'].append(line)
return grains
def smartos():
'''
Provide grains for SmartOS
'''
grains = {}
if salt.utils.platform.is_smartos_zone():
grains = salt.utils.dictupdate.update(grains, _smartos_zone_data(), merge_lists=True)
grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgsrc_data(), merge_lists=True)
grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgin_data(), merge_lists=True)
elif salt.utils.platform.is_smartos_globalzone():
grains = salt.utils.dictupdate.update(grains, _smartos_computenode_data(), merge_lists=True)
return grains
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/grains/smartos.py
|
_smartos_zone_pkgsrc_data
|
python
|
def _smartos_zone_pkgsrc_data():
'''
SmartOS zone pkgsrc information
'''
# Provides:
# pkgsrcversion
# pkgsrcpath
grains = {
'pkgsrcversion': 'Unknown',
'pkgsrcpath': 'Unknown',
}
pkgsrcversion = re.compile('^release:\\s(.+)')
if os.path.isfile('/etc/pkgsrc_version'):
with salt.utils.files.fopen('/etc/pkgsrc_version', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = pkgsrcversion.match(line)
if match:
grains['pkgsrcversion'] = match.group(1)
pkgsrcpath = re.compile('PKG_PATH=(.+)')
if os.path.isfile('/opt/local/etc/pkg_install.conf'):
with salt.utils.files.fopen('/opt/local/etc/pkg_install.conf', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = pkgsrcpath.match(line)
if match:
grains['pkgsrcpath'] = match.group(1)
return grains
|
SmartOS zone pkgsrc information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/smartos.py#L129-L160
|
[
"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"
] |
# -*- coding: utf-8 -*-
'''
SmartOS grain provider
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.utils, salt.ext.six, salt.module.cmdmod
:platform: SmartOS
.. versionadded:: nitrogen
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import re
import logging
# Import salt libs
import salt.utils.dictupdate
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
__virtualname__ = 'smartos'
__salt__ = {
'cmd.run': salt.modules.cmdmod.run,
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load when we are on SmartOS
'''
if salt.utils.platform.is_smartos():
return __virtualname__
return False
def _smartos_computenode_data():
'''
Return useful information from a SmartOS compute node
'''
# Provides:
# vms_total
# vms_running
# vms_stopped
# vms_type
# sdc_version
# vm_capable
# vm_hw_virt
grains = {}
# collect vm data
vms = {}
for vm in __salt__['cmd.run']('vmadm list -p -o uuid,alias,state,type').split("\n"):
vm = dict(list(zip(['uuid', 'alias', 'state', 'type'], vm.split(':'))))
vms[vm['uuid']] = vm
del vms[vm['uuid']]['uuid']
# set vm grains
grains['computenode_vms_total'] = len(vms)
grains['computenode_vms_running'] = 0
grains['computenode_vms_stopped'] = 0
grains['computenode_vms_type'] = {'KVM': 0, 'LX': 0, 'OS': 0}
for vm in vms:
if vms[vm]['state'].lower() == 'running':
grains['computenode_vms_running'] += 1
elif vms[vm]['state'].lower() == 'stopped':
grains['computenode_vms_stopped'] += 1
if vms[vm]['type'] not in grains['computenode_vms_type']:
# NOTE: be prepared for when bhyve gets its own type
grains['computenode_vms_type'][vms[vm]['type']] = 0
grains['computenode_vms_type'][vms[vm]['type']] += 1
# sysinfo derived grains
sysinfo = salt.utils.json.loads(__salt__['cmd.run']('sysinfo'))
grains['computenode_sdc_version'] = sysinfo['SDC Version']
grains['computenode_vm_capable'] = sysinfo['VM Capable']
if sysinfo['VM Capable']:
grains['computenode_vm_hw_virt'] = sysinfo['CPU Virtualization']
# sysinfo derived smbios grains
grains['manufacturer'] = sysinfo['Manufacturer']
grains['productname'] = sysinfo['Product']
grains['uuid'] = sysinfo['UUID']
return grains
def _smartos_zone_data():
'''
Return useful information from a SmartOS zone
'''
# Provides:
# zoneid
# zonename
# imageversion
grains = {
'zoneid': __salt__['cmd.run']('zoneadm list -p | awk -F: \'{ print $1 }\'', python_shell=True),
'zonename': __salt__['cmd.run']('zonename'),
'imageversion': 'Unknown',
}
imageversion = re.compile('Image:\\s(.+)')
if os.path.isfile('/etc/product'):
with salt.utils.files.fopen('/etc/product', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = imageversion.match(line)
if match:
grains['imageversion'] = match.group(1)
return grains
def _smartos_zone_pkgin_data():
'''
SmartOS zone pkgsrc information
'''
# Provides:
# pkgin_repositories
grains = {
'pkgin_repositories': [],
}
pkginrepo = re.compile('^(?:https|http|ftp|file)://.*$')
if os.path.isfile('/opt/local/etc/pkgin/repositories.conf'):
with salt.utils.files.fopen('/opt/local/etc/pkgin/repositories.conf', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if pkginrepo.match(line):
grains['pkgin_repositories'].append(line)
return grains
def smartos():
'''
Provide grains for SmartOS
'''
grains = {}
if salt.utils.platform.is_smartos_zone():
grains = salt.utils.dictupdate.update(grains, _smartos_zone_data(), merge_lists=True)
grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgsrc_data(), merge_lists=True)
grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgin_data(), merge_lists=True)
elif salt.utils.platform.is_smartos_globalzone():
grains = salt.utils.dictupdate.update(grains, _smartos_computenode_data(), merge_lists=True)
return grains
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/grains/smartos.py
|
_smartos_zone_pkgin_data
|
python
|
def _smartos_zone_pkgin_data():
'''
SmartOS zone pkgsrc information
'''
# Provides:
# pkgin_repositories
grains = {
'pkgin_repositories': [],
}
pkginrepo = re.compile('^(?:https|http|ftp|file)://.*$')
if os.path.isfile('/opt/local/etc/pkgin/repositories.conf'):
with salt.utils.files.fopen('/opt/local/etc/pkgin/repositories.conf', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if pkginrepo.match(line):
grains['pkgin_repositories'].append(line)
return grains
|
SmartOS zone pkgsrc information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/smartos.py#L163-L182
|
[
"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"
] |
# -*- coding: utf-8 -*-
'''
SmartOS grain provider
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.utils, salt.ext.six, salt.module.cmdmod
:platform: SmartOS
.. versionadded:: nitrogen
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import re
import logging
# Import salt libs
import salt.utils.dictupdate
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
__virtualname__ = 'smartos'
__salt__ = {
'cmd.run': salt.modules.cmdmod.run,
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load when we are on SmartOS
'''
if salt.utils.platform.is_smartos():
return __virtualname__
return False
def _smartos_computenode_data():
'''
Return useful information from a SmartOS compute node
'''
# Provides:
# vms_total
# vms_running
# vms_stopped
# vms_type
# sdc_version
# vm_capable
# vm_hw_virt
grains = {}
# collect vm data
vms = {}
for vm in __salt__['cmd.run']('vmadm list -p -o uuid,alias,state,type').split("\n"):
vm = dict(list(zip(['uuid', 'alias', 'state', 'type'], vm.split(':'))))
vms[vm['uuid']] = vm
del vms[vm['uuid']]['uuid']
# set vm grains
grains['computenode_vms_total'] = len(vms)
grains['computenode_vms_running'] = 0
grains['computenode_vms_stopped'] = 0
grains['computenode_vms_type'] = {'KVM': 0, 'LX': 0, 'OS': 0}
for vm in vms:
if vms[vm]['state'].lower() == 'running':
grains['computenode_vms_running'] += 1
elif vms[vm]['state'].lower() == 'stopped':
grains['computenode_vms_stopped'] += 1
if vms[vm]['type'] not in grains['computenode_vms_type']:
# NOTE: be prepared for when bhyve gets its own type
grains['computenode_vms_type'][vms[vm]['type']] = 0
grains['computenode_vms_type'][vms[vm]['type']] += 1
# sysinfo derived grains
sysinfo = salt.utils.json.loads(__salt__['cmd.run']('sysinfo'))
grains['computenode_sdc_version'] = sysinfo['SDC Version']
grains['computenode_vm_capable'] = sysinfo['VM Capable']
if sysinfo['VM Capable']:
grains['computenode_vm_hw_virt'] = sysinfo['CPU Virtualization']
# sysinfo derived smbios grains
grains['manufacturer'] = sysinfo['Manufacturer']
grains['productname'] = sysinfo['Product']
grains['uuid'] = sysinfo['UUID']
return grains
def _smartos_zone_data():
'''
Return useful information from a SmartOS zone
'''
# Provides:
# zoneid
# zonename
# imageversion
grains = {
'zoneid': __salt__['cmd.run']('zoneadm list -p | awk -F: \'{ print $1 }\'', python_shell=True),
'zonename': __salt__['cmd.run']('zonename'),
'imageversion': 'Unknown',
}
imageversion = re.compile('Image:\\s(.+)')
if os.path.isfile('/etc/product'):
with salt.utils.files.fopen('/etc/product', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = imageversion.match(line)
if match:
grains['imageversion'] = match.group(1)
return grains
def _smartos_zone_pkgsrc_data():
'''
SmartOS zone pkgsrc information
'''
# Provides:
# pkgsrcversion
# pkgsrcpath
grains = {
'pkgsrcversion': 'Unknown',
'pkgsrcpath': 'Unknown',
}
pkgsrcversion = re.compile('^release:\\s(.+)')
if os.path.isfile('/etc/pkgsrc_version'):
with salt.utils.files.fopen('/etc/pkgsrc_version', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = pkgsrcversion.match(line)
if match:
grains['pkgsrcversion'] = match.group(1)
pkgsrcpath = re.compile('PKG_PATH=(.+)')
if os.path.isfile('/opt/local/etc/pkg_install.conf'):
with salt.utils.files.fopen('/opt/local/etc/pkg_install.conf', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = pkgsrcpath.match(line)
if match:
grains['pkgsrcpath'] = match.group(1)
return grains
def smartos():
'''
Provide grains for SmartOS
'''
grains = {}
if salt.utils.platform.is_smartos_zone():
grains = salt.utils.dictupdate.update(grains, _smartos_zone_data(), merge_lists=True)
grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgsrc_data(), merge_lists=True)
grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgin_data(), merge_lists=True)
elif salt.utils.platform.is_smartos_globalzone():
grains = salt.utils.dictupdate.update(grains, _smartos_computenode_data(), merge_lists=True)
return grains
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/grains/smartos.py
|
smartos
|
python
|
def smartos():
'''
Provide grains for SmartOS
'''
grains = {}
if salt.utils.platform.is_smartos_zone():
grains = salt.utils.dictupdate.update(grains, _smartos_zone_data(), merge_lists=True)
grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgsrc_data(), merge_lists=True)
grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgin_data(), merge_lists=True)
elif salt.utils.platform.is_smartos_globalzone():
grains = salt.utils.dictupdate.update(grains, _smartos_computenode_data(), merge_lists=True)
return grains
|
Provide grains for SmartOS
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/smartos.py#L185-L198
|
[
"def _smartos_zone_data():\n '''\n Return useful information from a SmartOS zone\n '''\n # Provides:\n # zoneid\n # zonename\n # imageversion\n\n grains = {\n 'zoneid': __salt__['cmd.run']('zoneadm list -p | awk -F: \\'{ print $1 }\\'', python_shell=True),\n 'zonename': __salt__['cmd.run']('zonename'),\n 'imageversion': 'Unknown',\n }\n\n imageversion = re.compile('Image:\\\\s(.+)')\n if os.path.isfile('/etc/product'):\n with salt.utils.files.fopen('/etc/product', 'r') as fp_:\n for line in fp_:\n line = salt.utils.stringutils.to_unicode(line)\n match = imageversion.match(line)\n if match:\n grains['imageversion'] = match.group(1)\n\n return grains\n",
"def _smartos_zone_pkgsrc_data():\n '''\n SmartOS zone pkgsrc information\n '''\n # Provides:\n # pkgsrcversion\n # pkgsrcpath\n\n grains = {\n 'pkgsrcversion': 'Unknown',\n 'pkgsrcpath': 'Unknown',\n }\n\n pkgsrcversion = re.compile('^release:\\\\s(.+)')\n if os.path.isfile('/etc/pkgsrc_version'):\n with salt.utils.files.fopen('/etc/pkgsrc_version', 'r') as fp_:\n for line in fp_:\n line = salt.utils.stringutils.to_unicode(line)\n match = pkgsrcversion.match(line)\n if match:\n grains['pkgsrcversion'] = match.group(1)\n\n pkgsrcpath = re.compile('PKG_PATH=(.+)')\n if os.path.isfile('/opt/local/etc/pkg_install.conf'):\n with salt.utils.files.fopen('/opt/local/etc/pkg_install.conf', 'r') as fp_:\n for line in fp_:\n line = salt.utils.stringutils.to_unicode(line)\n match = pkgsrcpath.match(line)\n if match:\n grains['pkgsrcpath'] = match.group(1)\n\n return grains\n",
"def _smartos_zone_pkgin_data():\n '''\n SmartOS zone pkgsrc information\n '''\n # Provides:\n # pkgin_repositories\n\n grains = {\n 'pkgin_repositories': [],\n }\n\n pkginrepo = re.compile('^(?:https|http|ftp|file)://.*$')\n if os.path.isfile('/opt/local/etc/pkgin/repositories.conf'):\n with salt.utils.files.fopen('/opt/local/etc/pkgin/repositories.conf', 'r') as fp_:\n for line in fp_:\n line = salt.utils.stringutils.to_unicode(line)\n if pkginrepo.match(line):\n grains['pkgin_repositories'].append(line)\n\n return grains\n"
] |
# -*- coding: utf-8 -*-
'''
SmartOS grain provider
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.utils, salt.ext.six, salt.module.cmdmod
:platform: SmartOS
.. versionadded:: nitrogen
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import re
import logging
# Import salt libs
import salt.utils.dictupdate
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
__virtualname__ = 'smartos'
__salt__ = {
'cmd.run': salt.modules.cmdmod.run,
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load when we are on SmartOS
'''
if salt.utils.platform.is_smartos():
return __virtualname__
return False
def _smartos_computenode_data():
'''
Return useful information from a SmartOS compute node
'''
# Provides:
# vms_total
# vms_running
# vms_stopped
# vms_type
# sdc_version
# vm_capable
# vm_hw_virt
grains = {}
# collect vm data
vms = {}
for vm in __salt__['cmd.run']('vmadm list -p -o uuid,alias,state,type').split("\n"):
vm = dict(list(zip(['uuid', 'alias', 'state', 'type'], vm.split(':'))))
vms[vm['uuid']] = vm
del vms[vm['uuid']]['uuid']
# set vm grains
grains['computenode_vms_total'] = len(vms)
grains['computenode_vms_running'] = 0
grains['computenode_vms_stopped'] = 0
grains['computenode_vms_type'] = {'KVM': 0, 'LX': 0, 'OS': 0}
for vm in vms:
if vms[vm]['state'].lower() == 'running':
grains['computenode_vms_running'] += 1
elif vms[vm]['state'].lower() == 'stopped':
grains['computenode_vms_stopped'] += 1
if vms[vm]['type'] not in grains['computenode_vms_type']:
# NOTE: be prepared for when bhyve gets its own type
grains['computenode_vms_type'][vms[vm]['type']] = 0
grains['computenode_vms_type'][vms[vm]['type']] += 1
# sysinfo derived grains
sysinfo = salt.utils.json.loads(__salt__['cmd.run']('sysinfo'))
grains['computenode_sdc_version'] = sysinfo['SDC Version']
grains['computenode_vm_capable'] = sysinfo['VM Capable']
if sysinfo['VM Capable']:
grains['computenode_vm_hw_virt'] = sysinfo['CPU Virtualization']
# sysinfo derived smbios grains
grains['manufacturer'] = sysinfo['Manufacturer']
grains['productname'] = sysinfo['Product']
grains['uuid'] = sysinfo['UUID']
return grains
def _smartos_zone_data():
'''
Return useful information from a SmartOS zone
'''
# Provides:
# zoneid
# zonename
# imageversion
grains = {
'zoneid': __salt__['cmd.run']('zoneadm list -p | awk -F: \'{ print $1 }\'', python_shell=True),
'zonename': __salt__['cmd.run']('zonename'),
'imageversion': 'Unknown',
}
imageversion = re.compile('Image:\\s(.+)')
if os.path.isfile('/etc/product'):
with salt.utils.files.fopen('/etc/product', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = imageversion.match(line)
if match:
grains['imageversion'] = match.group(1)
return grains
def _smartos_zone_pkgsrc_data():
'''
SmartOS zone pkgsrc information
'''
# Provides:
# pkgsrcversion
# pkgsrcpath
grains = {
'pkgsrcversion': 'Unknown',
'pkgsrcpath': 'Unknown',
}
pkgsrcversion = re.compile('^release:\\s(.+)')
if os.path.isfile('/etc/pkgsrc_version'):
with salt.utils.files.fopen('/etc/pkgsrc_version', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = pkgsrcversion.match(line)
if match:
grains['pkgsrcversion'] = match.group(1)
pkgsrcpath = re.compile('PKG_PATH=(.+)')
if os.path.isfile('/opt/local/etc/pkg_install.conf'):
with salt.utils.files.fopen('/opt/local/etc/pkg_install.conf', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
match = pkgsrcpath.match(line)
if match:
grains['pkgsrcpath'] = match.group(1)
return grains
def _smartos_zone_pkgin_data():
'''
SmartOS zone pkgsrc information
'''
# Provides:
# pkgin_repositories
grains = {
'pkgin_repositories': [],
}
pkginrepo = re.compile('^(?:https|http|ftp|file)://.*$')
if os.path.isfile('/opt/local/etc/pkgin/repositories.conf'):
with salt.utils.files.fopen('/opt/local/etc/pkgin/repositories.conf', 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if pkginrepo.match(line):
grains['pkgin_repositories'].append(line)
return grains
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/engines/logentries.py
|
start
|
python
|
def start(endpoint='data.logentries.com',
port=10000,
token=None,
tag='salt/engines/logentries'):
'''
Listen to salt events and forward them to Logentries
'''
if __opts__.get('id').endswith('_master'):
event_bus = salt.utils.event.get_master_event(
__opts__,
__opts__['sock_dir'],
listen=True)
else:
event_bus = salt.utils.event.get_event(
'minion',
transport=__opts__['transport'],
opts=__opts__,
sock_dir=__opts__['sock_dir'],
listen=True)
log.debug('Logentries engine started')
try:
val = uuid.UUID(token)
except ValueError:
log.warning('Not a valid logentries token')
appender = SocketAppender(verbose=False, LE_API=endpoint, LE_PORT=port)
appender.reopen_connection()
while True:
event = event_bus.get_event()
if event:
# future lint: disable=blacklisted-function
msg = str(' ').join((
salt.utils.stringutils.to_str(token),
salt.utils.stringutils.to_str(tag),
salt.utils.json.dumps(event)
))
# future lint: enable=blacklisted-function
appender.put(msg)
appender.close_connection()
|
Listen to salt events and forward them to Logentries
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/logentries.py#L174-L215
|
[
"def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False, keep_loop=False):\n '''\n Return an event object suitable for the named transport\n '''\n # TODO: AIO core is separate from transport\n if opts['transport'] in ('zeromq', 'tcp', 'detect'):\n return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, raise_errors=raise_errors, keep_loop=keep_loop)\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 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 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 reopen_connection(self):\n self.close_connection()\n\n root_delay = self.MIN_DELAY\n while True:\n try:\n self.open_connection()\n return\n except Exception:\n if self.verbose:\n log.warning('Unable to connect to Logentries')\n\n root_delay *= 2\n if root_delay > self.MAX_DELAY:\n root_delay = self.MAX_DELAY\n\n wait_for = root_delay + random.uniform(0, root_delay)\n\n try:\n time.sleep(wait_for)\n except KeyboardInterrupt:\n raise\n",
"def put(self, data):\n # Replace newlines with Unicode line separator for multi-line events\n multiline = data.replace('\\n', self.LINE_SEP) + str('\\n') # future lint: disable=blacklisted-function\n # Send data, reconnect if needed\n while True:\n try:\n self._conn.send(multiline)\n except socket.error:\n self.reopen_connection()\n continue\n break\n\n self.close_connection()\n"
] |
# -*- coding: utf-8 -*-
'''
An engine that sends events to the Logentries logging service.
:maintainer: Jimmy Tang (jimmy_tang@rapid7.com)
:maturity: New
:depends: ssl, certifi
:platform: all
.. versionadded: 2016.3.0
To enable this engine the master and/or minion will need the following
python libraries
ssl
certifi
If you are running a new enough version of python then the ssl library
will be present already.
You will also need the following values configured in the minion or
master config.
:configuration:
Example configuration
.. code-block:: yaml
engines:
- logentries:
endpoint: data.logentries.com
port: 10000
token: 057af3e2-1c05-47c5-882a-5cd644655dbf
The 'token' can be obtained from the Logentries service.
To test this engine
.. code-block:: bash
salt '*' test.ping cmd.run uptime
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.event
import salt.utils.json
# Import third party libs
try:
import certifi
HAS_CERTIFI = True
except ImportError:
HAS_CERTIFI = False
# This is here for older python installs, it is needed to setup an
# encrypted tcp connection
try:
import ssl
HAS_SSL = True
except ImportError: # for systems without TLS support.
HAS_SSL = False
# Import Python libs
import socket
import random
import time
import uuid
import logging
log = logging.getLogger(__name__)
def __virtual__():
return True if HAS_CERTIFI and HAS_SSL else False
class PlainTextSocketAppender(object):
def __init__(self,
verbose=True,
LE_API='data.logentries.com',
LE_PORT=80,
LE_TLS_PORT=443):
self.LE_API = LE_API
self.LE_PORT = LE_PORT
self.LE_TLS_PORT = LE_TLS_PORT
self.MIN_DELAY = 0.1
self.MAX_DELAY = 10
# Error message displayed when an incorrect Token has been detected
self.INVALID_TOKEN = ("\n\nIt appears the LOGENTRIES_TOKEN "
"parameter you entered is incorrect!\n\n")
# Encoded unicode line separator
self.LINE_SEP = salt.utils.stringutils.to_str('\u2028')
self.verbose = verbose
self._conn = None
def open_connection(self):
self._conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._conn.connect((self.LE_API, self.LE_PORT))
def reopen_connection(self):
self.close_connection()
root_delay = self.MIN_DELAY
while True:
try:
self.open_connection()
return
except Exception:
if self.verbose:
log.warning('Unable to connect to Logentries')
root_delay *= 2
if root_delay > self.MAX_DELAY:
root_delay = self.MAX_DELAY
wait_for = root_delay + random.uniform(0, root_delay)
try:
time.sleep(wait_for)
except KeyboardInterrupt:
raise
def close_connection(self):
if self._conn is not None:
self._conn.close()
def put(self, data):
# Replace newlines with Unicode line separator for multi-line events
multiline = data.replace('\n', self.LINE_SEP) + str('\n') # future lint: disable=blacklisted-function
# Send data, reconnect if needed
while True:
try:
self._conn.send(multiline)
except socket.error:
self.reopen_connection()
continue
break
self.close_connection()
try:
import ssl
HAS_SSL = True
except ImportError: # for systems without TLS support.
SocketAppender = PlainTextSocketAppender
HAS_SSL = False
else:
class TLSSocketAppender(PlainTextSocketAppender):
def open_connection(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = ssl.wrap_socket(
sock=sock,
keyfile=None,
certfile=None,
server_side=False,
cert_reqs=ssl.CERT_REQUIRED,
ssl_version=getattr(
ssl, 'PROTOCOL_TLSv1_2', ssl.PROTOCOL_TLSv1),
ca_certs=certifi.where(),
do_handshake_on_connect=True,
suppress_ragged_eofs=True, )
sock.connect((self.LE_API, self.LE_TLS_PORT))
self._conn = sock
SocketAppender = TLSSocketAppender
|
saltstack/salt
|
salt/states/glusterfs.py
|
peered
|
python
|
def peered(name):
'''
Check if node is peered.
name
The remote host with which to peer.
.. code-block:: yaml
peer-cluster:
glusterfs.peered:
- name: two
peer-clusters:
glusterfs.peered:
- names:
- one
- two
- three
- four
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
suc.check_name(name, 'a-zA-Z0-9._-')
except SaltCloudException:
ret['comment'] = 'Invalid characters in peer name.'
return ret
# Check if the name resolves to one of this minion IP addresses
name_ips = salt.utils.network.host_to_ips(name)
if name_ips is not None:
# if it is None, it means resolution fails, let's not hide
# it from the user.
this_ips = set(salt.utils.network.ip_addrs())
this_ips.update(salt.utils.network.ip_addrs6())
if this_ips.intersection(name_ips):
ret['result'] = True
ret['comment'] = 'Peering with localhost is not needed'
return ret
peers = __salt__['glusterfs.peer_status']()
if peers and any(name in v['hostnames'] for v in peers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} already peered'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Peer {0} will be added.'.format(name)
ret['result'] = None
return ret
if not __salt__['glusterfs.peer'](name):
ret['comment'] = 'Failed to peer with {0}, please check logs for errors'.format(name)
return ret
# Double check that the action succeeded
newpeers = __salt__['glusterfs.peer_status']()
if newpeers and any(name in v['hostnames'] for v in newpeers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} successfully peered'.format(name)
ret['changes'] = {'new': newpeers, 'old': peers}
else:
ret['comment'] = 'Host {0} was successfully peered but did not appear in the list of peers'.format(name)
return ret
|
Check if node is peered.
name
The remote host with which to peer.
.. code-block:: yaml
peer-cluster:
glusterfs.peered:
- name: two
peer-clusters:
glusterfs.peered:
- names:
- one
- two
- three
- four
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glusterfs.py#L40-L108
|
[
"def check_name(name, safe_chars):\n '''\n Check whether the specified name contains invalid characters\n '''\n regexp = re.compile('[^{0}]'.format(safe_chars))\n if regexp.search(name):\n raise SaltCloudException(\n '{0} contains characters not supported by this cloud provider. '\n 'Valid characters are: {1}'.format(\n name, safe_chars\n )\n )\n",
"def ip_addrs(interface=None, include_loopback=False, interface_data=None):\n '''\n Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is\n ignored, unless 'include_loopback=True' is indicated. If 'interface' is\n provided, then only IP addresses from that interface will be returned.\n '''\n return _ip_addrs(interface, include_loopback, interface_data, 'inet')\n",
"def ip_addrs6(interface=None, include_loopback=False, interface_data=None):\n '''\n Returns a list of IPv6 addresses assigned to the host. ::1 is ignored,\n unless 'include_loopback=True' is indicated. If 'interface' is provided,\n then only IP addresses from that interface will be returned.\n '''\n return _ip_addrs(interface, include_loopback, interface_data, 'inet6')\n",
"def host_to_ips(host):\n '''\n Returns a list of IP addresses of a given hostname or None if not found.\n '''\n ips = []\n try:\n for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(\n host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM):\n if family == socket.AF_INET:\n ip, port = sockaddr\n elif family == socket.AF_INET6:\n ip, port, flow_info, scope_id = sockaddr\n ips.append(ip)\n if not ips:\n ips = None\n except Exception:\n ips = None\n return ips\n"
] |
# -*- coding: utf-8 -*-
'''
Manage GlusterFS pool.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, \
print_function, generators
import logging
# Import salt libs
import salt.utils.cloud as suc
import salt.utils.network
from salt.exceptions import SaltCloudException
log = logging.getLogger(__name__)
RESULT_CODES = [
'Peer {0} added successfully.',
'Probe on localhost not needed',
'Host {0} is already in the peer group',
'Host {0} is already part of another cluster',
'Volume on {0} conflicts with existing volumes',
'UUID of {0} is the same as local uuid',
'{0} responded with "unknown peer". This could happen if {0} doesn\'t have localhost defined',
'Failed to add peer. Information on {0}\'s logs',
'Cluster quorum is not met. Changing peers is not allowed.',
'Failed to update list of missed snapshots from {0}',
'Conflict comparing list of snapshots from {0}',
'Peer is already being detached from cluster.']
def __virtual__():
'''
Only load this module if the gluster command exists
'''
return 'glusterfs' if 'glusterfs.list_volumes' in __salt__ else False
def volume_present(name, bricks, stripe=False, replica=False, device_vg=False,
transport='tcp', start=False, force=False, arbiter=False):
'''
Ensure that the volume exists
name
name of the volume
bricks
list of brick paths
replica
replica count for volume
arbiter
use every third brick as arbiter (metadata only)
.. versionadded:: 2019.2.0
start
ensure that the volume is also started
.. code-block:: yaml
myvolume:
glusterfs.volume_present:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.volume_present:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- replica: 2
- start: True
Replicated Volume with arbiter brick:
glusterfs.volume_present:
- name: volume3
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- host3:/srv/gluster/drive4
- replica: 3
- arbiter: True
- start: True
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
if suc.check_name(name, 'a-zA-Z0-9._-'):
ret['comment'] = 'Invalid characters in volume name.'
return ret
volumes = __salt__['glusterfs.list_volumes']()
if name not in volumes:
if __opts__['test']:
comment = 'Volume {0} will be created'.format(name)
if start:
comment += ' and started'
ret['comment'] = comment
ret['result'] = None
return ret
vol_created = __salt__['glusterfs.create_volume'](
name, bricks, stripe,
replica, device_vg,
transport, start, force, arbiter)
if not vol_created:
ret['comment'] = 'Creation of volume {0} failed'.format(name)
return ret
old_volumes = volumes
volumes = __salt__['glusterfs.list_volumes']()
if name in volumes:
ret['changes'] = {'new': volumes, 'old': old_volumes}
ret['comment'] = 'Volume {0} is created'.format(name)
else:
ret['comment'] = 'Volume {0} already exists'.format(name)
if start:
if __opts__['test']:
# volume already exists
ret['comment'] = ret['comment'] + ' and will be started'
ret['result'] = None
return ret
if int(__salt__['glusterfs.info']()[name]['status']) == 1:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is started'
else:
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is now started'
if not ret['changes']:
ret['changes'] = {'new': 'started', 'old': 'stopped'}
else:
ret['comment'] = ret['comment'] + ' but failed to start. Check logs for further information'
return ret
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = True
return ret
def started(name):
'''
Check if volume has been started
name
name of the volume
.. code-block:: yaml
mycluster:
glusterfs.started: []
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['result'] = False
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) == 1:
ret['comment'] = 'Volume {0} is already started'.format(name)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Volume {0} will be started'.format(name)
ret['result'] = None
return ret
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = 'Volume {0} is started'.format(name)
ret['change'] = {'new': 'started', 'old': 'stopped'}
else:
ret['result'] = False
ret['comment'] = 'Failed to start volume {0}'.format(name)
return ret
def add_volume_bricks(name, bricks):
'''
Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
.. code-block:: yaml
myvolume:
glusterfs.add_volume_bricks:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.add_volume_bricks:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) != 1:
ret['comment'] = 'Volume {0} is not started'.format(name)
return ret
current_bricks = [brick['path'] for brick in volinfo[name]['bricks'].values()]
if not set(bricks) - set(current_bricks):
ret['result'] = True
ret['comment'] = 'Bricks already added in volume {0}'.format(name)
return ret
bricks_added = __salt__['glusterfs.add_volume_bricks'](name, bricks)
if bricks_added:
ret['result'] = True
ret['comment'] = 'Bricks successfully added to volume {0}'.format(name)
new_bricks = [brick['path'] for brick in __salt__['glusterfs.info']()[name]['bricks'].values()]
ret['changes'] = {'new': new_bricks, 'old': current_bricks}
return ret
ret['comment'] = 'Adding bricks to volume {0} failed'.format(name)
return ret
def op_version(name, version):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
version
Version to which the cluster.op-version should be set
.. code-block:: yaml
myvolume:
glusterfs.op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
if current == version:
ret['comment'] = 'Glusterfs cluster.op-version for {0} already set to {1}'.format(name, version)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version for {0} to {1}.'.format(name, version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': version}
ret['result'] = True
return ret
def max_op_version(name):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
.. code-block:: yaml
myvolume:
glusterfs.max_op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
try:
max_version = int(__salt__['glusterfs.get_max_op_version']())
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_max_op_version']()[1]
return ret
if current == max_version:
ret['comment'] = 'The cluster.op-version is already set to the cluster.max-op-version of {0}'.format(current)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version to {0}.'.format(max_version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](max_version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': max_version}
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/glusterfs.py
|
volume_present
|
python
|
def volume_present(name, bricks, stripe=False, replica=False, device_vg=False,
transport='tcp', start=False, force=False, arbiter=False):
'''
Ensure that the volume exists
name
name of the volume
bricks
list of brick paths
replica
replica count for volume
arbiter
use every third brick as arbiter (metadata only)
.. versionadded:: 2019.2.0
start
ensure that the volume is also started
.. code-block:: yaml
myvolume:
glusterfs.volume_present:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.volume_present:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- replica: 2
- start: True
Replicated Volume with arbiter brick:
glusterfs.volume_present:
- name: volume3
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- host3:/srv/gluster/drive4
- replica: 3
- arbiter: True
- start: True
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
if suc.check_name(name, 'a-zA-Z0-9._-'):
ret['comment'] = 'Invalid characters in volume name.'
return ret
volumes = __salt__['glusterfs.list_volumes']()
if name not in volumes:
if __opts__['test']:
comment = 'Volume {0} will be created'.format(name)
if start:
comment += ' and started'
ret['comment'] = comment
ret['result'] = None
return ret
vol_created = __salt__['glusterfs.create_volume'](
name, bricks, stripe,
replica, device_vg,
transport, start, force, arbiter)
if not vol_created:
ret['comment'] = 'Creation of volume {0} failed'.format(name)
return ret
old_volumes = volumes
volumes = __salt__['glusterfs.list_volumes']()
if name in volumes:
ret['changes'] = {'new': volumes, 'old': old_volumes}
ret['comment'] = 'Volume {0} is created'.format(name)
else:
ret['comment'] = 'Volume {0} already exists'.format(name)
if start:
if __opts__['test']:
# volume already exists
ret['comment'] = ret['comment'] + ' and will be started'
ret['result'] = None
return ret
if int(__salt__['glusterfs.info']()[name]['status']) == 1:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is started'
else:
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is now started'
if not ret['changes']:
ret['changes'] = {'new': 'started', 'old': 'stopped'}
else:
ret['comment'] = ret['comment'] + ' but failed to start. Check logs for further information'
return ret
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = True
return ret
|
Ensure that the volume exists
name
name of the volume
bricks
list of brick paths
replica
replica count for volume
arbiter
use every third brick as arbiter (metadata only)
.. versionadded:: 2019.2.0
start
ensure that the volume is also started
.. code-block:: yaml
myvolume:
glusterfs.volume_present:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.volume_present:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- replica: 2
- start: True
Replicated Volume with arbiter brick:
glusterfs.volume_present:
- name: volume3
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- host3:/srv/gluster/drive4
- replica: 3
- arbiter: True
- start: True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glusterfs.py#L111-L222
|
[
"def check_name(name, safe_chars):\n '''\n Check whether the specified name contains invalid characters\n '''\n regexp = re.compile('[^{0}]'.format(safe_chars))\n if regexp.search(name):\n raise SaltCloudException(\n '{0} contains characters not supported by this cloud provider. '\n 'Valid characters are: {1}'.format(\n name, safe_chars\n )\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Manage GlusterFS pool.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, \
print_function, generators
import logging
# Import salt libs
import salt.utils.cloud as suc
import salt.utils.network
from salt.exceptions import SaltCloudException
log = logging.getLogger(__name__)
RESULT_CODES = [
'Peer {0} added successfully.',
'Probe on localhost not needed',
'Host {0} is already in the peer group',
'Host {0} is already part of another cluster',
'Volume on {0} conflicts with existing volumes',
'UUID of {0} is the same as local uuid',
'{0} responded with "unknown peer". This could happen if {0} doesn\'t have localhost defined',
'Failed to add peer. Information on {0}\'s logs',
'Cluster quorum is not met. Changing peers is not allowed.',
'Failed to update list of missed snapshots from {0}',
'Conflict comparing list of snapshots from {0}',
'Peer is already being detached from cluster.']
def __virtual__():
'''
Only load this module if the gluster command exists
'''
return 'glusterfs' if 'glusterfs.list_volumes' in __salt__ else False
def peered(name):
'''
Check if node is peered.
name
The remote host with which to peer.
.. code-block:: yaml
peer-cluster:
glusterfs.peered:
- name: two
peer-clusters:
glusterfs.peered:
- names:
- one
- two
- three
- four
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
suc.check_name(name, 'a-zA-Z0-9._-')
except SaltCloudException:
ret['comment'] = 'Invalid characters in peer name.'
return ret
# Check if the name resolves to one of this minion IP addresses
name_ips = salt.utils.network.host_to_ips(name)
if name_ips is not None:
# if it is None, it means resolution fails, let's not hide
# it from the user.
this_ips = set(salt.utils.network.ip_addrs())
this_ips.update(salt.utils.network.ip_addrs6())
if this_ips.intersection(name_ips):
ret['result'] = True
ret['comment'] = 'Peering with localhost is not needed'
return ret
peers = __salt__['glusterfs.peer_status']()
if peers and any(name in v['hostnames'] for v in peers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} already peered'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Peer {0} will be added.'.format(name)
ret['result'] = None
return ret
if not __salt__['glusterfs.peer'](name):
ret['comment'] = 'Failed to peer with {0}, please check logs for errors'.format(name)
return ret
# Double check that the action succeeded
newpeers = __salt__['glusterfs.peer_status']()
if newpeers and any(name in v['hostnames'] for v in newpeers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} successfully peered'.format(name)
ret['changes'] = {'new': newpeers, 'old': peers}
else:
ret['comment'] = 'Host {0} was successfully peered but did not appear in the list of peers'.format(name)
return ret
def started(name):
'''
Check if volume has been started
name
name of the volume
.. code-block:: yaml
mycluster:
glusterfs.started: []
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['result'] = False
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) == 1:
ret['comment'] = 'Volume {0} is already started'.format(name)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Volume {0} will be started'.format(name)
ret['result'] = None
return ret
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = 'Volume {0} is started'.format(name)
ret['change'] = {'new': 'started', 'old': 'stopped'}
else:
ret['result'] = False
ret['comment'] = 'Failed to start volume {0}'.format(name)
return ret
def add_volume_bricks(name, bricks):
'''
Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
.. code-block:: yaml
myvolume:
glusterfs.add_volume_bricks:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.add_volume_bricks:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) != 1:
ret['comment'] = 'Volume {0} is not started'.format(name)
return ret
current_bricks = [brick['path'] for brick in volinfo[name]['bricks'].values()]
if not set(bricks) - set(current_bricks):
ret['result'] = True
ret['comment'] = 'Bricks already added in volume {0}'.format(name)
return ret
bricks_added = __salt__['glusterfs.add_volume_bricks'](name, bricks)
if bricks_added:
ret['result'] = True
ret['comment'] = 'Bricks successfully added to volume {0}'.format(name)
new_bricks = [brick['path'] for brick in __salt__['glusterfs.info']()[name]['bricks'].values()]
ret['changes'] = {'new': new_bricks, 'old': current_bricks}
return ret
ret['comment'] = 'Adding bricks to volume {0} failed'.format(name)
return ret
def op_version(name, version):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
version
Version to which the cluster.op-version should be set
.. code-block:: yaml
myvolume:
glusterfs.op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
if current == version:
ret['comment'] = 'Glusterfs cluster.op-version for {0} already set to {1}'.format(name, version)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version for {0} to {1}.'.format(name, version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': version}
ret['result'] = True
return ret
def max_op_version(name):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
.. code-block:: yaml
myvolume:
glusterfs.max_op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
try:
max_version = int(__salt__['glusterfs.get_max_op_version']())
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_max_op_version']()[1]
return ret
if current == max_version:
ret['comment'] = 'The cluster.op-version is already set to the cluster.max-op-version of {0}'.format(current)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version to {0}.'.format(max_version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](max_version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': max_version}
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/glusterfs.py
|
started
|
python
|
def started(name):
'''
Check if volume has been started
name
name of the volume
.. code-block:: yaml
mycluster:
glusterfs.started: []
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['result'] = False
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) == 1:
ret['comment'] = 'Volume {0} is already started'.format(name)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Volume {0} will be started'.format(name)
ret['result'] = None
return ret
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = 'Volume {0} is started'.format(name)
ret['change'] = {'new': 'started', 'old': 'stopped'}
else:
ret['result'] = False
ret['comment'] = 'Failed to start volume {0}'.format(name)
return ret
|
Check if volume has been started
name
name of the volume
.. code-block:: yaml
mycluster:
glusterfs.started: []
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glusterfs.py#L225-L266
| null |
# -*- coding: utf-8 -*-
'''
Manage GlusterFS pool.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, \
print_function, generators
import logging
# Import salt libs
import salt.utils.cloud as suc
import salt.utils.network
from salt.exceptions import SaltCloudException
log = logging.getLogger(__name__)
RESULT_CODES = [
'Peer {0} added successfully.',
'Probe on localhost not needed',
'Host {0} is already in the peer group',
'Host {0} is already part of another cluster',
'Volume on {0} conflicts with existing volumes',
'UUID of {0} is the same as local uuid',
'{0} responded with "unknown peer". This could happen if {0} doesn\'t have localhost defined',
'Failed to add peer. Information on {0}\'s logs',
'Cluster quorum is not met. Changing peers is not allowed.',
'Failed to update list of missed snapshots from {0}',
'Conflict comparing list of snapshots from {0}',
'Peer is already being detached from cluster.']
def __virtual__():
'''
Only load this module if the gluster command exists
'''
return 'glusterfs' if 'glusterfs.list_volumes' in __salt__ else False
def peered(name):
'''
Check if node is peered.
name
The remote host with which to peer.
.. code-block:: yaml
peer-cluster:
glusterfs.peered:
- name: two
peer-clusters:
glusterfs.peered:
- names:
- one
- two
- three
- four
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
suc.check_name(name, 'a-zA-Z0-9._-')
except SaltCloudException:
ret['comment'] = 'Invalid characters in peer name.'
return ret
# Check if the name resolves to one of this minion IP addresses
name_ips = salt.utils.network.host_to_ips(name)
if name_ips is not None:
# if it is None, it means resolution fails, let's not hide
# it from the user.
this_ips = set(salt.utils.network.ip_addrs())
this_ips.update(salt.utils.network.ip_addrs6())
if this_ips.intersection(name_ips):
ret['result'] = True
ret['comment'] = 'Peering with localhost is not needed'
return ret
peers = __salt__['glusterfs.peer_status']()
if peers and any(name in v['hostnames'] for v in peers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} already peered'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Peer {0} will be added.'.format(name)
ret['result'] = None
return ret
if not __salt__['glusterfs.peer'](name):
ret['comment'] = 'Failed to peer with {0}, please check logs for errors'.format(name)
return ret
# Double check that the action succeeded
newpeers = __salt__['glusterfs.peer_status']()
if newpeers and any(name in v['hostnames'] for v in newpeers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} successfully peered'.format(name)
ret['changes'] = {'new': newpeers, 'old': peers}
else:
ret['comment'] = 'Host {0} was successfully peered but did not appear in the list of peers'.format(name)
return ret
def volume_present(name, bricks, stripe=False, replica=False, device_vg=False,
transport='tcp', start=False, force=False, arbiter=False):
'''
Ensure that the volume exists
name
name of the volume
bricks
list of brick paths
replica
replica count for volume
arbiter
use every third brick as arbiter (metadata only)
.. versionadded:: 2019.2.0
start
ensure that the volume is also started
.. code-block:: yaml
myvolume:
glusterfs.volume_present:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.volume_present:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- replica: 2
- start: True
Replicated Volume with arbiter brick:
glusterfs.volume_present:
- name: volume3
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- host3:/srv/gluster/drive4
- replica: 3
- arbiter: True
- start: True
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
if suc.check_name(name, 'a-zA-Z0-9._-'):
ret['comment'] = 'Invalid characters in volume name.'
return ret
volumes = __salt__['glusterfs.list_volumes']()
if name not in volumes:
if __opts__['test']:
comment = 'Volume {0} will be created'.format(name)
if start:
comment += ' and started'
ret['comment'] = comment
ret['result'] = None
return ret
vol_created = __salt__['glusterfs.create_volume'](
name, bricks, stripe,
replica, device_vg,
transport, start, force, arbiter)
if not vol_created:
ret['comment'] = 'Creation of volume {0} failed'.format(name)
return ret
old_volumes = volumes
volumes = __salt__['glusterfs.list_volumes']()
if name in volumes:
ret['changes'] = {'new': volumes, 'old': old_volumes}
ret['comment'] = 'Volume {0} is created'.format(name)
else:
ret['comment'] = 'Volume {0} already exists'.format(name)
if start:
if __opts__['test']:
# volume already exists
ret['comment'] = ret['comment'] + ' and will be started'
ret['result'] = None
return ret
if int(__salt__['glusterfs.info']()[name]['status']) == 1:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is started'
else:
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is now started'
if not ret['changes']:
ret['changes'] = {'new': 'started', 'old': 'stopped'}
else:
ret['comment'] = ret['comment'] + ' but failed to start. Check logs for further information'
return ret
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = True
return ret
def add_volume_bricks(name, bricks):
'''
Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
.. code-block:: yaml
myvolume:
glusterfs.add_volume_bricks:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.add_volume_bricks:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) != 1:
ret['comment'] = 'Volume {0} is not started'.format(name)
return ret
current_bricks = [brick['path'] for brick in volinfo[name]['bricks'].values()]
if not set(bricks) - set(current_bricks):
ret['result'] = True
ret['comment'] = 'Bricks already added in volume {0}'.format(name)
return ret
bricks_added = __salt__['glusterfs.add_volume_bricks'](name, bricks)
if bricks_added:
ret['result'] = True
ret['comment'] = 'Bricks successfully added to volume {0}'.format(name)
new_bricks = [brick['path'] for brick in __salt__['glusterfs.info']()[name]['bricks'].values()]
ret['changes'] = {'new': new_bricks, 'old': current_bricks}
return ret
ret['comment'] = 'Adding bricks to volume {0} failed'.format(name)
return ret
def op_version(name, version):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
version
Version to which the cluster.op-version should be set
.. code-block:: yaml
myvolume:
glusterfs.op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
if current == version:
ret['comment'] = 'Glusterfs cluster.op-version for {0} already set to {1}'.format(name, version)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version for {0} to {1}.'.format(name, version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': version}
ret['result'] = True
return ret
def max_op_version(name):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
.. code-block:: yaml
myvolume:
glusterfs.max_op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
try:
max_version = int(__salt__['glusterfs.get_max_op_version']())
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_max_op_version']()[1]
return ret
if current == max_version:
ret['comment'] = 'The cluster.op-version is already set to the cluster.max-op-version of {0}'.format(current)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version to {0}.'.format(max_version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](max_version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': max_version}
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/glusterfs.py
|
add_volume_bricks
|
python
|
def add_volume_bricks(name, bricks):
'''
Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
.. code-block:: yaml
myvolume:
glusterfs.add_volume_bricks:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.add_volume_bricks:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) != 1:
ret['comment'] = 'Volume {0} is not started'.format(name)
return ret
current_bricks = [brick['path'] for brick in volinfo[name]['bricks'].values()]
if not set(bricks) - set(current_bricks):
ret['result'] = True
ret['comment'] = 'Bricks already added in volume {0}'.format(name)
return ret
bricks_added = __salt__['glusterfs.add_volume_bricks'](name, bricks)
if bricks_added:
ret['result'] = True
ret['comment'] = 'Bricks successfully added to volume {0}'.format(name)
new_bricks = [brick['path'] for brick in __salt__['glusterfs.info']()[name]['bricks'].values()]
ret['changes'] = {'new': new_bricks, 'old': current_bricks}
return ret
ret['comment'] = 'Adding bricks to volume {0} failed'.format(name)
return ret
|
Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
.. code-block:: yaml
myvolume:
glusterfs.add_volume_bricks:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.add_volume_bricks:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glusterfs.py#L269-L323
| null |
# -*- coding: utf-8 -*-
'''
Manage GlusterFS pool.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, \
print_function, generators
import logging
# Import salt libs
import salt.utils.cloud as suc
import salt.utils.network
from salt.exceptions import SaltCloudException
log = logging.getLogger(__name__)
RESULT_CODES = [
'Peer {0} added successfully.',
'Probe on localhost not needed',
'Host {0} is already in the peer group',
'Host {0} is already part of another cluster',
'Volume on {0} conflicts with existing volumes',
'UUID of {0} is the same as local uuid',
'{0} responded with "unknown peer". This could happen if {0} doesn\'t have localhost defined',
'Failed to add peer. Information on {0}\'s logs',
'Cluster quorum is not met. Changing peers is not allowed.',
'Failed to update list of missed snapshots from {0}',
'Conflict comparing list of snapshots from {0}',
'Peer is already being detached from cluster.']
def __virtual__():
'''
Only load this module if the gluster command exists
'''
return 'glusterfs' if 'glusterfs.list_volumes' in __salt__ else False
def peered(name):
'''
Check if node is peered.
name
The remote host with which to peer.
.. code-block:: yaml
peer-cluster:
glusterfs.peered:
- name: two
peer-clusters:
glusterfs.peered:
- names:
- one
- two
- three
- four
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
suc.check_name(name, 'a-zA-Z0-9._-')
except SaltCloudException:
ret['comment'] = 'Invalid characters in peer name.'
return ret
# Check if the name resolves to one of this minion IP addresses
name_ips = salt.utils.network.host_to_ips(name)
if name_ips is not None:
# if it is None, it means resolution fails, let's not hide
# it from the user.
this_ips = set(salt.utils.network.ip_addrs())
this_ips.update(salt.utils.network.ip_addrs6())
if this_ips.intersection(name_ips):
ret['result'] = True
ret['comment'] = 'Peering with localhost is not needed'
return ret
peers = __salt__['glusterfs.peer_status']()
if peers and any(name in v['hostnames'] for v in peers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} already peered'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Peer {0} will be added.'.format(name)
ret['result'] = None
return ret
if not __salt__['glusterfs.peer'](name):
ret['comment'] = 'Failed to peer with {0}, please check logs for errors'.format(name)
return ret
# Double check that the action succeeded
newpeers = __salt__['glusterfs.peer_status']()
if newpeers and any(name in v['hostnames'] for v in newpeers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} successfully peered'.format(name)
ret['changes'] = {'new': newpeers, 'old': peers}
else:
ret['comment'] = 'Host {0} was successfully peered but did not appear in the list of peers'.format(name)
return ret
def volume_present(name, bricks, stripe=False, replica=False, device_vg=False,
transport='tcp', start=False, force=False, arbiter=False):
'''
Ensure that the volume exists
name
name of the volume
bricks
list of brick paths
replica
replica count for volume
arbiter
use every third brick as arbiter (metadata only)
.. versionadded:: 2019.2.0
start
ensure that the volume is also started
.. code-block:: yaml
myvolume:
glusterfs.volume_present:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.volume_present:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- replica: 2
- start: True
Replicated Volume with arbiter brick:
glusterfs.volume_present:
- name: volume3
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- host3:/srv/gluster/drive4
- replica: 3
- arbiter: True
- start: True
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
if suc.check_name(name, 'a-zA-Z0-9._-'):
ret['comment'] = 'Invalid characters in volume name.'
return ret
volumes = __salt__['glusterfs.list_volumes']()
if name not in volumes:
if __opts__['test']:
comment = 'Volume {0} will be created'.format(name)
if start:
comment += ' and started'
ret['comment'] = comment
ret['result'] = None
return ret
vol_created = __salt__['glusterfs.create_volume'](
name, bricks, stripe,
replica, device_vg,
transport, start, force, arbiter)
if not vol_created:
ret['comment'] = 'Creation of volume {0} failed'.format(name)
return ret
old_volumes = volumes
volumes = __salt__['glusterfs.list_volumes']()
if name in volumes:
ret['changes'] = {'new': volumes, 'old': old_volumes}
ret['comment'] = 'Volume {0} is created'.format(name)
else:
ret['comment'] = 'Volume {0} already exists'.format(name)
if start:
if __opts__['test']:
# volume already exists
ret['comment'] = ret['comment'] + ' and will be started'
ret['result'] = None
return ret
if int(__salt__['glusterfs.info']()[name]['status']) == 1:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is started'
else:
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is now started'
if not ret['changes']:
ret['changes'] = {'new': 'started', 'old': 'stopped'}
else:
ret['comment'] = ret['comment'] + ' but failed to start. Check logs for further information'
return ret
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = True
return ret
def started(name):
'''
Check if volume has been started
name
name of the volume
.. code-block:: yaml
mycluster:
glusterfs.started: []
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['result'] = False
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) == 1:
ret['comment'] = 'Volume {0} is already started'.format(name)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Volume {0} will be started'.format(name)
ret['result'] = None
return ret
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = 'Volume {0} is started'.format(name)
ret['change'] = {'new': 'started', 'old': 'stopped'}
else:
ret['result'] = False
ret['comment'] = 'Failed to start volume {0}'.format(name)
return ret
def op_version(name, version):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
version
Version to which the cluster.op-version should be set
.. code-block:: yaml
myvolume:
glusterfs.op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
if current == version:
ret['comment'] = 'Glusterfs cluster.op-version for {0} already set to {1}'.format(name, version)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version for {0} to {1}.'.format(name, version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': version}
ret['result'] = True
return ret
def max_op_version(name):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
.. code-block:: yaml
myvolume:
glusterfs.max_op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
try:
max_version = int(__salt__['glusterfs.get_max_op_version']())
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_max_op_version']()[1]
return ret
if current == max_version:
ret['comment'] = 'The cluster.op-version is already set to the cluster.max-op-version of {0}'.format(current)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version to {0}.'.format(max_version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](max_version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': max_version}
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/glusterfs.py
|
op_version
|
python
|
def op_version(name, version):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
version
Version to which the cluster.op-version should be set
.. code-block:: yaml
myvolume:
glusterfs.op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
if current == version:
ret['comment'] = 'Glusterfs cluster.op-version for {0} already set to {1}'.format(name, version)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version for {0} to {1}.'.format(name, version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': version}
ret['result'] = True
return ret
|
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
version
Version to which the cluster.op-version should be set
.. code-block:: yaml
myvolume:
glusterfs.op_version:
- name: volume1
- version: 30707
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glusterfs.py#L326-L375
| null |
# -*- coding: utf-8 -*-
'''
Manage GlusterFS pool.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, \
print_function, generators
import logging
# Import salt libs
import salt.utils.cloud as suc
import salt.utils.network
from salt.exceptions import SaltCloudException
log = logging.getLogger(__name__)
RESULT_CODES = [
'Peer {0} added successfully.',
'Probe on localhost not needed',
'Host {0} is already in the peer group',
'Host {0} is already part of another cluster',
'Volume on {0} conflicts with existing volumes',
'UUID of {0} is the same as local uuid',
'{0} responded with "unknown peer". This could happen if {0} doesn\'t have localhost defined',
'Failed to add peer. Information on {0}\'s logs',
'Cluster quorum is not met. Changing peers is not allowed.',
'Failed to update list of missed snapshots from {0}',
'Conflict comparing list of snapshots from {0}',
'Peer is already being detached from cluster.']
def __virtual__():
'''
Only load this module if the gluster command exists
'''
return 'glusterfs' if 'glusterfs.list_volumes' in __salt__ else False
def peered(name):
'''
Check if node is peered.
name
The remote host with which to peer.
.. code-block:: yaml
peer-cluster:
glusterfs.peered:
- name: two
peer-clusters:
glusterfs.peered:
- names:
- one
- two
- three
- four
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
suc.check_name(name, 'a-zA-Z0-9._-')
except SaltCloudException:
ret['comment'] = 'Invalid characters in peer name.'
return ret
# Check if the name resolves to one of this minion IP addresses
name_ips = salt.utils.network.host_to_ips(name)
if name_ips is not None:
# if it is None, it means resolution fails, let's not hide
# it from the user.
this_ips = set(salt.utils.network.ip_addrs())
this_ips.update(salt.utils.network.ip_addrs6())
if this_ips.intersection(name_ips):
ret['result'] = True
ret['comment'] = 'Peering with localhost is not needed'
return ret
peers = __salt__['glusterfs.peer_status']()
if peers and any(name in v['hostnames'] for v in peers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} already peered'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Peer {0} will be added.'.format(name)
ret['result'] = None
return ret
if not __salt__['glusterfs.peer'](name):
ret['comment'] = 'Failed to peer with {0}, please check logs for errors'.format(name)
return ret
# Double check that the action succeeded
newpeers = __salt__['glusterfs.peer_status']()
if newpeers and any(name in v['hostnames'] for v in newpeers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} successfully peered'.format(name)
ret['changes'] = {'new': newpeers, 'old': peers}
else:
ret['comment'] = 'Host {0} was successfully peered but did not appear in the list of peers'.format(name)
return ret
def volume_present(name, bricks, stripe=False, replica=False, device_vg=False,
transport='tcp', start=False, force=False, arbiter=False):
'''
Ensure that the volume exists
name
name of the volume
bricks
list of brick paths
replica
replica count for volume
arbiter
use every third brick as arbiter (metadata only)
.. versionadded:: 2019.2.0
start
ensure that the volume is also started
.. code-block:: yaml
myvolume:
glusterfs.volume_present:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.volume_present:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- replica: 2
- start: True
Replicated Volume with arbiter brick:
glusterfs.volume_present:
- name: volume3
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- host3:/srv/gluster/drive4
- replica: 3
- arbiter: True
- start: True
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
if suc.check_name(name, 'a-zA-Z0-9._-'):
ret['comment'] = 'Invalid characters in volume name.'
return ret
volumes = __salt__['glusterfs.list_volumes']()
if name not in volumes:
if __opts__['test']:
comment = 'Volume {0} will be created'.format(name)
if start:
comment += ' and started'
ret['comment'] = comment
ret['result'] = None
return ret
vol_created = __salt__['glusterfs.create_volume'](
name, bricks, stripe,
replica, device_vg,
transport, start, force, arbiter)
if not vol_created:
ret['comment'] = 'Creation of volume {0} failed'.format(name)
return ret
old_volumes = volumes
volumes = __salt__['glusterfs.list_volumes']()
if name in volumes:
ret['changes'] = {'new': volumes, 'old': old_volumes}
ret['comment'] = 'Volume {0} is created'.format(name)
else:
ret['comment'] = 'Volume {0} already exists'.format(name)
if start:
if __opts__['test']:
# volume already exists
ret['comment'] = ret['comment'] + ' and will be started'
ret['result'] = None
return ret
if int(__salt__['glusterfs.info']()[name]['status']) == 1:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is started'
else:
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is now started'
if not ret['changes']:
ret['changes'] = {'new': 'started', 'old': 'stopped'}
else:
ret['comment'] = ret['comment'] + ' but failed to start. Check logs for further information'
return ret
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = True
return ret
def started(name):
'''
Check if volume has been started
name
name of the volume
.. code-block:: yaml
mycluster:
glusterfs.started: []
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['result'] = False
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) == 1:
ret['comment'] = 'Volume {0} is already started'.format(name)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Volume {0} will be started'.format(name)
ret['result'] = None
return ret
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = 'Volume {0} is started'.format(name)
ret['change'] = {'new': 'started', 'old': 'stopped'}
else:
ret['result'] = False
ret['comment'] = 'Failed to start volume {0}'.format(name)
return ret
def add_volume_bricks(name, bricks):
'''
Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
.. code-block:: yaml
myvolume:
glusterfs.add_volume_bricks:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.add_volume_bricks:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) != 1:
ret['comment'] = 'Volume {0} is not started'.format(name)
return ret
current_bricks = [brick['path'] for brick in volinfo[name]['bricks'].values()]
if not set(bricks) - set(current_bricks):
ret['result'] = True
ret['comment'] = 'Bricks already added in volume {0}'.format(name)
return ret
bricks_added = __salt__['glusterfs.add_volume_bricks'](name, bricks)
if bricks_added:
ret['result'] = True
ret['comment'] = 'Bricks successfully added to volume {0}'.format(name)
new_bricks = [brick['path'] for brick in __salt__['glusterfs.info']()[name]['bricks'].values()]
ret['changes'] = {'new': new_bricks, 'old': current_bricks}
return ret
ret['comment'] = 'Adding bricks to volume {0} failed'.format(name)
return ret
def max_op_version(name):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
.. code-block:: yaml
myvolume:
glusterfs.max_op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
try:
max_version = int(__salt__['glusterfs.get_max_op_version']())
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_max_op_version']()[1]
return ret
if current == max_version:
ret['comment'] = 'The cluster.op-version is already set to the cluster.max-op-version of {0}'.format(current)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version to {0}.'.format(max_version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](max_version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': max_version}
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/glusterfs.py
|
max_op_version
|
python
|
def max_op_version(name):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
.. code-block:: yaml
myvolume:
glusterfs.max_op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
try:
max_version = int(__salt__['glusterfs.get_max_op_version']())
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_max_op_version']()[1]
return ret
if current == max_version:
ret['comment'] = 'The cluster.op-version is already set to the cluster.max-op-version of {0}'.format(current)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version to {0}.'.format(max_version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](max_version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': max_version}
ret['result'] = True
return ret
|
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
.. code-block:: yaml
myvolume:
glusterfs.max_op_version:
- name: volume1
- version: 30707
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glusterfs.py#L378-L431
| null |
# -*- coding: utf-8 -*-
'''
Manage GlusterFS pool.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, \
print_function, generators
import logging
# Import salt libs
import salt.utils.cloud as suc
import salt.utils.network
from salt.exceptions import SaltCloudException
log = logging.getLogger(__name__)
RESULT_CODES = [
'Peer {0} added successfully.',
'Probe on localhost not needed',
'Host {0} is already in the peer group',
'Host {0} is already part of another cluster',
'Volume on {0} conflicts with existing volumes',
'UUID of {0} is the same as local uuid',
'{0} responded with "unknown peer". This could happen if {0} doesn\'t have localhost defined',
'Failed to add peer. Information on {0}\'s logs',
'Cluster quorum is not met. Changing peers is not allowed.',
'Failed to update list of missed snapshots from {0}',
'Conflict comparing list of snapshots from {0}',
'Peer is already being detached from cluster.']
def __virtual__():
'''
Only load this module if the gluster command exists
'''
return 'glusterfs' if 'glusterfs.list_volumes' in __salt__ else False
def peered(name):
'''
Check if node is peered.
name
The remote host with which to peer.
.. code-block:: yaml
peer-cluster:
glusterfs.peered:
- name: two
peer-clusters:
glusterfs.peered:
- names:
- one
- two
- three
- four
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
suc.check_name(name, 'a-zA-Z0-9._-')
except SaltCloudException:
ret['comment'] = 'Invalid characters in peer name.'
return ret
# Check if the name resolves to one of this minion IP addresses
name_ips = salt.utils.network.host_to_ips(name)
if name_ips is not None:
# if it is None, it means resolution fails, let's not hide
# it from the user.
this_ips = set(salt.utils.network.ip_addrs())
this_ips.update(salt.utils.network.ip_addrs6())
if this_ips.intersection(name_ips):
ret['result'] = True
ret['comment'] = 'Peering with localhost is not needed'
return ret
peers = __salt__['glusterfs.peer_status']()
if peers and any(name in v['hostnames'] for v in peers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} already peered'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Peer {0} will be added.'.format(name)
ret['result'] = None
return ret
if not __salt__['glusterfs.peer'](name):
ret['comment'] = 'Failed to peer with {0}, please check logs for errors'.format(name)
return ret
# Double check that the action succeeded
newpeers = __salt__['glusterfs.peer_status']()
if newpeers and any(name in v['hostnames'] for v in newpeers.values()):
ret['result'] = True
ret['comment'] = 'Host {0} successfully peered'.format(name)
ret['changes'] = {'new': newpeers, 'old': peers}
else:
ret['comment'] = 'Host {0} was successfully peered but did not appear in the list of peers'.format(name)
return ret
def volume_present(name, bricks, stripe=False, replica=False, device_vg=False,
transport='tcp', start=False, force=False, arbiter=False):
'''
Ensure that the volume exists
name
name of the volume
bricks
list of brick paths
replica
replica count for volume
arbiter
use every third brick as arbiter (metadata only)
.. versionadded:: 2019.2.0
start
ensure that the volume is also started
.. code-block:: yaml
myvolume:
glusterfs.volume_present:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.volume_present:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- replica: 2
- start: True
Replicated Volume with arbiter brick:
glusterfs.volume_present:
- name: volume3
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
- host3:/srv/gluster/drive4
- replica: 3
- arbiter: True
- start: True
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
if suc.check_name(name, 'a-zA-Z0-9._-'):
ret['comment'] = 'Invalid characters in volume name.'
return ret
volumes = __salt__['glusterfs.list_volumes']()
if name not in volumes:
if __opts__['test']:
comment = 'Volume {0} will be created'.format(name)
if start:
comment += ' and started'
ret['comment'] = comment
ret['result'] = None
return ret
vol_created = __salt__['glusterfs.create_volume'](
name, bricks, stripe,
replica, device_vg,
transport, start, force, arbiter)
if not vol_created:
ret['comment'] = 'Creation of volume {0} failed'.format(name)
return ret
old_volumes = volumes
volumes = __salt__['glusterfs.list_volumes']()
if name in volumes:
ret['changes'] = {'new': volumes, 'old': old_volumes}
ret['comment'] = 'Volume {0} is created'.format(name)
else:
ret['comment'] = 'Volume {0} already exists'.format(name)
if start:
if __opts__['test']:
# volume already exists
ret['comment'] = ret['comment'] + ' and will be started'
ret['result'] = None
return ret
if int(__salt__['glusterfs.info']()[name]['status']) == 1:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is started'
else:
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = ret['comment'] + ' and is now started'
if not ret['changes']:
ret['changes'] = {'new': 'started', 'old': 'stopped'}
else:
ret['comment'] = ret['comment'] + ' but failed to start. Check logs for further information'
return ret
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = True
return ret
def started(name):
'''
Check if volume has been started
name
name of the volume
.. code-block:: yaml
mycluster:
glusterfs.started: []
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['result'] = False
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) == 1:
ret['comment'] = 'Volume {0} is already started'.format(name)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Volume {0} will be started'.format(name)
ret['result'] = None
return ret
vol_started = __salt__['glusterfs.start_volume'](name)
if vol_started:
ret['result'] = True
ret['comment'] = 'Volume {0} is started'.format(name)
ret['change'] = {'new': 'started', 'old': 'stopped'}
else:
ret['result'] = False
ret['comment'] = 'Failed to start volume {0}'.format(name)
return ret
def add_volume_bricks(name, bricks):
'''
Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
.. code-block:: yaml
myvolume:
glusterfs.add_volume_bricks:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
Replicated Volume:
glusterfs.add_volume_bricks:
- name: volume2
- bricks:
- host1:/srv/gluster/drive2
- host2:/srv/gluster/drive3
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glusterfs.info']()
if name not in volinfo:
ret['comment'] = 'Volume {0} does not exist'.format(name)
return ret
if int(volinfo[name]['status']) != 1:
ret['comment'] = 'Volume {0} is not started'.format(name)
return ret
current_bricks = [brick['path'] for brick in volinfo[name]['bricks'].values()]
if not set(bricks) - set(current_bricks):
ret['result'] = True
ret['comment'] = 'Bricks already added in volume {0}'.format(name)
return ret
bricks_added = __salt__['glusterfs.add_volume_bricks'](name, bricks)
if bricks_added:
ret['result'] = True
ret['comment'] = 'Bricks successfully added to volume {0}'.format(name)
new_bricks = [brick['path'] for brick in __salt__['glusterfs.info']()[name]['bricks'].values()]
ret['changes'] = {'new': new_bricks, 'old': current_bricks}
return ret
ret['comment'] = 'Adding bricks to volume {0} failed'.format(name)
return ret
def op_version(name, version):
'''
.. versionadded:: 2019.2.0
Add brick(s) to an existing volume
name
Volume name
version
Version to which the cluster.op-version should be set
.. code-block:: yaml
myvolume:
glusterfs.op_version:
- name: volume1
- version: 30707
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
try:
current = int(__salt__['glusterfs.get_op_version'](name))
except TypeError:
ret['result'] = False
ret['comment'] = __salt__['glusterfs.get_op_version'](name)[1]
return ret
if current == version:
ret['comment'] = 'Glusterfs cluster.op-version for {0} already set to {1}'.format(name, version)
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'An attempt would be made to set the cluster.op-version for {0} to {1}.'.format(name, version)
ret['result'] = None
return ret
result = __salt__['glusterfs.set_op_version'](version)
if result[0] is False:
ret['comment'] = result[1]
return ret
ret['comment'] = result
ret['changes'] = {'old': current, 'new': version}
ret['result'] = True
return ret
|
saltstack/salt
|
salt/returners/nagios_nrdp_return.py
|
_prepare_xml
|
python
|
def _prepare_xml(options=None, state=None):
'''
Get the requests options from salt.
'''
if state:
_state = '0'
else:
_state = '2'
xml = "<?xml version='1.0'?>\n<checkresults>\n"
# No service defined then we set the status of the hostname
if 'service' in options and options['service'] != '':
xml += "<checkresult type='service' checktype='" + six.text_type(options['checktype'])+"'>"
xml += "<hostname>"+cgi.escape(options['hostname'], True)+"</hostname>"
xml += "<servicename>"+cgi.escape(options['service'], True)+"</servicename>"
else:
xml += "<checkresult type='host' checktype='" + six.text_type(options['checktype'])+"'>"
xml += "<hostname>"+cgi.escape(options['hostname'], True)+"</hostname>"
xml += "<state>"+_state+"</state>"
if 'output' in options:
xml += "<output>"+cgi.escape(options['output'], True)+"</output>"
xml += "</checkresult>"
xml += "\n</checkresults>"
return xml
|
Get the requests options from salt.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/nagios_nrdp_return.py#L108-L138
| null |
# -*- coding: utf-8 -*-
'''
Return salt data to Nagios
The following fields can be set in the minion conf file::
nagios.url (required)
nagios.token (required)
nagios.service (optional)
nagios.check_type (optional)
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location::
nagios.url
nagios.token
nagios.service
Nagios settings may also be configured as::
nagios:
url: http://localhost/nrdp
token: r4nd0mt0k3n
service: service-check
alternative.nagios:
url: http://localhost/nrdp
token: r4nd0mt0k3n
service: another-service-check
To use the Nagios returner, append '--return nagios' to the salt command. ex:
.. code-block:: bash
salt '*' test.ping --return nagios
To use the alternative configuration, append '--return_config alternative' to the salt command. ex:
salt '*' test.ping --return nagios --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return nagios --return_kwargs '{"service": "service-name"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import cgi
import logging
import salt.returners
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
import salt.ext.six.moves.http_client
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
__virtualname__ = 'nagios_nrdp'
def __virtual__():
'''
Return virtualname
'''
return 'nagios.list_plugins' in __salt__
def _get_options(ret=None):
'''
Get the requests options from salt.
'''
attrs = {'url': 'url',
'token': 'token',
'service': 'service',
'checktype': 'checktype',
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
log.debug('attrs %s', attrs)
if 'checktype' not in _options or _options['checktype'] == '':
# default to passive check type
_options['checktype'] = '1'
if _options['checktype'] == 'active':
_options['checktype'] = '0'
if _options['checktype'] == 'passive':
_options['checktype'] = '1'
# checktype should be a string
_options['checktype'] = six.text_type(_options['checktype'])
return _options
def _getText(nodelist):
'''
Simple function to return value from XML
'''
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
def _post_data(options=None, xml=None):
'''
Post data to Nagios NRDP
'''
params = {'token': options['token'].strip(), 'cmd': 'submitcheck', 'XMLDATA': xml}
res = salt.utils.http.query(
url=options['url'],
method='POST',
params=params,
data='',
decode=True,
status=True,
header_dict={},
opts=__opts__,
)
if res.get('status', None) == salt.ext.six.moves.http_client.OK:
if res.get('dict', None) and isinstance(res['dict'], list):
_content = res['dict'][0]
if _content.get('status', None):
return True
else:
return False
else:
log.error('No content returned from Nagios NRDP.')
return False
else:
log.error(
'Error returned from Nagios NRDP. Status code: %s.',
res.status_code
)
return False
def returner(ret):
'''
Send a message to Nagios with the data
'''
_options = _get_options(ret)
log.debug('_options %s', _options)
_options['hostname'] = ret.get('id')
if 'url' not in _options or _options['url'] == '':
log.error('nagios_nrdp.url not defined in salt config')
return
if 'token' not in _options or _options['token'] == '':
log.error('nagios_nrdp.token not defined in salt config')
return
xml = _prepare_xml(options=_options, state=ret['return'])
res = _post_data(options=_options, xml=xml)
return res
|
saltstack/salt
|
salt/returners/nagios_nrdp_return.py
|
_getText
|
python
|
def _getText(nodelist):
'''
Simple function to return value from XML
'''
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
|
Simple function to return value from XML
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/nagios_nrdp_return.py#L141-L149
| null |
# -*- coding: utf-8 -*-
'''
Return salt data to Nagios
The following fields can be set in the minion conf file::
nagios.url (required)
nagios.token (required)
nagios.service (optional)
nagios.check_type (optional)
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location::
nagios.url
nagios.token
nagios.service
Nagios settings may also be configured as::
nagios:
url: http://localhost/nrdp
token: r4nd0mt0k3n
service: service-check
alternative.nagios:
url: http://localhost/nrdp
token: r4nd0mt0k3n
service: another-service-check
To use the Nagios returner, append '--return nagios' to the salt command. ex:
.. code-block:: bash
salt '*' test.ping --return nagios
To use the alternative configuration, append '--return_config alternative' to the salt command. ex:
salt '*' test.ping --return nagios --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return nagios --return_kwargs '{"service": "service-name"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import cgi
import logging
import salt.returners
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
import salt.ext.six.moves.http_client
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
__virtualname__ = 'nagios_nrdp'
def __virtual__():
'''
Return virtualname
'''
return 'nagios.list_plugins' in __salt__
def _get_options(ret=None):
'''
Get the requests options from salt.
'''
attrs = {'url': 'url',
'token': 'token',
'service': 'service',
'checktype': 'checktype',
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
log.debug('attrs %s', attrs)
if 'checktype' not in _options or _options['checktype'] == '':
# default to passive check type
_options['checktype'] = '1'
if _options['checktype'] == 'active':
_options['checktype'] = '0'
if _options['checktype'] == 'passive':
_options['checktype'] = '1'
# checktype should be a string
_options['checktype'] = six.text_type(_options['checktype'])
return _options
def _prepare_xml(options=None, state=None):
'''
Get the requests options from salt.
'''
if state:
_state = '0'
else:
_state = '2'
xml = "<?xml version='1.0'?>\n<checkresults>\n"
# No service defined then we set the status of the hostname
if 'service' in options and options['service'] != '':
xml += "<checkresult type='service' checktype='" + six.text_type(options['checktype'])+"'>"
xml += "<hostname>"+cgi.escape(options['hostname'], True)+"</hostname>"
xml += "<servicename>"+cgi.escape(options['service'], True)+"</servicename>"
else:
xml += "<checkresult type='host' checktype='" + six.text_type(options['checktype'])+"'>"
xml += "<hostname>"+cgi.escape(options['hostname'], True)+"</hostname>"
xml += "<state>"+_state+"</state>"
if 'output' in options:
xml += "<output>"+cgi.escape(options['output'], True)+"</output>"
xml += "</checkresult>"
xml += "\n</checkresults>"
return xml
def _post_data(options=None, xml=None):
'''
Post data to Nagios NRDP
'''
params = {'token': options['token'].strip(), 'cmd': 'submitcheck', 'XMLDATA': xml}
res = salt.utils.http.query(
url=options['url'],
method='POST',
params=params,
data='',
decode=True,
status=True,
header_dict={},
opts=__opts__,
)
if res.get('status', None) == salt.ext.six.moves.http_client.OK:
if res.get('dict', None) and isinstance(res['dict'], list):
_content = res['dict'][0]
if _content.get('status', None):
return True
else:
return False
else:
log.error('No content returned from Nagios NRDP.')
return False
else:
log.error(
'Error returned from Nagios NRDP. Status code: %s.',
res.status_code
)
return False
def returner(ret):
'''
Send a message to Nagios with the data
'''
_options = _get_options(ret)
log.debug('_options %s', _options)
_options['hostname'] = ret.get('id')
if 'url' not in _options or _options['url'] == '':
log.error('nagios_nrdp.url not defined in salt config')
return
if 'token' not in _options or _options['token'] == '':
log.error('nagios_nrdp.token not defined in salt config')
return
xml = _prepare_xml(options=_options, state=ret['return'])
res = _post_data(options=_options, xml=xml)
return res
|
saltstack/salt
|
salt/returners/nagios_nrdp_return.py
|
_post_data
|
python
|
def _post_data(options=None, xml=None):
'''
Post data to Nagios NRDP
'''
params = {'token': options['token'].strip(), 'cmd': 'submitcheck', 'XMLDATA': xml}
res = salt.utils.http.query(
url=options['url'],
method='POST',
params=params,
data='',
decode=True,
status=True,
header_dict={},
opts=__opts__,
)
if res.get('status', None) == salt.ext.six.moves.http_client.OK:
if res.get('dict', None) and isinstance(res['dict'], list):
_content = res['dict'][0]
if _content.get('status', None):
return True
else:
return False
else:
log.error('No content returned from Nagios NRDP.')
return False
else:
log.error(
'Error returned from Nagios NRDP. Status code: %s.',
res.status_code
)
return False
|
Post data to Nagios NRDP
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/nagios_nrdp_return.py#L152-L184
| null |
# -*- coding: utf-8 -*-
'''
Return salt data to Nagios
The following fields can be set in the minion conf file::
nagios.url (required)
nagios.token (required)
nagios.service (optional)
nagios.check_type (optional)
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location::
nagios.url
nagios.token
nagios.service
Nagios settings may also be configured as::
nagios:
url: http://localhost/nrdp
token: r4nd0mt0k3n
service: service-check
alternative.nagios:
url: http://localhost/nrdp
token: r4nd0mt0k3n
service: another-service-check
To use the Nagios returner, append '--return nagios' to the salt command. ex:
.. code-block:: bash
salt '*' test.ping --return nagios
To use the alternative configuration, append '--return_config alternative' to the salt command. ex:
salt '*' test.ping --return nagios --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return nagios --return_kwargs '{"service": "service-name"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import cgi
import logging
import salt.returners
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
import salt.ext.six.moves.http_client
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
__virtualname__ = 'nagios_nrdp'
def __virtual__():
'''
Return virtualname
'''
return 'nagios.list_plugins' in __salt__
def _get_options(ret=None):
'''
Get the requests options from salt.
'''
attrs = {'url': 'url',
'token': 'token',
'service': 'service',
'checktype': 'checktype',
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
log.debug('attrs %s', attrs)
if 'checktype' not in _options or _options['checktype'] == '':
# default to passive check type
_options['checktype'] = '1'
if _options['checktype'] == 'active':
_options['checktype'] = '0'
if _options['checktype'] == 'passive':
_options['checktype'] = '1'
# checktype should be a string
_options['checktype'] = six.text_type(_options['checktype'])
return _options
def _prepare_xml(options=None, state=None):
'''
Get the requests options from salt.
'''
if state:
_state = '0'
else:
_state = '2'
xml = "<?xml version='1.0'?>\n<checkresults>\n"
# No service defined then we set the status of the hostname
if 'service' in options and options['service'] != '':
xml += "<checkresult type='service' checktype='" + six.text_type(options['checktype'])+"'>"
xml += "<hostname>"+cgi.escape(options['hostname'], True)+"</hostname>"
xml += "<servicename>"+cgi.escape(options['service'], True)+"</servicename>"
else:
xml += "<checkresult type='host' checktype='" + six.text_type(options['checktype'])+"'>"
xml += "<hostname>"+cgi.escape(options['hostname'], True)+"</hostname>"
xml += "<state>"+_state+"</state>"
if 'output' in options:
xml += "<output>"+cgi.escape(options['output'], True)+"</output>"
xml += "</checkresult>"
xml += "\n</checkresults>"
return xml
def _getText(nodelist):
'''
Simple function to return value from XML
'''
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
def returner(ret):
'''
Send a message to Nagios with the data
'''
_options = _get_options(ret)
log.debug('_options %s', _options)
_options['hostname'] = ret.get('id')
if 'url' not in _options or _options['url'] == '':
log.error('nagios_nrdp.url not defined in salt config')
return
if 'token' not in _options or _options['token'] == '':
log.error('nagios_nrdp.token not defined in salt config')
return
xml = _prepare_xml(options=_options, state=ret['return'])
res = _post_data(options=_options, xml=xml)
return res
|
saltstack/salt
|
salt/returners/nagios_nrdp_return.py
|
returner
|
python
|
def returner(ret):
'''
Send a message to Nagios with the data
'''
_options = _get_options(ret)
log.debug('_options %s', _options)
_options['hostname'] = ret.get('id')
if 'url' not in _options or _options['url'] == '':
log.error('nagios_nrdp.url not defined in salt config')
return
if 'token' not in _options or _options['token'] == '':
log.error('nagios_nrdp.token not defined in salt config')
return
xml = _prepare_xml(options=_options, state=ret['return'])
res = _post_data(options=_options, xml=xml)
return res
|
Send a message to Nagios with the data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/nagios_nrdp_return.py#L187-L207
|
[
"def _get_options(ret=None):\n '''\n Get the requests options from salt.\n '''\n attrs = {'url': 'url',\n 'token': 'token',\n 'service': 'service',\n 'checktype': 'checktype',\n }\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n\n log.debug('attrs %s', attrs)\n if 'checktype' not in _options or _options['checktype'] == '':\n # default to passive check type\n _options['checktype'] = '1'\n\n if _options['checktype'] == 'active':\n _options['checktype'] = '0'\n\n if _options['checktype'] == 'passive':\n _options['checktype'] = '1'\n\n # checktype should be a string\n _options['checktype'] = six.text_type(_options['checktype'])\n\n return _options\n",
"def _prepare_xml(options=None, state=None):\n '''\n Get the requests options from salt.\n '''\n\n if state:\n _state = '0'\n else:\n _state = '2'\n\n xml = \"<?xml version='1.0'?>\\n<checkresults>\\n\"\n\n # No service defined then we set the status of the hostname\n if 'service' in options and options['service'] != '':\n xml += \"<checkresult type='service' checktype='\" + six.text_type(options['checktype'])+\"'>\"\n xml += \"<hostname>\"+cgi.escape(options['hostname'], True)+\"</hostname>\"\n xml += \"<servicename>\"+cgi.escape(options['service'], True)+\"</servicename>\"\n else:\n xml += \"<checkresult type='host' checktype='\" + six.text_type(options['checktype'])+\"'>\"\n xml += \"<hostname>\"+cgi.escape(options['hostname'], True)+\"</hostname>\"\n\n xml += \"<state>\"+_state+\"</state>\"\n\n if 'output' in options:\n xml += \"<output>\"+cgi.escape(options['output'], True)+\"</output>\"\n\n xml += \"</checkresult>\"\n\n xml += \"\\n</checkresults>\"\n\n return xml\n",
"def _post_data(options=None, xml=None):\n '''\n Post data to Nagios NRDP\n '''\n params = {'token': options['token'].strip(), 'cmd': 'submitcheck', 'XMLDATA': xml}\n\n res = salt.utils.http.query(\n url=options['url'],\n method='POST',\n params=params,\n data='',\n decode=True,\n status=True,\n header_dict={},\n opts=__opts__,\n )\n\n if res.get('status', None) == salt.ext.six.moves.http_client.OK:\n if res.get('dict', None) and isinstance(res['dict'], list):\n _content = res['dict'][0]\n if _content.get('status', None):\n return True\n else:\n return False\n else:\n log.error('No content returned from Nagios NRDP.')\n return False\n else:\n log.error(\n 'Error returned from Nagios NRDP. Status code: %s.',\n res.status_code\n )\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Return salt data to Nagios
The following fields can be set in the minion conf file::
nagios.url (required)
nagios.token (required)
nagios.service (optional)
nagios.check_type (optional)
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location::
nagios.url
nagios.token
nagios.service
Nagios settings may also be configured as::
nagios:
url: http://localhost/nrdp
token: r4nd0mt0k3n
service: service-check
alternative.nagios:
url: http://localhost/nrdp
token: r4nd0mt0k3n
service: another-service-check
To use the Nagios returner, append '--return nagios' to the salt command. ex:
.. code-block:: bash
salt '*' test.ping --return nagios
To use the alternative configuration, append '--return_config alternative' to the salt command. ex:
salt '*' test.ping --return nagios --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return nagios --return_kwargs '{"service": "service-name"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import cgi
import logging
import salt.returners
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
import salt.ext.six.moves.http_client
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
__virtualname__ = 'nagios_nrdp'
def __virtual__():
'''
Return virtualname
'''
return 'nagios.list_plugins' in __salt__
def _get_options(ret=None):
'''
Get the requests options from salt.
'''
attrs = {'url': 'url',
'token': 'token',
'service': 'service',
'checktype': 'checktype',
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
log.debug('attrs %s', attrs)
if 'checktype' not in _options or _options['checktype'] == '':
# default to passive check type
_options['checktype'] = '1'
if _options['checktype'] == 'active':
_options['checktype'] = '0'
if _options['checktype'] == 'passive':
_options['checktype'] = '1'
# checktype should be a string
_options['checktype'] = six.text_type(_options['checktype'])
return _options
def _prepare_xml(options=None, state=None):
'''
Get the requests options from salt.
'''
if state:
_state = '0'
else:
_state = '2'
xml = "<?xml version='1.0'?>\n<checkresults>\n"
# No service defined then we set the status of the hostname
if 'service' in options and options['service'] != '':
xml += "<checkresult type='service' checktype='" + six.text_type(options['checktype'])+"'>"
xml += "<hostname>"+cgi.escape(options['hostname'], True)+"</hostname>"
xml += "<servicename>"+cgi.escape(options['service'], True)+"</servicename>"
else:
xml += "<checkresult type='host' checktype='" + six.text_type(options['checktype'])+"'>"
xml += "<hostname>"+cgi.escape(options['hostname'], True)+"</hostname>"
xml += "<state>"+_state+"</state>"
if 'output' in options:
xml += "<output>"+cgi.escape(options['output'], True)+"</output>"
xml += "</checkresult>"
xml += "\n</checkresults>"
return xml
def _getText(nodelist):
'''
Simple function to return value from XML
'''
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
def _post_data(options=None, xml=None):
'''
Post data to Nagios NRDP
'''
params = {'token': options['token'].strip(), 'cmd': 'submitcheck', 'XMLDATA': xml}
res = salt.utils.http.query(
url=options['url'],
method='POST',
params=params,
data='',
decode=True,
status=True,
header_dict={},
opts=__opts__,
)
if res.get('status', None) == salt.ext.six.moves.http_client.OK:
if res.get('dict', None) and isinstance(res['dict'], list):
_content = res['dict'][0]
if _content.get('status', None):
return True
else:
return False
else:
log.error('No content returned from Nagios NRDP.')
return False
else:
log.error(
'Error returned from Nagios NRDP. Status code: %s.',
res.status_code
)
return False
|
saltstack/salt
|
salt/returners/influxdb_return.py
|
_get_serv
|
python
|
def _get_serv(ret=None):
'''
Return an influxdb client object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
database = _options.get('db')
user = _options.get('user')
password = _options.get('password')
version = _get_version(host, port, user, password)
if version and "v0.8" in version:
return influxdb.influxdb08.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
else:
return influxdb.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
|
Return an influxdb client object
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/influxdb_return.py#L122-L147
|
[
"def _get_options(ret=None):\n '''\n Get the influxdb options from salt.\n '''\n attrs = {'host': 'host',\n 'port': 'port',\n 'db': 'db',\n 'user': 'user',\n 'password': 'password'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n return _options\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to an influxdb server.
.. versionadded:: 2015.8.0
To enable this returner the minion will need the python client for influxdb
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
influxdb.db: 'salt'
influxdb.user: 'salt'
influxdb.password: 'salt'
influxdb.host: 'localhost'
influxdb.port: 8086
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.influxdb.db: 'salt'
alternative.influxdb.user: 'salt'
alternative.influxdb.password: 'salt'
alternative.influxdb.host: 'localhost'
alternative.influxdb.port: 6379
To use the influxdb returner, append '--return influxdb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return influxdb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import requests
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.utils.decorators import memoize
# Import third party libs
try:
import influxdb
import influxdb.influxdb08
HAS_INFLUXDB = True
except ImportError:
HAS_INFLUXDB = False
# HTTP API header used to check the InfluxDB version
influxDBVersionHeader = "X-Influxdb-Version"
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'influxdb'
def __virtual__():
if not HAS_INFLUXDB:
return False, 'Could not import influxdb returner; ' \
'influxdb python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the influxdb options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@memoize
def _get_version(host, port, user, password):
version = None
# check the InfluxDB version via the HTTP API
try:
result = requests.get("http://{0}:{1}/ping".format(host, port), auth=(user, password))
if influxDBVersionHeader in result.headers:
version = result.headers[influxDBVersionHeader]
except Exception as ex:
log.critical(
'Failed to query InfluxDB version from HTTP API within InfluxDB '
'returner: %s', ex
)
return version
def returner(ret):
'''
Return data to a influxdb data store
'''
serv = _get_serv(ret)
# strip the 'return' key to avoid data duplication in the database
json_return = salt.utils.json.dumps(ret['return'])
del ret['return']
json_full_ret = salt.utils.json.dumps(ret)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'returns',
'columns': ['fun', 'id', 'jid', 'return', 'full_ret'],
'points': [
[ret['fun'], ret['id'], ret['jid'], json_return, json_full_ret]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'returns',
'tags': {
'fun': ret['fun'],
'id': ret['id'],
'jid': ret['jid']
},
'fields': {
'return': json_return,
'full_ret': json_full_ret
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store return with InfluxDB returner: %s', ex)
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'jids',
'columns': ['jid', 'load'],
'points': [
[jid, salt.utils.json.dumps(load)]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'jids',
'tags': {
'jid': jid
},
'fields': {
'load': salt.utils.json.dumps(load)
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store load with InfluxDB returner: %s', ex)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
sql = "select load from jids where jid = '{0}'".format(jid)
log.debug(">> Now in get_load %s", jid)
data = serv.query(sql)
log.debug(">> Now Data: %s", data)
if data:
return data
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
sql = "select id, full_ret from returns where jid = '{0}'".format(jid)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[3]] = salt.utils.json.loads(point[2])
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
sql = '''select first(id) as fid, first(full_ret) as fret
from returns
where fun = '{0}'
group by fun, id
'''.format(fun)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[1]] = salt.utils.json.loads(point[2])
return ret
def get_jids():
'''
Return a list of all job ids
'''
serv = _get_serv(ret=None)
sql = "select distinct(jid) from jids group by load"
# [{u'points': [[0, jid, load],
# [0, jid, load]],
# u'name': u'jids',
# u'columns': [u'time', u'distinct', u'load']}]
data = serv.query(sql)
ret = {}
if data:
for _, jid, load in data[0]['points']:
ret[jid] = salt.utils.jid.format_jid_instance(jid, salt.utils.json.loads(load))
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
sql = "select distinct(id) from returns"
data = serv.query(sql)
ret = []
if data:
for jid in data[0]['points']:
ret.append(jid[1])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/influxdb_return.py
|
returner
|
python
|
def returner(ret):
'''
Return data to a influxdb data store
'''
serv = _get_serv(ret)
# strip the 'return' key to avoid data duplication in the database
json_return = salt.utils.json.dumps(ret['return'])
del ret['return']
json_full_ret = salt.utils.json.dumps(ret)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'returns',
'columns': ['fun', 'id', 'jid', 'return', 'full_ret'],
'points': [
[ret['fun'], ret['id'], ret['jid'], json_return, json_full_ret]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'returns',
'tags': {
'fun': ret['fun'],
'id': ret['id'],
'jid': ret['jid']
},
'fields': {
'return': json_return,
'full_ret': json_full_ret
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store return with InfluxDB returner: %s', ex)
|
Return data to a influxdb data store
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/influxdb_return.py#L150-L192
|
[
"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 _get_serv(ret=None):\n '''\n Return an influxdb client object\n '''\n _options = _get_options(ret)\n host = _options.get('host')\n port = _options.get('port')\n database = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n version = _get_version(host, port, user, password)\n\n if version and \"v0.8\" in version:\n return influxdb.influxdb08.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n else:\n return influxdb.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to an influxdb server.
.. versionadded:: 2015.8.0
To enable this returner the minion will need the python client for influxdb
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
influxdb.db: 'salt'
influxdb.user: 'salt'
influxdb.password: 'salt'
influxdb.host: 'localhost'
influxdb.port: 8086
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.influxdb.db: 'salt'
alternative.influxdb.user: 'salt'
alternative.influxdb.password: 'salt'
alternative.influxdb.host: 'localhost'
alternative.influxdb.port: 6379
To use the influxdb returner, append '--return influxdb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return influxdb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import requests
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.utils.decorators import memoize
# Import third party libs
try:
import influxdb
import influxdb.influxdb08
HAS_INFLUXDB = True
except ImportError:
HAS_INFLUXDB = False
# HTTP API header used to check the InfluxDB version
influxDBVersionHeader = "X-Influxdb-Version"
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'influxdb'
def __virtual__():
if not HAS_INFLUXDB:
return False, 'Could not import influxdb returner; ' \
'influxdb python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the influxdb options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@memoize
def _get_version(host, port, user, password):
version = None
# check the InfluxDB version via the HTTP API
try:
result = requests.get("http://{0}:{1}/ping".format(host, port), auth=(user, password))
if influxDBVersionHeader in result.headers:
version = result.headers[influxDBVersionHeader]
except Exception as ex:
log.critical(
'Failed to query InfluxDB version from HTTP API within InfluxDB '
'returner: %s', ex
)
return version
def _get_serv(ret=None):
'''
Return an influxdb client object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
database = _options.get('db')
user = _options.get('user')
password = _options.get('password')
version = _get_version(host, port, user, password)
if version and "v0.8" in version:
return influxdb.influxdb08.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
else:
return influxdb.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'jids',
'columns': ['jid', 'load'],
'points': [
[jid, salt.utils.json.dumps(load)]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'jids',
'tags': {
'jid': jid
},
'fields': {
'load': salt.utils.json.dumps(load)
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store load with InfluxDB returner: %s', ex)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
sql = "select load from jids where jid = '{0}'".format(jid)
log.debug(">> Now in get_load %s", jid)
data = serv.query(sql)
log.debug(">> Now Data: %s", data)
if data:
return data
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
sql = "select id, full_ret from returns where jid = '{0}'".format(jid)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[3]] = salt.utils.json.loads(point[2])
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
sql = '''select first(id) as fid, first(full_ret) as fret
from returns
where fun = '{0}'
group by fun, id
'''.format(fun)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[1]] = salt.utils.json.loads(point[2])
return ret
def get_jids():
'''
Return a list of all job ids
'''
serv = _get_serv(ret=None)
sql = "select distinct(jid) from jids group by load"
# [{u'points': [[0, jid, load],
# [0, jid, load]],
# u'name': u'jids',
# u'columns': [u'time', u'distinct', u'load']}]
data = serv.query(sql)
ret = {}
if data:
for _, jid, load in data[0]['points']:
ret[jid] = salt.utils.jid.format_jid_instance(jid, salt.utils.json.loads(load))
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
sql = "select distinct(id) from returns"
data = serv.query(sql)
ret = []
if data:
for jid in data[0]['points']:
ret.append(jid[1])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/influxdb_return.py
|
save_load
|
python
|
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'jids',
'columns': ['jid', 'load'],
'points': [
[jid, salt.utils.json.dumps(load)]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'jids',
'tags': {
'jid': jid
},
'fields': {
'load': salt.utils.json.dumps(load)
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store load with InfluxDB returner: %s', ex)
|
Save the load to the specified jid
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/influxdb_return.py#L195-L229
|
[
"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 _get_serv(ret=None):\n '''\n Return an influxdb client object\n '''\n _options = _get_options(ret)\n host = _options.get('host')\n port = _options.get('port')\n database = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n version = _get_version(host, port, user, password)\n\n if version and \"v0.8\" in version:\n return influxdb.influxdb08.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n else:\n return influxdb.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to an influxdb server.
.. versionadded:: 2015.8.0
To enable this returner the minion will need the python client for influxdb
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
influxdb.db: 'salt'
influxdb.user: 'salt'
influxdb.password: 'salt'
influxdb.host: 'localhost'
influxdb.port: 8086
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.influxdb.db: 'salt'
alternative.influxdb.user: 'salt'
alternative.influxdb.password: 'salt'
alternative.influxdb.host: 'localhost'
alternative.influxdb.port: 6379
To use the influxdb returner, append '--return influxdb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return influxdb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import requests
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.utils.decorators import memoize
# Import third party libs
try:
import influxdb
import influxdb.influxdb08
HAS_INFLUXDB = True
except ImportError:
HAS_INFLUXDB = False
# HTTP API header used to check the InfluxDB version
influxDBVersionHeader = "X-Influxdb-Version"
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'influxdb'
def __virtual__():
if not HAS_INFLUXDB:
return False, 'Could not import influxdb returner; ' \
'influxdb python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the influxdb options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@memoize
def _get_version(host, port, user, password):
version = None
# check the InfluxDB version via the HTTP API
try:
result = requests.get("http://{0}:{1}/ping".format(host, port), auth=(user, password))
if influxDBVersionHeader in result.headers:
version = result.headers[influxDBVersionHeader]
except Exception as ex:
log.critical(
'Failed to query InfluxDB version from HTTP API within InfluxDB '
'returner: %s', ex
)
return version
def _get_serv(ret=None):
'''
Return an influxdb client object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
database = _options.get('db')
user = _options.get('user')
password = _options.get('password')
version = _get_version(host, port, user, password)
if version and "v0.8" in version:
return influxdb.influxdb08.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
else:
return influxdb.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
def returner(ret):
'''
Return data to a influxdb data store
'''
serv = _get_serv(ret)
# strip the 'return' key to avoid data duplication in the database
json_return = salt.utils.json.dumps(ret['return'])
del ret['return']
json_full_ret = salt.utils.json.dumps(ret)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'returns',
'columns': ['fun', 'id', 'jid', 'return', 'full_ret'],
'points': [
[ret['fun'], ret['id'], ret['jid'], json_return, json_full_ret]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'returns',
'tags': {
'fun': ret['fun'],
'id': ret['id'],
'jid': ret['jid']
},
'fields': {
'return': json_return,
'full_ret': json_full_ret
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store return with InfluxDB returner: %s', ex)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
sql = "select load from jids where jid = '{0}'".format(jid)
log.debug(">> Now in get_load %s", jid)
data = serv.query(sql)
log.debug(">> Now Data: %s", data)
if data:
return data
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
sql = "select id, full_ret from returns where jid = '{0}'".format(jid)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[3]] = salt.utils.json.loads(point[2])
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
sql = '''select first(id) as fid, first(full_ret) as fret
from returns
where fun = '{0}'
group by fun, id
'''.format(fun)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[1]] = salt.utils.json.loads(point[2])
return ret
def get_jids():
'''
Return a list of all job ids
'''
serv = _get_serv(ret=None)
sql = "select distinct(jid) from jids group by load"
# [{u'points': [[0, jid, load],
# [0, jid, load]],
# u'name': u'jids',
# u'columns': [u'time', u'distinct', u'load']}]
data = serv.query(sql)
ret = {}
if data:
for _, jid, load in data[0]['points']:
ret[jid] = salt.utils.jid.format_jid_instance(jid, salt.utils.json.loads(load))
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
sql = "select distinct(id) from returns"
data = serv.query(sql)
ret = []
if data:
for jid in data[0]['points']:
ret.append(jid[1])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/influxdb_return.py
|
get_load
|
python
|
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
sql = "select load from jids where jid = '{0}'".format(jid)
log.debug(">> Now in get_load %s", jid)
data = serv.query(sql)
log.debug(">> Now Data: %s", data)
if data:
return data
return {}
|
Return the load data that marks a specified jid
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/influxdb_return.py#L239-L251
|
[
"def _get_serv(ret=None):\n '''\n Return an influxdb client object\n '''\n _options = _get_options(ret)\n host = _options.get('host')\n port = _options.get('port')\n database = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n version = _get_version(host, port, user, password)\n\n if version and \"v0.8\" in version:\n return influxdb.influxdb08.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n else:\n return influxdb.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to an influxdb server.
.. versionadded:: 2015.8.0
To enable this returner the minion will need the python client for influxdb
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
influxdb.db: 'salt'
influxdb.user: 'salt'
influxdb.password: 'salt'
influxdb.host: 'localhost'
influxdb.port: 8086
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.influxdb.db: 'salt'
alternative.influxdb.user: 'salt'
alternative.influxdb.password: 'salt'
alternative.influxdb.host: 'localhost'
alternative.influxdb.port: 6379
To use the influxdb returner, append '--return influxdb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return influxdb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import requests
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.utils.decorators import memoize
# Import third party libs
try:
import influxdb
import influxdb.influxdb08
HAS_INFLUXDB = True
except ImportError:
HAS_INFLUXDB = False
# HTTP API header used to check the InfluxDB version
influxDBVersionHeader = "X-Influxdb-Version"
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'influxdb'
def __virtual__():
if not HAS_INFLUXDB:
return False, 'Could not import influxdb returner; ' \
'influxdb python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the influxdb options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@memoize
def _get_version(host, port, user, password):
version = None
# check the InfluxDB version via the HTTP API
try:
result = requests.get("http://{0}:{1}/ping".format(host, port), auth=(user, password))
if influxDBVersionHeader in result.headers:
version = result.headers[influxDBVersionHeader]
except Exception as ex:
log.critical(
'Failed to query InfluxDB version from HTTP API within InfluxDB '
'returner: %s', ex
)
return version
def _get_serv(ret=None):
'''
Return an influxdb client object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
database = _options.get('db')
user = _options.get('user')
password = _options.get('password')
version = _get_version(host, port, user, password)
if version and "v0.8" in version:
return influxdb.influxdb08.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
else:
return influxdb.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
def returner(ret):
'''
Return data to a influxdb data store
'''
serv = _get_serv(ret)
# strip the 'return' key to avoid data duplication in the database
json_return = salt.utils.json.dumps(ret['return'])
del ret['return']
json_full_ret = salt.utils.json.dumps(ret)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'returns',
'columns': ['fun', 'id', 'jid', 'return', 'full_ret'],
'points': [
[ret['fun'], ret['id'], ret['jid'], json_return, json_full_ret]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'returns',
'tags': {
'fun': ret['fun'],
'id': ret['id'],
'jid': ret['jid']
},
'fields': {
'return': json_return,
'full_ret': json_full_ret
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store return with InfluxDB returner: %s', ex)
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'jids',
'columns': ['jid', 'load'],
'points': [
[jid, salt.utils.json.dumps(load)]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'jids',
'tags': {
'jid': jid
},
'fields': {
'load': salt.utils.json.dumps(load)
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store load with InfluxDB returner: %s', ex)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
sql = "select id, full_ret from returns where jid = '{0}'".format(jid)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[3]] = salt.utils.json.loads(point[2])
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
sql = '''select first(id) as fid, first(full_ret) as fret
from returns
where fun = '{0}'
group by fun, id
'''.format(fun)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[1]] = salt.utils.json.loads(point[2])
return ret
def get_jids():
'''
Return a list of all job ids
'''
serv = _get_serv(ret=None)
sql = "select distinct(jid) from jids group by load"
# [{u'points': [[0, jid, load],
# [0, jid, load]],
# u'name': u'jids',
# u'columns': [u'time', u'distinct', u'load']}]
data = serv.query(sql)
ret = {}
if data:
for _, jid, load in data[0]['points']:
ret[jid] = salt.utils.jid.format_jid_instance(jid, salt.utils.json.loads(load))
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
sql = "select distinct(id) from returns"
data = serv.query(sql)
ret = []
if data:
for jid in data[0]['points']:
ret.append(jid[1])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/influxdb_return.py
|
get_jid
|
python
|
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
sql = "select id, full_ret from returns where jid = '{0}'".format(jid)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[3]] = salt.utils.json.loads(point[2])
return ret
|
Return the information returned when the specified job id was executed
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/influxdb_return.py#L254-L269
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\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 try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n",
"def _get_serv(ret=None):\n '''\n Return an influxdb client object\n '''\n _options = _get_options(ret)\n host = _options.get('host')\n port = _options.get('port')\n database = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n version = _get_version(host, port, user, password)\n\n if version and \"v0.8\" in version:\n return influxdb.influxdb08.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n else:\n return influxdb.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to an influxdb server.
.. versionadded:: 2015.8.0
To enable this returner the minion will need the python client for influxdb
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
influxdb.db: 'salt'
influxdb.user: 'salt'
influxdb.password: 'salt'
influxdb.host: 'localhost'
influxdb.port: 8086
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.influxdb.db: 'salt'
alternative.influxdb.user: 'salt'
alternative.influxdb.password: 'salt'
alternative.influxdb.host: 'localhost'
alternative.influxdb.port: 6379
To use the influxdb returner, append '--return influxdb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return influxdb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import requests
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.utils.decorators import memoize
# Import third party libs
try:
import influxdb
import influxdb.influxdb08
HAS_INFLUXDB = True
except ImportError:
HAS_INFLUXDB = False
# HTTP API header used to check the InfluxDB version
influxDBVersionHeader = "X-Influxdb-Version"
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'influxdb'
def __virtual__():
if not HAS_INFLUXDB:
return False, 'Could not import influxdb returner; ' \
'influxdb python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the influxdb options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@memoize
def _get_version(host, port, user, password):
version = None
# check the InfluxDB version via the HTTP API
try:
result = requests.get("http://{0}:{1}/ping".format(host, port), auth=(user, password))
if influxDBVersionHeader in result.headers:
version = result.headers[influxDBVersionHeader]
except Exception as ex:
log.critical(
'Failed to query InfluxDB version from HTTP API within InfluxDB '
'returner: %s', ex
)
return version
def _get_serv(ret=None):
'''
Return an influxdb client object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
database = _options.get('db')
user = _options.get('user')
password = _options.get('password')
version = _get_version(host, port, user, password)
if version and "v0.8" in version:
return influxdb.influxdb08.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
else:
return influxdb.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
def returner(ret):
'''
Return data to a influxdb data store
'''
serv = _get_serv(ret)
# strip the 'return' key to avoid data duplication in the database
json_return = salt.utils.json.dumps(ret['return'])
del ret['return']
json_full_ret = salt.utils.json.dumps(ret)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'returns',
'columns': ['fun', 'id', 'jid', 'return', 'full_ret'],
'points': [
[ret['fun'], ret['id'], ret['jid'], json_return, json_full_ret]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'returns',
'tags': {
'fun': ret['fun'],
'id': ret['id'],
'jid': ret['jid']
},
'fields': {
'return': json_return,
'full_ret': json_full_ret
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store return with InfluxDB returner: %s', ex)
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'jids',
'columns': ['jid', 'load'],
'points': [
[jid, salt.utils.json.dumps(load)]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'jids',
'tags': {
'jid': jid
},
'fields': {
'load': salt.utils.json.dumps(load)
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store load with InfluxDB returner: %s', ex)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
sql = "select load from jids where jid = '{0}'".format(jid)
log.debug(">> Now in get_load %s", jid)
data = serv.query(sql)
log.debug(">> Now Data: %s", data)
if data:
return data
return {}
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
sql = '''select first(id) as fid, first(full_ret) as fret
from returns
where fun = '{0}'
group by fun, id
'''.format(fun)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[1]] = salt.utils.json.loads(point[2])
return ret
def get_jids():
'''
Return a list of all job ids
'''
serv = _get_serv(ret=None)
sql = "select distinct(jid) from jids group by load"
# [{u'points': [[0, jid, load],
# [0, jid, load]],
# u'name': u'jids',
# u'columns': [u'time', u'distinct', u'load']}]
data = serv.query(sql)
ret = {}
if data:
for _, jid, load in data[0]['points']:
ret[jid] = salt.utils.jid.format_jid_instance(jid, salt.utils.json.loads(load))
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
sql = "select distinct(id) from returns"
data = serv.query(sql)
ret = []
if data:
for jid in data[0]['points']:
ret.append(jid[1])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/influxdb_return.py
|
get_fun
|
python
|
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
sql = '''select first(id) as fid, first(full_ret) as fret
from returns
where fun = '{0}'
group by fun, id
'''.format(fun)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[1]] = salt.utils.json.loads(point[2])
return ret
|
Return a dict of the last function called for all minions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/influxdb_return.py#L272-L291
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\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 try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n",
"def _get_serv(ret=None):\n '''\n Return an influxdb client object\n '''\n _options = _get_options(ret)\n host = _options.get('host')\n port = _options.get('port')\n database = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n version = _get_version(host, port, user, password)\n\n if version and \"v0.8\" in version:\n return influxdb.influxdb08.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n else:\n return influxdb.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to an influxdb server.
.. versionadded:: 2015.8.0
To enable this returner the minion will need the python client for influxdb
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
influxdb.db: 'salt'
influxdb.user: 'salt'
influxdb.password: 'salt'
influxdb.host: 'localhost'
influxdb.port: 8086
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.influxdb.db: 'salt'
alternative.influxdb.user: 'salt'
alternative.influxdb.password: 'salt'
alternative.influxdb.host: 'localhost'
alternative.influxdb.port: 6379
To use the influxdb returner, append '--return influxdb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return influxdb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import requests
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.utils.decorators import memoize
# Import third party libs
try:
import influxdb
import influxdb.influxdb08
HAS_INFLUXDB = True
except ImportError:
HAS_INFLUXDB = False
# HTTP API header used to check the InfluxDB version
influxDBVersionHeader = "X-Influxdb-Version"
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'influxdb'
def __virtual__():
if not HAS_INFLUXDB:
return False, 'Could not import influxdb returner; ' \
'influxdb python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the influxdb options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@memoize
def _get_version(host, port, user, password):
version = None
# check the InfluxDB version via the HTTP API
try:
result = requests.get("http://{0}:{1}/ping".format(host, port), auth=(user, password))
if influxDBVersionHeader in result.headers:
version = result.headers[influxDBVersionHeader]
except Exception as ex:
log.critical(
'Failed to query InfluxDB version from HTTP API within InfluxDB '
'returner: %s', ex
)
return version
def _get_serv(ret=None):
'''
Return an influxdb client object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
database = _options.get('db')
user = _options.get('user')
password = _options.get('password')
version = _get_version(host, port, user, password)
if version and "v0.8" in version:
return influxdb.influxdb08.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
else:
return influxdb.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
def returner(ret):
'''
Return data to a influxdb data store
'''
serv = _get_serv(ret)
# strip the 'return' key to avoid data duplication in the database
json_return = salt.utils.json.dumps(ret['return'])
del ret['return']
json_full_ret = salt.utils.json.dumps(ret)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'returns',
'columns': ['fun', 'id', 'jid', 'return', 'full_ret'],
'points': [
[ret['fun'], ret['id'], ret['jid'], json_return, json_full_ret]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'returns',
'tags': {
'fun': ret['fun'],
'id': ret['id'],
'jid': ret['jid']
},
'fields': {
'return': json_return,
'full_ret': json_full_ret
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store return with InfluxDB returner: %s', ex)
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'jids',
'columns': ['jid', 'load'],
'points': [
[jid, salt.utils.json.dumps(load)]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'jids',
'tags': {
'jid': jid
},
'fields': {
'load': salt.utils.json.dumps(load)
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store load with InfluxDB returner: %s', ex)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
sql = "select load from jids where jid = '{0}'".format(jid)
log.debug(">> Now in get_load %s", jid)
data = serv.query(sql)
log.debug(">> Now Data: %s", data)
if data:
return data
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
sql = "select id, full_ret from returns where jid = '{0}'".format(jid)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[3]] = salt.utils.json.loads(point[2])
return ret
def get_jids():
'''
Return a list of all job ids
'''
serv = _get_serv(ret=None)
sql = "select distinct(jid) from jids group by load"
# [{u'points': [[0, jid, load],
# [0, jid, load]],
# u'name': u'jids',
# u'columns': [u'time', u'distinct', u'load']}]
data = serv.query(sql)
ret = {}
if data:
for _, jid, load in data[0]['points']:
ret[jid] = salt.utils.jid.format_jid_instance(jid, salt.utils.json.loads(load))
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
sql = "select distinct(id) from returns"
data = serv.query(sql)
ret = []
if data:
for jid in data[0]['points']:
ret.append(jid[1])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/influxdb_return.py
|
get_jids
|
python
|
def get_jids():
'''
Return a list of all job ids
'''
serv = _get_serv(ret=None)
sql = "select distinct(jid) from jids group by load"
# [{u'points': [[0, jid, load],
# [0, jid, load]],
# u'name': u'jids',
# u'columns': [u'time', u'distinct', u'load']}]
data = serv.query(sql)
ret = {}
if data:
for _, jid, load in data[0]['points']:
ret[jid] = salt.utils.jid.format_jid_instance(jid, salt.utils.json.loads(load))
return ret
|
Return a list of all job ids
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/influxdb_return.py#L294-L310
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\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 try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n",
"def format_jid_instance(jid, job):\n '''\n Format the jid correctly\n '''\n ret = format_job_instance(job)\n ret.update({'StartTime': jid_to_time(jid)})\n return ret\n",
"def _get_serv(ret=None):\n '''\n Return an influxdb client object\n '''\n _options = _get_options(ret)\n host = _options.get('host')\n port = _options.get('port')\n database = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n version = _get_version(host, port, user, password)\n\n if version and \"v0.8\" in version:\n return influxdb.influxdb08.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n else:\n return influxdb.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to an influxdb server.
.. versionadded:: 2015.8.0
To enable this returner the minion will need the python client for influxdb
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
influxdb.db: 'salt'
influxdb.user: 'salt'
influxdb.password: 'salt'
influxdb.host: 'localhost'
influxdb.port: 8086
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.influxdb.db: 'salt'
alternative.influxdb.user: 'salt'
alternative.influxdb.password: 'salt'
alternative.influxdb.host: 'localhost'
alternative.influxdb.port: 6379
To use the influxdb returner, append '--return influxdb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return influxdb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import requests
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.utils.decorators import memoize
# Import third party libs
try:
import influxdb
import influxdb.influxdb08
HAS_INFLUXDB = True
except ImportError:
HAS_INFLUXDB = False
# HTTP API header used to check the InfluxDB version
influxDBVersionHeader = "X-Influxdb-Version"
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'influxdb'
def __virtual__():
if not HAS_INFLUXDB:
return False, 'Could not import influxdb returner; ' \
'influxdb python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the influxdb options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@memoize
def _get_version(host, port, user, password):
version = None
# check the InfluxDB version via the HTTP API
try:
result = requests.get("http://{0}:{1}/ping".format(host, port), auth=(user, password))
if influxDBVersionHeader in result.headers:
version = result.headers[influxDBVersionHeader]
except Exception as ex:
log.critical(
'Failed to query InfluxDB version from HTTP API within InfluxDB '
'returner: %s', ex
)
return version
def _get_serv(ret=None):
'''
Return an influxdb client object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
database = _options.get('db')
user = _options.get('user')
password = _options.get('password')
version = _get_version(host, port, user, password)
if version and "v0.8" in version:
return influxdb.influxdb08.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
else:
return influxdb.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
def returner(ret):
'''
Return data to a influxdb data store
'''
serv = _get_serv(ret)
# strip the 'return' key to avoid data duplication in the database
json_return = salt.utils.json.dumps(ret['return'])
del ret['return']
json_full_ret = salt.utils.json.dumps(ret)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'returns',
'columns': ['fun', 'id', 'jid', 'return', 'full_ret'],
'points': [
[ret['fun'], ret['id'], ret['jid'], json_return, json_full_ret]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'returns',
'tags': {
'fun': ret['fun'],
'id': ret['id'],
'jid': ret['jid']
},
'fields': {
'return': json_return,
'full_ret': json_full_ret
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store return with InfluxDB returner: %s', ex)
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'jids',
'columns': ['jid', 'load'],
'points': [
[jid, salt.utils.json.dumps(load)]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'jids',
'tags': {
'jid': jid
},
'fields': {
'load': salt.utils.json.dumps(load)
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store load with InfluxDB returner: %s', ex)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
sql = "select load from jids where jid = '{0}'".format(jid)
log.debug(">> Now in get_load %s", jid)
data = serv.query(sql)
log.debug(">> Now Data: %s", data)
if data:
return data
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
sql = "select id, full_ret from returns where jid = '{0}'".format(jid)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[3]] = salt.utils.json.loads(point[2])
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
sql = '''select first(id) as fid, first(full_ret) as fret
from returns
where fun = '{0}'
group by fun, id
'''.format(fun)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[1]] = salt.utils.json.loads(point[2])
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
sql = "select distinct(id) from returns"
data = serv.query(sql)
ret = []
if data:
for jid in data[0]['points']:
ret.append(jid[1])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/influxdb_return.py
|
get_minions
|
python
|
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
sql = "select distinct(id) from returns"
data = serv.query(sql)
ret = []
if data:
for jid in data[0]['points']:
ret.append(jid[1])
return ret
|
Return a list of minions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/influxdb_return.py#L313-L326
|
[
"def _get_serv(ret=None):\n '''\n Return an influxdb client object\n '''\n _options = _get_options(ret)\n host = _options.get('host')\n port = _options.get('port')\n database = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n version = _get_version(host, port, user, password)\n\n if version and \"v0.8\" in version:\n return influxdb.influxdb08.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n else:\n return influxdb.InfluxDBClient(host=host,\n port=port,\n username=user,\n password=password,\n database=database\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to an influxdb server.
.. versionadded:: 2015.8.0
To enable this returner the minion will need the python client for influxdb
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
influxdb.db: 'salt'
influxdb.user: 'salt'
influxdb.password: 'salt'
influxdb.host: 'localhost'
influxdb.port: 8086
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.influxdb.db: 'salt'
alternative.influxdb.user: 'salt'
alternative.influxdb.password: 'salt'
alternative.influxdb.host: 'localhost'
alternative.influxdb.port: 6379
To use the influxdb returner, append '--return influxdb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return influxdb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return influxdb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import requests
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.utils.decorators import memoize
# Import third party libs
try:
import influxdb
import influxdb.influxdb08
HAS_INFLUXDB = True
except ImportError:
HAS_INFLUXDB = False
# HTTP API header used to check the InfluxDB version
influxDBVersionHeader = "X-Influxdb-Version"
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'influxdb'
def __virtual__():
if not HAS_INFLUXDB:
return False, 'Could not import influxdb returner; ' \
'influxdb python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the influxdb options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@memoize
def _get_version(host, port, user, password):
version = None
# check the InfluxDB version via the HTTP API
try:
result = requests.get("http://{0}:{1}/ping".format(host, port), auth=(user, password))
if influxDBVersionHeader in result.headers:
version = result.headers[influxDBVersionHeader]
except Exception as ex:
log.critical(
'Failed to query InfluxDB version from HTTP API within InfluxDB '
'returner: %s', ex
)
return version
def _get_serv(ret=None):
'''
Return an influxdb client object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
database = _options.get('db')
user = _options.get('user')
password = _options.get('password')
version = _get_version(host, port, user, password)
if version and "v0.8" in version:
return influxdb.influxdb08.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
else:
return influxdb.InfluxDBClient(host=host,
port=port,
username=user,
password=password,
database=database
)
def returner(ret):
'''
Return data to a influxdb data store
'''
serv = _get_serv(ret)
# strip the 'return' key to avoid data duplication in the database
json_return = salt.utils.json.dumps(ret['return'])
del ret['return']
json_full_ret = salt.utils.json.dumps(ret)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'returns',
'columns': ['fun', 'id', 'jid', 'return', 'full_ret'],
'points': [
[ret['fun'], ret['id'], ret['jid'], json_return, json_full_ret]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'returns',
'tags': {
'fun': ret['fun'],
'id': ret['id'],
'jid': ret['jid']
},
'fields': {
'return': json_return,
'full_ret': json_full_ret
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store return with InfluxDB returner: %s', ex)
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
# create legacy request in case an InfluxDB 0.8.x version is used
if "influxdb08" in serv.__module__:
req = [
{
'name': 'jids',
'columns': ['jid', 'load'],
'points': [
[jid, salt.utils.json.dumps(load)]
],
}
]
# create InfluxDB 0.9+ version request
else:
req = [
{
'measurement': 'jids',
'tags': {
'jid': jid
},
'fields': {
'load': salt.utils.json.dumps(load)
}
}
]
try:
serv.write_points(req)
except Exception as ex:
log.critical('Failed to store load with InfluxDB returner: %s', ex)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
sql = "select load from jids where jid = '{0}'".format(jid)
log.debug(">> Now in get_load %s", jid)
data = serv.query(sql)
log.debug(">> Now Data: %s", data)
if data:
return data
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
sql = "select id, full_ret from returns where jid = '{0}'".format(jid)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[3]] = salt.utils.json.loads(point[2])
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
sql = '''select first(id) as fid, first(full_ret) as fret
from returns
where fun = '{0}'
group by fun, id
'''.format(fun)
data = serv.query(sql)
ret = {}
if data:
points = data[0]['points']
for point in points:
ret[point[1]] = salt.utils.json.loads(point[2])
return ret
def get_jids():
'''
Return a list of all job ids
'''
serv = _get_serv(ret=None)
sql = "select distinct(jid) from jids group by load"
# [{u'points': [[0, jid, load],
# [0, jid, load]],
# u'name': u'jids',
# u'columns': [u'time', u'distinct', u'load']}]
data = serv.query(sql)
ret = {}
if data:
for _, jid, load in data[0]['points']:
ret[jid] = salt.utils.jid.format_jid_instance(jid, salt.utils.json.loads(load))
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/utils/master.py
|
get_running_jobs
|
python
|
def get_running_jobs(opts):
'''
Return the running jobs on the master
'''
ret = []
proc_dir = os.path.join(opts['cachedir'], 'proc')
if not os.path.isdir(proc_dir):
return ret
for fn_ in os.listdir(proc_dir):
path = os.path.join(proc_dir, fn_)
data = read_proc_file(path, opts)
if not data:
continue
if not is_pid_healthy(data['pid']):
continue
ret.append(data)
return ret
|
Return the running jobs on the master
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L48-L65
|
[
"def read_proc_file(path, opts):\n '''\n Return a dict of JID metadata, or None\n '''\n serial = salt.payload.Serial(opts)\n with salt.utils.files.fopen(path, 'rb') as fp_:\n try:\n data = serial.load(fp_)\n except Exception as err:\n # need to add serial exception here\n # Could not read proc file\n log.warning(\"Issue deserializing data: %s\", err)\n return None\n\n if not isinstance(data, dict):\n # Invalid serial object\n log.warning(\"Data is not a dict: %s\", data)\n return None\n\n pid = data.get('pid', None)\n if not pid:\n # No pid, not a salt proc file\n log.warning(\"No PID found in data\")\n return None\n\n return data\n",
"def is_pid_healthy(pid):\n '''\n This is a health check that will confirm the PID is running\n and executed by salt.\n\n If pusutil is available:\n * all architectures are checked\n\n if psutil is not available:\n * Linux/Solaris/etc: archs with `/proc/cmdline` available are checked\n * AIX/Windows: assume PID is healhty and return True\n '''\n if HAS_PSUTIL:\n try:\n proc = psutil.Process(pid)\n except psutil.NoSuchProcess:\n log.warning(\"PID %s is no longer running.\", pid)\n return False\n return any(['salt' in cmd for cmd in proc.cmdline()])\n\n if salt.utils.platform.is_aix() or salt.utils.platform.is_windows():\n return True\n\n if not salt.utils.process.os_is_running(pid):\n log.warning(\"PID %s is no longer running.\", pid)\n return False\n\n cmdline_file = os.path.join('proc', str(pid), 'cmdline')\n try:\n with salt.utils.files.fopen(cmdline_file, 'rb') as fp_:\n return b'salt' in fp_.read()\n except (OSError, IOError) as err:\n log.error(\"There was a problem reading proc file: %s\", err)\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
salt.utils.master
-----------------
Utilities that can only be used on a salt master.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import os
import logging
import signal
from threading import Thread, Event
# Import salt libs
import salt.log
import salt.cache
import salt.client
import salt.pillar
import salt.utils.atomicfile
import salt.utils.files
import salt.utils.minions
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.verify
import salt.payload
from salt.exceptions import SaltException
import salt.config
from salt.utils.cache import CacheCli as cache_cli
from salt.utils.process import MultiprocessingProcess
# pylint: disable=import-error
try:
import salt.utils.psutil_compat as psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
# Import third party libs
from salt.ext import six
from salt.utils.zeromq import zmq
log = logging.getLogger(__name__)
def read_proc_file(path, opts):
'''
Return a dict of JID metadata, or None
'''
serial = salt.payload.Serial(opts)
with salt.utils.files.fopen(path, 'rb') as fp_:
try:
data = serial.load(fp_)
except Exception as err:
# need to add serial exception here
# Could not read proc file
log.warning("Issue deserializing data: %s", err)
return None
if not isinstance(data, dict):
# Invalid serial object
log.warning("Data is not a dict: %s", data)
return None
pid = data.get('pid', None)
if not pid:
# No pid, not a salt proc file
log.warning("No PID found in data")
return None
return data
def is_pid_healthy(pid):
'''
This is a health check that will confirm the PID is running
and executed by salt.
If pusutil is available:
* all architectures are checked
if psutil is not available:
* Linux/Solaris/etc: archs with `/proc/cmdline` available are checked
* AIX/Windows: assume PID is healhty and return True
'''
if HAS_PSUTIL:
try:
proc = psutil.Process(pid)
except psutil.NoSuchProcess:
log.warning("PID %s is no longer running.", pid)
return False
return any(['salt' in cmd for cmd in proc.cmdline()])
if salt.utils.platform.is_aix() or salt.utils.platform.is_windows():
return True
if not salt.utils.process.os_is_running(pid):
log.warning("PID %s is no longer running.", pid)
return False
cmdline_file = os.path.join('proc', str(pid), 'cmdline')
try:
with salt.utils.files.fopen(cmdline_file, 'rb') as fp_:
return b'salt' in fp_.read()
except (OSError, IOError) as err:
log.error("There was a problem reading proc file: %s", err)
return False
class MasterPillarUtil(object):
'''
Helper utility for easy access to targeted minion grain and
pillar data, either from cached data on the master or retrieved
on demand, or (by default) both.
The minion pillar data returned in get_minion_pillar() is
compiled directly from salt.pillar.Pillar on the master to
avoid any possible 'pillar poisoning' from a compromised or
untrusted minion.
** However, the minion grains are still possibly entirely
supplied by the minion. **
Example use case:
For runner modules that need access minion pillar data,
MasterPillarUtil.get_minion_pillar should be used instead
of getting the pillar data by executing the "pillar" module
on the minions:
# my_runner.py
tgt = 'web*'
pillar_util = salt.utils.master.MasterPillarUtil(tgt, tgt_type='glob', opts=__opts__)
pillar_data = pillar_util.get_minion_pillar()
'''
def __init__(self,
tgt='',
tgt_type='glob',
saltenv=None,
use_cached_grains=True,
use_cached_pillar=True,
grains_fallback=True,
pillar_fallback=True,
opts=None):
log.debug('New instance of %s created.',
self.__class__.__name__)
if opts is None:
log.error('%s: Missing master opts init arg.',
self.__class__.__name__)
raise SaltException('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
else:
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.tgt = tgt
self.tgt_type = tgt_type
self.saltenv = saltenv
self.use_cached_grains = use_cached_grains
self.use_cached_pillar = use_cached_pillar
self.grains_fallback = grains_fallback
self.pillar_fallback = pillar_fallback
self.cache = salt.cache.factory(opts)
log.debug(
'Init settings: tgt: \'%s\', tgt_type: \'%s\', saltenv: \'%s\', '
'use_cached_grains: %s, use_cached_pillar: %s, '
'grains_fallback: %s, pillar_fallback: %s',
tgt, tgt_type, saltenv, use_cached_grains, use_cached_pillar,
grains_fallback, pillar_fallback
)
def _get_cached_mine_data(self, *minion_ids):
# Return one dict with the cached mine data of the targeted minions
mine_data = dict([(minion_id, {}) for minion_id in minion_ids])
if (not self.opts.get('minion_data_cache', False)
and not self.opts.get('enforce_mine_cache', False)):
log.debug('Skipping cached mine data minion_data_cache'
'and enfore_mine_cache are both disabled.')
return mine_data
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'mine')
if isinstance(mdata, dict):
mine_data[minion_id] = mdata
return mine_data
def _get_cached_minion_data(self, *minion_ids):
# Return two separate dicts of cached grains and pillar data of the
# minions
grains = dict([(minion_id, {}) for minion_id in minion_ids])
pillars = grains.copy()
if not self.opts.get('minion_data_cache', False):
log.debug('Skipping cached data because minion_data_cache is not '
'enabled.')
return grains, pillars
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'data')
if not isinstance(mdata, dict):
log.warning(
'cache.fetch should always return a dict. ReturnedType: %s, MinionId: %s',
type(mdata).__name__,
minion_id
)
continue
if 'grains' in mdata:
grains[minion_id] = mdata['grains']
if 'pillar' in mdata:
pillars[minion_id] = mdata['pillar']
return grains, pillars
def _get_live_minion_grains(self, minion_ids):
# Returns a dict of grains fetched directly from the minions
log.debug('Getting live grains for minions: "%s"', minion_ids)
client = salt.client.get_local_client(self.opts['conf_file'])
ret = client.cmd(
','.join(minion_ids),
'grains.items',
timeout=self.opts['timeout'],
tgt_type='list')
return ret
def _get_live_minion_pillar(self, minion_id=None, minion_grains=None):
# Returns a dict of pillar data for one minion
if minion_id is None:
return {}
if not minion_grains:
log.warning(
'Cannot get pillar data for %s: no grains supplied.',
minion_id
)
return {}
log.debug('Getting live pillar for %s', minion_id)
pillar = salt.pillar.Pillar(
self.opts,
minion_grains,
minion_id,
self.saltenv,
self.opts['ext_pillar'])
log.debug('Compiling pillar for %s', minion_id)
ret = pillar.compile_pillar()
return ret
def _get_minion_grains(self, *minion_ids, **kwargs):
# Get the minion grains either from cache or from a direct query
# on the minion. By default try to use cached grains first, then
# fall back to querying the minion directly.
ret = {}
cached_grains = kwargs.get('cached_grains', {})
cret = {}
lret = {}
if self.use_cached_grains:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
lret = self._get_live_minion_grains(missed_minions)
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = self._get_live_minion_grains(minion_ids)
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _get_minion_pillar(self, *minion_ids, **kwargs):
# Get the minion pillar either from cache or from a direct query
# on the minion. By default try use the cached pillar first, then
# fall back to rendering pillar on demand with the supplied grains.
ret = {}
grains = kwargs.get('grains', {})
cached_pillar = kwargs.get('cached_pillar', {})
cret = {}
lret = {}
if self.use_cached_pillar:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in missed_minions])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in minion_ids])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _tgt_to_list(self):
# Return a list of minion ids that match the target and tgt_type
minion_ids = []
ckminions = salt.utils.minions.CkMinions(self.opts)
_res = ckminions.check_minions(self.tgt, self.tgt_type)
minion_ids = _res['minions']
if not minion_ids:
log.debug('No minions matched for tgt="%s" and tgt_type="%s"', self.tgt, self.tgt_type)
return {}
log.debug('Matching minions for tgt="%s" and tgt_type="%s": %s', self.tgt, self.tgt_type, minion_ids)
return minion_ids
def get_minion_pillar(self):
'''
Get pillar data for the targeted minions, either by fetching the
cached minion data on the master, or by compiling the minion's
pillar data on the master.
For runner modules that need access minion pillar data, this
function should be used instead of getting the pillar data by
executing the pillar module on the minions.
By default, this function tries hard to get the pillar data:
- Try to get the cached minion grains and pillar if the
master has minion_data_cache: True
- If the pillar data for the minion is cached, use it.
- If there is no cached grains/pillar data for a minion,
then try to get the minion grains directly from the minion.
- Use the minion grains to compile the pillar directly from the
master using salt.pillar.Pillar
'''
minion_pillars = {}
minion_grains = {}
minion_ids = self._tgt_to_list()
if any(arg for arg in [self.use_cached_grains, self.use_cached_pillar, self.grains_fallback, self.pillar_fallback]):
log.debug('Getting cached minion data')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
cached_minion_pillars = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
log.debug('Getting minion pillar data for: %s', minion_ids)
minion_pillars = self._get_minion_pillar(
*minion_ids,
grains=minion_grains,
cached_pillar=cached_minion_pillars)
return minion_pillars
def get_minion_grains(self):
'''
Get grains data for the targeted minions, either by fetching the
cached minion data on the master, or by fetching the grains
directly on the minion.
By default, this function tries hard to get the grains data:
- Try to get the cached minion grains if the master
has minion_data_cache: True
- If the grains data for the minion is cached, use it.
- If there is no cached grains data for a minion,
then try to get the minion grains directly from the minion.
'''
minion_grains = {}
minion_ids = self._tgt_to_list()
if not minion_ids:
return {}
if any(arg for arg in [self.use_cached_grains, self.grains_fallback]):
log.debug('Getting cached minion data.')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
return minion_grains
def get_cached_mine_data(self):
'''
Get cached mine data for the targeted minions.
'''
mine_data = {}
minion_ids = self._tgt_to_list()
log.debug('Getting cached mine data for: %s', minion_ids)
mine_data = self._get_cached_mine_data(*minion_ids)
return mine_data
def clear_cached_minion_data(self,
clear_pillar=False,
clear_grains=False,
clear_mine=False,
clear_mine_func=None):
'''
Clear the cached data/files for the targeted minions.
'''
clear_what = []
if clear_pillar:
clear_what.append('pillar')
if clear_grains:
clear_what.append('grains')
if clear_mine:
clear_what.append('mine')
if clear_mine_func is not None:
clear_what.append('mine_func: \'{0}\''.format(clear_mine_func))
if not clear_what:
log.debug('No cached data types specified for clearing.')
return False
minion_ids = self._tgt_to_list()
log.debug('Clearing cached %s data for: %s',
', '.join(clear_what),
minion_ids)
if clear_pillar == clear_grains:
# clear_pillar and clear_grains are both True or both False.
# This means we don't deal with pillar/grains caches at all.
grains = {}
pillars = {}
else:
# Unless both clear_pillar and clear_grains are True, we need
# to read in the pillar/grains data since they are both stored
# in the same file, 'data.p'
grains, pillars = self._get_cached_minion_data(*minion_ids)
try:
c_minions = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
if minion_id not in c_minions:
# Cache bank for this minion does not exist. Nothing to do.
continue
bank = 'minions/{0}'.format(minion_id)
minion_pillar = pillars.pop(minion_id, False)
minion_grains = grains.pop(minion_id, False)
if ((clear_pillar and clear_grains) or
(clear_pillar and not minion_grains) or
(clear_grains and not minion_pillar)):
# Not saving pillar or grains, so just delete the cache file
self.cache.flush(bank, 'data')
elif clear_pillar and minion_grains:
self.cache.store(bank, 'data', {'grains': minion_grains})
elif clear_grains and minion_pillar:
self.cache.store(bank, 'data', {'pillar': minion_pillar})
if clear_mine:
# Delete the whole mine file
self.cache.flush(bank, 'mine')
elif clear_mine_func is not None:
# Delete a specific function from the mine file
mine_data = self.cache.fetch(bank, 'mine')
if isinstance(mine_data, dict):
if mine_data.pop(clear_mine_func, False):
self.cache.store(bank, 'mine', mine_data)
except (OSError, IOError):
return True
return True
class CacheTimer(Thread):
'''
A basic timer class the fires timer-events every second.
This is used for cleanup by the ConnectedCache()
'''
def __init__(self, opts, event):
Thread.__init__(self)
self.opts = opts
self.stopped = event
self.daemon = True
self.serial = salt.payload.Serial(opts.get('serial', ''))
self.timer_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
def run(self):
'''
main loop that fires the event every second
'''
context = zmq.Context()
# the socket for outgoing timer events
socket = context.socket(zmq.PUB)
socket.setsockopt(zmq.LINGER, 100)
socket.bind('ipc://' + self.timer_sock)
count = 0
log.debug('ConCache-Timer started')
while not self.stopped.wait(1):
socket.send(self.serial.dumps(count))
count += 1
if count >= 60:
count = 0
class CacheWorker(MultiprocessingProcess):
'''
Worker for ConnectedCache which runs in its
own process to prevent blocking of ConnectedCache
main-loop when refreshing minion-list
'''
def __init__(self, opts, **kwargs):
'''
Sets up the zmq-connection to the ConCache
'''
super(CacheWorker, self).__init__(**kwargs)
self.opts = opts
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def run(self):
'''
Gather currently connected minions and update the cache
'''
new_mins = list(salt.utils.minions.CkMinions(self.opts).connected_ids())
cc = cache_cli(self.opts)
cc.get_cached()
cc.put_cache([new_mins])
log.debug('ConCache CacheWorker update finished')
class ConnectedCache(MultiprocessingProcess):
'''
Provides access to all minions ids that the master has
successfully authenticated. The cache is cleaned up regularly by
comparing it to the IPs that have open connections to
the master publisher port.
'''
def __init__(self, opts, **kwargs):
'''
starts the timer and inits the cache itself
'''
super(ConnectedCache, self).__init__(**kwargs)
log.debug('ConCache initializing...')
# the possible settings for the cache
self.opts = opts
# the actual cached minion ids
self.minions = []
self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc')
self.update_sock = os.path.join(self.opts['sock_dir'], 'con_upd.ipc')
self.upd_t_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
self.cleanup()
# the timer provides 1-second intervals to the loop in run()
# to make the cache system most responsive, we do not use a loop-
# delay which makes it hard to get 1-second intervals without a timer
self.timer_stop = Event()
self.timer = CacheTimer(self.opts, self.timer_stop)
self.timer.start()
self.running = True
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def signal_handler(self, sig, frame):
'''
handle signals and shutdown
'''
self.stop()
def cleanup(self):
'''
remove sockets on shutdown
'''
log.debug('ConCache cleaning up')
if os.path.exists(self.cache_sock):
os.remove(self.cache_sock)
if os.path.exists(self.update_sock):
os.remove(self.update_sock)
if os.path.exists(self.upd_t_sock):
os.remove(self.upd_t_sock)
def secure(self):
'''
secure the sockets for root-only access
'''
log.debug('ConCache securing sockets')
if os.path.exists(self.cache_sock):
os.chmod(self.cache_sock, 0o600)
if os.path.exists(self.update_sock):
os.chmod(self.update_sock, 0o600)
if os.path.exists(self.upd_t_sock):
os.chmod(self.upd_t_sock, 0o600)
def stop(self):
'''
shutdown cache process
'''
# avoid getting called twice
self.cleanup()
if self.running:
self.running = False
self.timer_stop.set()
self.timer.join()
def run(self):
'''
Main loop of the ConCache, starts updates in intervals and
answers requests from the MWorkers
'''
context = zmq.Context()
# the socket for incoming cache requests
creq_in = context.socket(zmq.REP)
creq_in.setsockopt(zmq.LINGER, 100)
creq_in.bind('ipc://' + self.cache_sock)
# the socket for incoming cache-updates from workers
cupd_in = context.socket(zmq.SUB)
cupd_in.setsockopt(zmq.SUBSCRIBE, b'')
cupd_in.setsockopt(zmq.LINGER, 100)
cupd_in.bind('ipc://' + self.update_sock)
# the socket for the timer-event
timer_in = context.socket(zmq.SUB)
timer_in.setsockopt(zmq.SUBSCRIBE, b'')
timer_in.setsockopt(zmq.LINGER, 100)
timer_in.connect('ipc://' + self.upd_t_sock)
poller = zmq.Poller()
poller.register(creq_in, zmq.POLLIN)
poller.register(cupd_in, zmq.POLLIN)
poller.register(timer_in, zmq.POLLIN)
# our serializer
serial = salt.payload.Serial(self.opts.get('serial', ''))
# register a signal handler
signal.signal(signal.SIGINT, self.signal_handler)
# secure the sockets from the world
self.secure()
log.info('ConCache started')
while self.running:
# we check for new events with the poller
try:
socks = dict(poller.poll(1))
except KeyboardInterrupt:
self.stop()
except zmq.ZMQError as zmq_err:
log.error('ConCache ZeroMQ-Error occurred')
log.exception(zmq_err)
self.stop()
# check for next cache-request
if socks.get(creq_in) == zmq.POLLIN:
msg = serial.loads(creq_in.recv())
log.debug('ConCache Received request: %s', msg)
# requests to the minion list are send as str's
if isinstance(msg, six.string_types):
if msg == 'minions':
# Send reply back to client
reply = serial.dumps(self.minions)
creq_in.send(reply)
# check for next cache-update from workers
if socks.get(cupd_in) == zmq.POLLIN:
new_c_data = serial.loads(cupd_in.recv())
# tell the worker to exit
#cupd_in.send(serial.dumps('ACK'))
# check if the returned data is usable
if not isinstance(new_c_data, list):
log.error('ConCache Worker returned unusable result')
del new_c_data
continue
# the cache will receive lists of minions
# 1. if the list only has 1 item, its from an MWorker, we append it
# 2. if the list contains another list, its from a CacheWorker and
# the currently cached minions are replaced with that list
# 3. anything else is considered malformed
try:
if not new_c_data:
log.debug('ConCache Got empty update from worker')
continue
data = new_c_data[0]
if isinstance(data, six.string_types):
if data not in self.minions:
log.debug('ConCache Adding minion %s to cache',
new_c_data[0])
self.minions.append(data)
elif isinstance(data, list):
log.debug('ConCache Replacing minion list from worker')
self.minions = data
except IndexError:
log.debug('ConCache Got malformed result dict from worker')
del new_c_data
log.info('ConCache %s entries in cache', len(self.minions))
# check for next timer-event to start new jobs
if socks.get(timer_in) == zmq.POLLIN:
sec_event = serial.loads(timer_in.recv())
# update the list every 30 seconds
if int(sec_event % 30) == 0:
cw = CacheWorker(self.opts)
cw.start()
self.stop()
creq_in.close()
cupd_in.close()
timer_in.close()
context.term()
log.debug('ConCache Shutting down')
def ping_all_connected_minions(opts):
client = salt.client.LocalClient()
if opts['minion_data_cache']:
tgt = list(salt.utils.minions.CkMinions(opts).connected_ids())
form = 'list'
else:
tgt = '*'
form = 'glob'
client.cmd_async(tgt, 'test.ping', tgt_type=form)
def get_master_key(key_user, opts, skip_perm_errors=False):
if key_user == 'root':
if opts.get('user', 'root') != 'root':
key_user = opts.get('user', 'root')
if key_user.startswith('sudo_'):
key_user = opts.get('user', 'root')
if salt.utils.platform.is_windows():
# The username may contain '\' if it is in Windows
# 'DOMAIN\username' format. Fix this for the keyfile path.
key_user = key_user.replace('\\', '_')
keyfile = os.path.join(opts['cachedir'],
'.{0}_key'.format(key_user))
# Make sure all key parent directories are accessible
salt.utils.verify.check_path_traversal(opts['cachedir'],
key_user,
skip_perm_errors)
try:
with salt.utils.files.fopen(keyfile, 'r') as key:
return key.read()
except (OSError, IOError):
# Fall back to eauth
return ''
def get_values_of_matching_keys(pattern_dict, user_name):
'''
Check a whitelist and/or blacklist to see if the value matches it.
'''
ret = []
for expr in pattern_dict:
if salt.utils.stringutils.expr_match(user_name, expr):
ret.extend(pattern_dict[expr])
return ret
# test code for the ConCache class
if __name__ == '__main__':
opts = salt.config.master_config('/etc/salt/master')
conc = ConnectedCache(opts)
conc.start()
|
saltstack/salt
|
salt/utils/master.py
|
read_proc_file
|
python
|
def read_proc_file(path, opts):
'''
Return a dict of JID metadata, or None
'''
serial = salt.payload.Serial(opts)
with salt.utils.files.fopen(path, 'rb') as fp_:
try:
data = serial.load(fp_)
except Exception as err:
# need to add serial exception here
# Could not read proc file
log.warning("Issue deserializing data: %s", err)
return None
if not isinstance(data, dict):
# Invalid serial object
log.warning("Data is not a dict: %s", data)
return None
pid = data.get('pid', None)
if not pid:
# No pid, not a salt proc file
log.warning("No PID found in data")
return None
return data
|
Return a dict of JID metadata, or None
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L68-L93
|
[
"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 load(self, fn_):\n '''\n Run the correct serialization to load a file\n '''\n data = fn_.read()\n fn_.close()\n if data:\n if six.PY3:\n return self.loads(data, encoding='utf-8')\n else:\n return self.loads(data)\n"
] |
# -*- coding: utf-8 -*-
'''
salt.utils.master
-----------------
Utilities that can only be used on a salt master.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import os
import logging
import signal
from threading import Thread, Event
# Import salt libs
import salt.log
import salt.cache
import salt.client
import salt.pillar
import salt.utils.atomicfile
import salt.utils.files
import salt.utils.minions
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.verify
import salt.payload
from salt.exceptions import SaltException
import salt.config
from salt.utils.cache import CacheCli as cache_cli
from salt.utils.process import MultiprocessingProcess
# pylint: disable=import-error
try:
import salt.utils.psutil_compat as psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
# Import third party libs
from salt.ext import six
from salt.utils.zeromq import zmq
log = logging.getLogger(__name__)
def get_running_jobs(opts):
'''
Return the running jobs on the master
'''
ret = []
proc_dir = os.path.join(opts['cachedir'], 'proc')
if not os.path.isdir(proc_dir):
return ret
for fn_ in os.listdir(proc_dir):
path = os.path.join(proc_dir, fn_)
data = read_proc_file(path, opts)
if not data:
continue
if not is_pid_healthy(data['pid']):
continue
ret.append(data)
return ret
def is_pid_healthy(pid):
'''
This is a health check that will confirm the PID is running
and executed by salt.
If pusutil is available:
* all architectures are checked
if psutil is not available:
* Linux/Solaris/etc: archs with `/proc/cmdline` available are checked
* AIX/Windows: assume PID is healhty and return True
'''
if HAS_PSUTIL:
try:
proc = psutil.Process(pid)
except psutil.NoSuchProcess:
log.warning("PID %s is no longer running.", pid)
return False
return any(['salt' in cmd for cmd in proc.cmdline()])
if salt.utils.platform.is_aix() or salt.utils.platform.is_windows():
return True
if not salt.utils.process.os_is_running(pid):
log.warning("PID %s is no longer running.", pid)
return False
cmdline_file = os.path.join('proc', str(pid), 'cmdline')
try:
with salt.utils.files.fopen(cmdline_file, 'rb') as fp_:
return b'salt' in fp_.read()
except (OSError, IOError) as err:
log.error("There was a problem reading proc file: %s", err)
return False
class MasterPillarUtil(object):
'''
Helper utility for easy access to targeted minion grain and
pillar data, either from cached data on the master or retrieved
on demand, or (by default) both.
The minion pillar data returned in get_minion_pillar() is
compiled directly from salt.pillar.Pillar on the master to
avoid any possible 'pillar poisoning' from a compromised or
untrusted minion.
** However, the minion grains are still possibly entirely
supplied by the minion. **
Example use case:
For runner modules that need access minion pillar data,
MasterPillarUtil.get_minion_pillar should be used instead
of getting the pillar data by executing the "pillar" module
on the minions:
# my_runner.py
tgt = 'web*'
pillar_util = salt.utils.master.MasterPillarUtil(tgt, tgt_type='glob', opts=__opts__)
pillar_data = pillar_util.get_minion_pillar()
'''
def __init__(self,
tgt='',
tgt_type='glob',
saltenv=None,
use_cached_grains=True,
use_cached_pillar=True,
grains_fallback=True,
pillar_fallback=True,
opts=None):
log.debug('New instance of %s created.',
self.__class__.__name__)
if opts is None:
log.error('%s: Missing master opts init arg.',
self.__class__.__name__)
raise SaltException('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
else:
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.tgt = tgt
self.tgt_type = tgt_type
self.saltenv = saltenv
self.use_cached_grains = use_cached_grains
self.use_cached_pillar = use_cached_pillar
self.grains_fallback = grains_fallback
self.pillar_fallback = pillar_fallback
self.cache = salt.cache.factory(opts)
log.debug(
'Init settings: tgt: \'%s\', tgt_type: \'%s\', saltenv: \'%s\', '
'use_cached_grains: %s, use_cached_pillar: %s, '
'grains_fallback: %s, pillar_fallback: %s',
tgt, tgt_type, saltenv, use_cached_grains, use_cached_pillar,
grains_fallback, pillar_fallback
)
def _get_cached_mine_data(self, *minion_ids):
# Return one dict with the cached mine data of the targeted minions
mine_data = dict([(minion_id, {}) for minion_id in minion_ids])
if (not self.opts.get('minion_data_cache', False)
and not self.opts.get('enforce_mine_cache', False)):
log.debug('Skipping cached mine data minion_data_cache'
'and enfore_mine_cache are both disabled.')
return mine_data
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'mine')
if isinstance(mdata, dict):
mine_data[minion_id] = mdata
return mine_data
def _get_cached_minion_data(self, *minion_ids):
# Return two separate dicts of cached grains and pillar data of the
# minions
grains = dict([(minion_id, {}) for minion_id in minion_ids])
pillars = grains.copy()
if not self.opts.get('minion_data_cache', False):
log.debug('Skipping cached data because minion_data_cache is not '
'enabled.')
return grains, pillars
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'data')
if not isinstance(mdata, dict):
log.warning(
'cache.fetch should always return a dict. ReturnedType: %s, MinionId: %s',
type(mdata).__name__,
minion_id
)
continue
if 'grains' in mdata:
grains[minion_id] = mdata['grains']
if 'pillar' in mdata:
pillars[minion_id] = mdata['pillar']
return grains, pillars
def _get_live_minion_grains(self, minion_ids):
# Returns a dict of grains fetched directly from the minions
log.debug('Getting live grains for minions: "%s"', minion_ids)
client = salt.client.get_local_client(self.opts['conf_file'])
ret = client.cmd(
','.join(minion_ids),
'grains.items',
timeout=self.opts['timeout'],
tgt_type='list')
return ret
def _get_live_minion_pillar(self, minion_id=None, minion_grains=None):
# Returns a dict of pillar data for one minion
if minion_id is None:
return {}
if not minion_grains:
log.warning(
'Cannot get pillar data for %s: no grains supplied.',
minion_id
)
return {}
log.debug('Getting live pillar for %s', minion_id)
pillar = salt.pillar.Pillar(
self.opts,
minion_grains,
minion_id,
self.saltenv,
self.opts['ext_pillar'])
log.debug('Compiling pillar for %s', minion_id)
ret = pillar.compile_pillar()
return ret
def _get_minion_grains(self, *minion_ids, **kwargs):
# Get the minion grains either from cache or from a direct query
# on the minion. By default try to use cached grains first, then
# fall back to querying the minion directly.
ret = {}
cached_grains = kwargs.get('cached_grains', {})
cret = {}
lret = {}
if self.use_cached_grains:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
lret = self._get_live_minion_grains(missed_minions)
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = self._get_live_minion_grains(minion_ids)
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _get_minion_pillar(self, *minion_ids, **kwargs):
# Get the minion pillar either from cache or from a direct query
# on the minion. By default try use the cached pillar first, then
# fall back to rendering pillar on demand with the supplied grains.
ret = {}
grains = kwargs.get('grains', {})
cached_pillar = kwargs.get('cached_pillar', {})
cret = {}
lret = {}
if self.use_cached_pillar:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in missed_minions])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in minion_ids])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _tgt_to_list(self):
# Return a list of minion ids that match the target and tgt_type
minion_ids = []
ckminions = salt.utils.minions.CkMinions(self.opts)
_res = ckminions.check_minions(self.tgt, self.tgt_type)
minion_ids = _res['minions']
if not minion_ids:
log.debug('No minions matched for tgt="%s" and tgt_type="%s"', self.tgt, self.tgt_type)
return {}
log.debug('Matching minions for tgt="%s" and tgt_type="%s": %s', self.tgt, self.tgt_type, minion_ids)
return minion_ids
def get_minion_pillar(self):
'''
Get pillar data for the targeted minions, either by fetching the
cached minion data on the master, or by compiling the minion's
pillar data on the master.
For runner modules that need access minion pillar data, this
function should be used instead of getting the pillar data by
executing the pillar module on the minions.
By default, this function tries hard to get the pillar data:
- Try to get the cached minion grains and pillar if the
master has minion_data_cache: True
- If the pillar data for the minion is cached, use it.
- If there is no cached grains/pillar data for a minion,
then try to get the minion grains directly from the minion.
- Use the minion grains to compile the pillar directly from the
master using salt.pillar.Pillar
'''
minion_pillars = {}
minion_grains = {}
minion_ids = self._tgt_to_list()
if any(arg for arg in [self.use_cached_grains, self.use_cached_pillar, self.grains_fallback, self.pillar_fallback]):
log.debug('Getting cached minion data')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
cached_minion_pillars = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
log.debug('Getting minion pillar data for: %s', minion_ids)
minion_pillars = self._get_minion_pillar(
*minion_ids,
grains=minion_grains,
cached_pillar=cached_minion_pillars)
return minion_pillars
def get_minion_grains(self):
'''
Get grains data for the targeted minions, either by fetching the
cached minion data on the master, or by fetching the grains
directly on the minion.
By default, this function tries hard to get the grains data:
- Try to get the cached minion grains if the master
has minion_data_cache: True
- If the grains data for the minion is cached, use it.
- If there is no cached grains data for a minion,
then try to get the minion grains directly from the minion.
'''
minion_grains = {}
minion_ids = self._tgt_to_list()
if not minion_ids:
return {}
if any(arg for arg in [self.use_cached_grains, self.grains_fallback]):
log.debug('Getting cached minion data.')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
return minion_grains
def get_cached_mine_data(self):
'''
Get cached mine data for the targeted minions.
'''
mine_data = {}
minion_ids = self._tgt_to_list()
log.debug('Getting cached mine data for: %s', minion_ids)
mine_data = self._get_cached_mine_data(*minion_ids)
return mine_data
def clear_cached_minion_data(self,
clear_pillar=False,
clear_grains=False,
clear_mine=False,
clear_mine_func=None):
'''
Clear the cached data/files for the targeted minions.
'''
clear_what = []
if clear_pillar:
clear_what.append('pillar')
if clear_grains:
clear_what.append('grains')
if clear_mine:
clear_what.append('mine')
if clear_mine_func is not None:
clear_what.append('mine_func: \'{0}\''.format(clear_mine_func))
if not clear_what:
log.debug('No cached data types specified for clearing.')
return False
minion_ids = self._tgt_to_list()
log.debug('Clearing cached %s data for: %s',
', '.join(clear_what),
minion_ids)
if clear_pillar == clear_grains:
# clear_pillar and clear_grains are both True or both False.
# This means we don't deal with pillar/grains caches at all.
grains = {}
pillars = {}
else:
# Unless both clear_pillar and clear_grains are True, we need
# to read in the pillar/grains data since they are both stored
# in the same file, 'data.p'
grains, pillars = self._get_cached_minion_data(*minion_ids)
try:
c_minions = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
if minion_id not in c_minions:
# Cache bank for this minion does not exist. Nothing to do.
continue
bank = 'minions/{0}'.format(minion_id)
minion_pillar = pillars.pop(minion_id, False)
minion_grains = grains.pop(minion_id, False)
if ((clear_pillar and clear_grains) or
(clear_pillar and not minion_grains) or
(clear_grains and not minion_pillar)):
# Not saving pillar or grains, so just delete the cache file
self.cache.flush(bank, 'data')
elif clear_pillar and minion_grains:
self.cache.store(bank, 'data', {'grains': minion_grains})
elif clear_grains and minion_pillar:
self.cache.store(bank, 'data', {'pillar': minion_pillar})
if clear_mine:
# Delete the whole mine file
self.cache.flush(bank, 'mine')
elif clear_mine_func is not None:
# Delete a specific function from the mine file
mine_data = self.cache.fetch(bank, 'mine')
if isinstance(mine_data, dict):
if mine_data.pop(clear_mine_func, False):
self.cache.store(bank, 'mine', mine_data)
except (OSError, IOError):
return True
return True
class CacheTimer(Thread):
'''
A basic timer class the fires timer-events every second.
This is used for cleanup by the ConnectedCache()
'''
def __init__(self, opts, event):
Thread.__init__(self)
self.opts = opts
self.stopped = event
self.daemon = True
self.serial = salt.payload.Serial(opts.get('serial', ''))
self.timer_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
def run(self):
'''
main loop that fires the event every second
'''
context = zmq.Context()
# the socket for outgoing timer events
socket = context.socket(zmq.PUB)
socket.setsockopt(zmq.LINGER, 100)
socket.bind('ipc://' + self.timer_sock)
count = 0
log.debug('ConCache-Timer started')
while not self.stopped.wait(1):
socket.send(self.serial.dumps(count))
count += 1
if count >= 60:
count = 0
class CacheWorker(MultiprocessingProcess):
'''
Worker for ConnectedCache which runs in its
own process to prevent blocking of ConnectedCache
main-loop when refreshing minion-list
'''
def __init__(self, opts, **kwargs):
'''
Sets up the zmq-connection to the ConCache
'''
super(CacheWorker, self).__init__(**kwargs)
self.opts = opts
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def run(self):
'''
Gather currently connected minions and update the cache
'''
new_mins = list(salt.utils.minions.CkMinions(self.opts).connected_ids())
cc = cache_cli(self.opts)
cc.get_cached()
cc.put_cache([new_mins])
log.debug('ConCache CacheWorker update finished')
class ConnectedCache(MultiprocessingProcess):
'''
Provides access to all minions ids that the master has
successfully authenticated. The cache is cleaned up regularly by
comparing it to the IPs that have open connections to
the master publisher port.
'''
def __init__(self, opts, **kwargs):
'''
starts the timer and inits the cache itself
'''
super(ConnectedCache, self).__init__(**kwargs)
log.debug('ConCache initializing...')
# the possible settings for the cache
self.opts = opts
# the actual cached minion ids
self.minions = []
self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc')
self.update_sock = os.path.join(self.opts['sock_dir'], 'con_upd.ipc')
self.upd_t_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
self.cleanup()
# the timer provides 1-second intervals to the loop in run()
# to make the cache system most responsive, we do not use a loop-
# delay which makes it hard to get 1-second intervals without a timer
self.timer_stop = Event()
self.timer = CacheTimer(self.opts, self.timer_stop)
self.timer.start()
self.running = True
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def signal_handler(self, sig, frame):
'''
handle signals and shutdown
'''
self.stop()
def cleanup(self):
'''
remove sockets on shutdown
'''
log.debug('ConCache cleaning up')
if os.path.exists(self.cache_sock):
os.remove(self.cache_sock)
if os.path.exists(self.update_sock):
os.remove(self.update_sock)
if os.path.exists(self.upd_t_sock):
os.remove(self.upd_t_sock)
def secure(self):
'''
secure the sockets for root-only access
'''
log.debug('ConCache securing sockets')
if os.path.exists(self.cache_sock):
os.chmod(self.cache_sock, 0o600)
if os.path.exists(self.update_sock):
os.chmod(self.update_sock, 0o600)
if os.path.exists(self.upd_t_sock):
os.chmod(self.upd_t_sock, 0o600)
def stop(self):
'''
shutdown cache process
'''
# avoid getting called twice
self.cleanup()
if self.running:
self.running = False
self.timer_stop.set()
self.timer.join()
def run(self):
'''
Main loop of the ConCache, starts updates in intervals and
answers requests from the MWorkers
'''
context = zmq.Context()
# the socket for incoming cache requests
creq_in = context.socket(zmq.REP)
creq_in.setsockopt(zmq.LINGER, 100)
creq_in.bind('ipc://' + self.cache_sock)
# the socket for incoming cache-updates from workers
cupd_in = context.socket(zmq.SUB)
cupd_in.setsockopt(zmq.SUBSCRIBE, b'')
cupd_in.setsockopt(zmq.LINGER, 100)
cupd_in.bind('ipc://' + self.update_sock)
# the socket for the timer-event
timer_in = context.socket(zmq.SUB)
timer_in.setsockopt(zmq.SUBSCRIBE, b'')
timer_in.setsockopt(zmq.LINGER, 100)
timer_in.connect('ipc://' + self.upd_t_sock)
poller = zmq.Poller()
poller.register(creq_in, zmq.POLLIN)
poller.register(cupd_in, zmq.POLLIN)
poller.register(timer_in, zmq.POLLIN)
# our serializer
serial = salt.payload.Serial(self.opts.get('serial', ''))
# register a signal handler
signal.signal(signal.SIGINT, self.signal_handler)
# secure the sockets from the world
self.secure()
log.info('ConCache started')
while self.running:
# we check for new events with the poller
try:
socks = dict(poller.poll(1))
except KeyboardInterrupt:
self.stop()
except zmq.ZMQError as zmq_err:
log.error('ConCache ZeroMQ-Error occurred')
log.exception(zmq_err)
self.stop()
# check for next cache-request
if socks.get(creq_in) == zmq.POLLIN:
msg = serial.loads(creq_in.recv())
log.debug('ConCache Received request: %s', msg)
# requests to the minion list are send as str's
if isinstance(msg, six.string_types):
if msg == 'minions':
# Send reply back to client
reply = serial.dumps(self.minions)
creq_in.send(reply)
# check for next cache-update from workers
if socks.get(cupd_in) == zmq.POLLIN:
new_c_data = serial.loads(cupd_in.recv())
# tell the worker to exit
#cupd_in.send(serial.dumps('ACK'))
# check if the returned data is usable
if not isinstance(new_c_data, list):
log.error('ConCache Worker returned unusable result')
del new_c_data
continue
# the cache will receive lists of minions
# 1. if the list only has 1 item, its from an MWorker, we append it
# 2. if the list contains another list, its from a CacheWorker and
# the currently cached minions are replaced with that list
# 3. anything else is considered malformed
try:
if not new_c_data:
log.debug('ConCache Got empty update from worker')
continue
data = new_c_data[0]
if isinstance(data, six.string_types):
if data not in self.minions:
log.debug('ConCache Adding minion %s to cache',
new_c_data[0])
self.minions.append(data)
elif isinstance(data, list):
log.debug('ConCache Replacing minion list from worker')
self.minions = data
except IndexError:
log.debug('ConCache Got malformed result dict from worker')
del new_c_data
log.info('ConCache %s entries in cache', len(self.minions))
# check for next timer-event to start new jobs
if socks.get(timer_in) == zmq.POLLIN:
sec_event = serial.loads(timer_in.recv())
# update the list every 30 seconds
if int(sec_event % 30) == 0:
cw = CacheWorker(self.opts)
cw.start()
self.stop()
creq_in.close()
cupd_in.close()
timer_in.close()
context.term()
log.debug('ConCache Shutting down')
def ping_all_connected_minions(opts):
client = salt.client.LocalClient()
if opts['minion_data_cache']:
tgt = list(salt.utils.minions.CkMinions(opts).connected_ids())
form = 'list'
else:
tgt = '*'
form = 'glob'
client.cmd_async(tgt, 'test.ping', tgt_type=form)
def get_master_key(key_user, opts, skip_perm_errors=False):
if key_user == 'root':
if opts.get('user', 'root') != 'root':
key_user = opts.get('user', 'root')
if key_user.startswith('sudo_'):
key_user = opts.get('user', 'root')
if salt.utils.platform.is_windows():
# The username may contain '\' if it is in Windows
# 'DOMAIN\username' format. Fix this for the keyfile path.
key_user = key_user.replace('\\', '_')
keyfile = os.path.join(opts['cachedir'],
'.{0}_key'.format(key_user))
# Make sure all key parent directories are accessible
salt.utils.verify.check_path_traversal(opts['cachedir'],
key_user,
skip_perm_errors)
try:
with salt.utils.files.fopen(keyfile, 'r') as key:
return key.read()
except (OSError, IOError):
# Fall back to eauth
return ''
def get_values_of_matching_keys(pattern_dict, user_name):
'''
Check a whitelist and/or blacklist to see if the value matches it.
'''
ret = []
for expr in pattern_dict:
if salt.utils.stringutils.expr_match(user_name, expr):
ret.extend(pattern_dict[expr])
return ret
# test code for the ConCache class
if __name__ == '__main__':
opts = salt.config.master_config('/etc/salt/master')
conc = ConnectedCache(opts)
conc.start()
|
saltstack/salt
|
salt/utils/master.py
|
is_pid_healthy
|
python
|
def is_pid_healthy(pid):
'''
This is a health check that will confirm the PID is running
and executed by salt.
If pusutil is available:
* all architectures are checked
if psutil is not available:
* Linux/Solaris/etc: archs with `/proc/cmdline` available are checked
* AIX/Windows: assume PID is healhty and return True
'''
if HAS_PSUTIL:
try:
proc = psutil.Process(pid)
except psutil.NoSuchProcess:
log.warning("PID %s is no longer running.", pid)
return False
return any(['salt' in cmd for cmd in proc.cmdline()])
if salt.utils.platform.is_aix() or salt.utils.platform.is_windows():
return True
if not salt.utils.process.os_is_running(pid):
log.warning("PID %s is no longer running.", pid)
return False
cmdline_file = os.path.join('proc', str(pid), 'cmdline')
try:
with salt.utils.files.fopen(cmdline_file, 'rb') as fp_:
return b'salt' in fp_.read()
except (OSError, IOError) as err:
log.error("There was a problem reading proc file: %s", err)
return False
|
This is a health check that will confirm the PID is running
and executed by salt.
If pusutil is available:
* all architectures are checked
if psutil is not available:
* Linux/Solaris/etc: archs with `/proc/cmdline` available are checked
* AIX/Windows: assume PID is healhty and return True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L96-L129
| null |
# -*- coding: utf-8 -*-
'''
salt.utils.master
-----------------
Utilities that can only be used on a salt master.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import os
import logging
import signal
from threading import Thread, Event
# Import salt libs
import salt.log
import salt.cache
import salt.client
import salt.pillar
import salt.utils.atomicfile
import salt.utils.files
import salt.utils.minions
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.verify
import salt.payload
from salt.exceptions import SaltException
import salt.config
from salt.utils.cache import CacheCli as cache_cli
from salt.utils.process import MultiprocessingProcess
# pylint: disable=import-error
try:
import salt.utils.psutil_compat as psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
# Import third party libs
from salt.ext import six
from salt.utils.zeromq import zmq
log = logging.getLogger(__name__)
def get_running_jobs(opts):
'''
Return the running jobs on the master
'''
ret = []
proc_dir = os.path.join(opts['cachedir'], 'proc')
if not os.path.isdir(proc_dir):
return ret
for fn_ in os.listdir(proc_dir):
path = os.path.join(proc_dir, fn_)
data = read_proc_file(path, opts)
if not data:
continue
if not is_pid_healthy(data['pid']):
continue
ret.append(data)
return ret
def read_proc_file(path, opts):
'''
Return a dict of JID metadata, or None
'''
serial = salt.payload.Serial(opts)
with salt.utils.files.fopen(path, 'rb') as fp_:
try:
data = serial.load(fp_)
except Exception as err:
# need to add serial exception here
# Could not read proc file
log.warning("Issue deserializing data: %s", err)
return None
if not isinstance(data, dict):
# Invalid serial object
log.warning("Data is not a dict: %s", data)
return None
pid = data.get('pid', None)
if not pid:
# No pid, not a salt proc file
log.warning("No PID found in data")
return None
return data
class MasterPillarUtil(object):
'''
Helper utility for easy access to targeted minion grain and
pillar data, either from cached data on the master or retrieved
on demand, or (by default) both.
The minion pillar data returned in get_minion_pillar() is
compiled directly from salt.pillar.Pillar on the master to
avoid any possible 'pillar poisoning' from a compromised or
untrusted minion.
** However, the minion grains are still possibly entirely
supplied by the minion. **
Example use case:
For runner modules that need access minion pillar data,
MasterPillarUtil.get_minion_pillar should be used instead
of getting the pillar data by executing the "pillar" module
on the minions:
# my_runner.py
tgt = 'web*'
pillar_util = salt.utils.master.MasterPillarUtil(tgt, tgt_type='glob', opts=__opts__)
pillar_data = pillar_util.get_minion_pillar()
'''
def __init__(self,
tgt='',
tgt_type='glob',
saltenv=None,
use_cached_grains=True,
use_cached_pillar=True,
grains_fallback=True,
pillar_fallback=True,
opts=None):
log.debug('New instance of %s created.',
self.__class__.__name__)
if opts is None:
log.error('%s: Missing master opts init arg.',
self.__class__.__name__)
raise SaltException('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
else:
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.tgt = tgt
self.tgt_type = tgt_type
self.saltenv = saltenv
self.use_cached_grains = use_cached_grains
self.use_cached_pillar = use_cached_pillar
self.grains_fallback = grains_fallback
self.pillar_fallback = pillar_fallback
self.cache = salt.cache.factory(opts)
log.debug(
'Init settings: tgt: \'%s\', tgt_type: \'%s\', saltenv: \'%s\', '
'use_cached_grains: %s, use_cached_pillar: %s, '
'grains_fallback: %s, pillar_fallback: %s',
tgt, tgt_type, saltenv, use_cached_grains, use_cached_pillar,
grains_fallback, pillar_fallback
)
def _get_cached_mine_data(self, *minion_ids):
# Return one dict with the cached mine data of the targeted minions
mine_data = dict([(minion_id, {}) for minion_id in minion_ids])
if (not self.opts.get('minion_data_cache', False)
and not self.opts.get('enforce_mine_cache', False)):
log.debug('Skipping cached mine data minion_data_cache'
'and enfore_mine_cache are both disabled.')
return mine_data
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'mine')
if isinstance(mdata, dict):
mine_data[minion_id] = mdata
return mine_data
def _get_cached_minion_data(self, *minion_ids):
# Return two separate dicts of cached grains and pillar data of the
# minions
grains = dict([(minion_id, {}) for minion_id in minion_ids])
pillars = grains.copy()
if not self.opts.get('minion_data_cache', False):
log.debug('Skipping cached data because minion_data_cache is not '
'enabled.')
return grains, pillars
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'data')
if not isinstance(mdata, dict):
log.warning(
'cache.fetch should always return a dict. ReturnedType: %s, MinionId: %s',
type(mdata).__name__,
minion_id
)
continue
if 'grains' in mdata:
grains[minion_id] = mdata['grains']
if 'pillar' in mdata:
pillars[minion_id] = mdata['pillar']
return grains, pillars
def _get_live_minion_grains(self, minion_ids):
# Returns a dict of grains fetched directly from the minions
log.debug('Getting live grains for minions: "%s"', minion_ids)
client = salt.client.get_local_client(self.opts['conf_file'])
ret = client.cmd(
','.join(minion_ids),
'grains.items',
timeout=self.opts['timeout'],
tgt_type='list')
return ret
def _get_live_minion_pillar(self, minion_id=None, minion_grains=None):
# Returns a dict of pillar data for one minion
if minion_id is None:
return {}
if not minion_grains:
log.warning(
'Cannot get pillar data for %s: no grains supplied.',
minion_id
)
return {}
log.debug('Getting live pillar for %s', minion_id)
pillar = salt.pillar.Pillar(
self.opts,
minion_grains,
minion_id,
self.saltenv,
self.opts['ext_pillar'])
log.debug('Compiling pillar for %s', minion_id)
ret = pillar.compile_pillar()
return ret
def _get_minion_grains(self, *minion_ids, **kwargs):
# Get the minion grains either from cache or from a direct query
# on the minion. By default try to use cached grains first, then
# fall back to querying the minion directly.
ret = {}
cached_grains = kwargs.get('cached_grains', {})
cret = {}
lret = {}
if self.use_cached_grains:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
lret = self._get_live_minion_grains(missed_minions)
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = self._get_live_minion_grains(minion_ids)
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _get_minion_pillar(self, *minion_ids, **kwargs):
# Get the minion pillar either from cache or from a direct query
# on the minion. By default try use the cached pillar first, then
# fall back to rendering pillar on demand with the supplied grains.
ret = {}
grains = kwargs.get('grains', {})
cached_pillar = kwargs.get('cached_pillar', {})
cret = {}
lret = {}
if self.use_cached_pillar:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in missed_minions])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in minion_ids])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _tgt_to_list(self):
# Return a list of minion ids that match the target and tgt_type
minion_ids = []
ckminions = salt.utils.minions.CkMinions(self.opts)
_res = ckminions.check_minions(self.tgt, self.tgt_type)
minion_ids = _res['minions']
if not minion_ids:
log.debug('No minions matched for tgt="%s" and tgt_type="%s"', self.tgt, self.tgt_type)
return {}
log.debug('Matching minions for tgt="%s" and tgt_type="%s": %s', self.tgt, self.tgt_type, minion_ids)
return minion_ids
def get_minion_pillar(self):
'''
Get pillar data for the targeted minions, either by fetching the
cached minion data on the master, or by compiling the minion's
pillar data on the master.
For runner modules that need access minion pillar data, this
function should be used instead of getting the pillar data by
executing the pillar module on the minions.
By default, this function tries hard to get the pillar data:
- Try to get the cached minion grains and pillar if the
master has minion_data_cache: True
- If the pillar data for the minion is cached, use it.
- If there is no cached grains/pillar data for a minion,
then try to get the minion grains directly from the minion.
- Use the minion grains to compile the pillar directly from the
master using salt.pillar.Pillar
'''
minion_pillars = {}
minion_grains = {}
minion_ids = self._tgt_to_list()
if any(arg for arg in [self.use_cached_grains, self.use_cached_pillar, self.grains_fallback, self.pillar_fallback]):
log.debug('Getting cached minion data')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
cached_minion_pillars = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
log.debug('Getting minion pillar data for: %s', minion_ids)
minion_pillars = self._get_minion_pillar(
*minion_ids,
grains=minion_grains,
cached_pillar=cached_minion_pillars)
return minion_pillars
def get_minion_grains(self):
'''
Get grains data for the targeted minions, either by fetching the
cached minion data on the master, or by fetching the grains
directly on the minion.
By default, this function tries hard to get the grains data:
- Try to get the cached minion grains if the master
has minion_data_cache: True
- If the grains data for the minion is cached, use it.
- If there is no cached grains data for a minion,
then try to get the minion grains directly from the minion.
'''
minion_grains = {}
minion_ids = self._tgt_to_list()
if not minion_ids:
return {}
if any(arg for arg in [self.use_cached_grains, self.grains_fallback]):
log.debug('Getting cached minion data.')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
return minion_grains
def get_cached_mine_data(self):
'''
Get cached mine data for the targeted minions.
'''
mine_data = {}
minion_ids = self._tgt_to_list()
log.debug('Getting cached mine data for: %s', minion_ids)
mine_data = self._get_cached_mine_data(*minion_ids)
return mine_data
def clear_cached_minion_data(self,
clear_pillar=False,
clear_grains=False,
clear_mine=False,
clear_mine_func=None):
'''
Clear the cached data/files for the targeted minions.
'''
clear_what = []
if clear_pillar:
clear_what.append('pillar')
if clear_grains:
clear_what.append('grains')
if clear_mine:
clear_what.append('mine')
if clear_mine_func is not None:
clear_what.append('mine_func: \'{0}\''.format(clear_mine_func))
if not clear_what:
log.debug('No cached data types specified for clearing.')
return False
minion_ids = self._tgt_to_list()
log.debug('Clearing cached %s data for: %s',
', '.join(clear_what),
minion_ids)
if clear_pillar == clear_grains:
# clear_pillar and clear_grains are both True or both False.
# This means we don't deal with pillar/grains caches at all.
grains = {}
pillars = {}
else:
# Unless both clear_pillar and clear_grains are True, we need
# to read in the pillar/grains data since they are both stored
# in the same file, 'data.p'
grains, pillars = self._get_cached_minion_data(*minion_ids)
try:
c_minions = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
if minion_id not in c_minions:
# Cache bank for this minion does not exist. Nothing to do.
continue
bank = 'minions/{0}'.format(minion_id)
minion_pillar = pillars.pop(minion_id, False)
minion_grains = grains.pop(minion_id, False)
if ((clear_pillar and clear_grains) or
(clear_pillar and not minion_grains) or
(clear_grains and not minion_pillar)):
# Not saving pillar or grains, so just delete the cache file
self.cache.flush(bank, 'data')
elif clear_pillar and minion_grains:
self.cache.store(bank, 'data', {'grains': minion_grains})
elif clear_grains and minion_pillar:
self.cache.store(bank, 'data', {'pillar': minion_pillar})
if clear_mine:
# Delete the whole mine file
self.cache.flush(bank, 'mine')
elif clear_mine_func is not None:
# Delete a specific function from the mine file
mine_data = self.cache.fetch(bank, 'mine')
if isinstance(mine_data, dict):
if mine_data.pop(clear_mine_func, False):
self.cache.store(bank, 'mine', mine_data)
except (OSError, IOError):
return True
return True
class CacheTimer(Thread):
'''
A basic timer class the fires timer-events every second.
This is used for cleanup by the ConnectedCache()
'''
def __init__(self, opts, event):
Thread.__init__(self)
self.opts = opts
self.stopped = event
self.daemon = True
self.serial = salt.payload.Serial(opts.get('serial', ''))
self.timer_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
def run(self):
'''
main loop that fires the event every second
'''
context = zmq.Context()
# the socket for outgoing timer events
socket = context.socket(zmq.PUB)
socket.setsockopt(zmq.LINGER, 100)
socket.bind('ipc://' + self.timer_sock)
count = 0
log.debug('ConCache-Timer started')
while not self.stopped.wait(1):
socket.send(self.serial.dumps(count))
count += 1
if count >= 60:
count = 0
class CacheWorker(MultiprocessingProcess):
'''
Worker for ConnectedCache which runs in its
own process to prevent blocking of ConnectedCache
main-loop when refreshing minion-list
'''
def __init__(self, opts, **kwargs):
'''
Sets up the zmq-connection to the ConCache
'''
super(CacheWorker, self).__init__(**kwargs)
self.opts = opts
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def run(self):
'''
Gather currently connected minions and update the cache
'''
new_mins = list(salt.utils.minions.CkMinions(self.opts).connected_ids())
cc = cache_cli(self.opts)
cc.get_cached()
cc.put_cache([new_mins])
log.debug('ConCache CacheWorker update finished')
class ConnectedCache(MultiprocessingProcess):
'''
Provides access to all minions ids that the master has
successfully authenticated. The cache is cleaned up regularly by
comparing it to the IPs that have open connections to
the master publisher port.
'''
def __init__(self, opts, **kwargs):
'''
starts the timer and inits the cache itself
'''
super(ConnectedCache, self).__init__(**kwargs)
log.debug('ConCache initializing...')
# the possible settings for the cache
self.opts = opts
# the actual cached minion ids
self.minions = []
self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc')
self.update_sock = os.path.join(self.opts['sock_dir'], 'con_upd.ipc')
self.upd_t_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
self.cleanup()
# the timer provides 1-second intervals to the loop in run()
# to make the cache system most responsive, we do not use a loop-
# delay which makes it hard to get 1-second intervals without a timer
self.timer_stop = Event()
self.timer = CacheTimer(self.opts, self.timer_stop)
self.timer.start()
self.running = True
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def signal_handler(self, sig, frame):
'''
handle signals and shutdown
'''
self.stop()
def cleanup(self):
'''
remove sockets on shutdown
'''
log.debug('ConCache cleaning up')
if os.path.exists(self.cache_sock):
os.remove(self.cache_sock)
if os.path.exists(self.update_sock):
os.remove(self.update_sock)
if os.path.exists(self.upd_t_sock):
os.remove(self.upd_t_sock)
def secure(self):
'''
secure the sockets for root-only access
'''
log.debug('ConCache securing sockets')
if os.path.exists(self.cache_sock):
os.chmod(self.cache_sock, 0o600)
if os.path.exists(self.update_sock):
os.chmod(self.update_sock, 0o600)
if os.path.exists(self.upd_t_sock):
os.chmod(self.upd_t_sock, 0o600)
def stop(self):
'''
shutdown cache process
'''
# avoid getting called twice
self.cleanup()
if self.running:
self.running = False
self.timer_stop.set()
self.timer.join()
def run(self):
'''
Main loop of the ConCache, starts updates in intervals and
answers requests from the MWorkers
'''
context = zmq.Context()
# the socket for incoming cache requests
creq_in = context.socket(zmq.REP)
creq_in.setsockopt(zmq.LINGER, 100)
creq_in.bind('ipc://' + self.cache_sock)
# the socket for incoming cache-updates from workers
cupd_in = context.socket(zmq.SUB)
cupd_in.setsockopt(zmq.SUBSCRIBE, b'')
cupd_in.setsockopt(zmq.LINGER, 100)
cupd_in.bind('ipc://' + self.update_sock)
# the socket for the timer-event
timer_in = context.socket(zmq.SUB)
timer_in.setsockopt(zmq.SUBSCRIBE, b'')
timer_in.setsockopt(zmq.LINGER, 100)
timer_in.connect('ipc://' + self.upd_t_sock)
poller = zmq.Poller()
poller.register(creq_in, zmq.POLLIN)
poller.register(cupd_in, zmq.POLLIN)
poller.register(timer_in, zmq.POLLIN)
# our serializer
serial = salt.payload.Serial(self.opts.get('serial', ''))
# register a signal handler
signal.signal(signal.SIGINT, self.signal_handler)
# secure the sockets from the world
self.secure()
log.info('ConCache started')
while self.running:
# we check for new events with the poller
try:
socks = dict(poller.poll(1))
except KeyboardInterrupt:
self.stop()
except zmq.ZMQError as zmq_err:
log.error('ConCache ZeroMQ-Error occurred')
log.exception(zmq_err)
self.stop()
# check for next cache-request
if socks.get(creq_in) == zmq.POLLIN:
msg = serial.loads(creq_in.recv())
log.debug('ConCache Received request: %s', msg)
# requests to the minion list are send as str's
if isinstance(msg, six.string_types):
if msg == 'minions':
# Send reply back to client
reply = serial.dumps(self.minions)
creq_in.send(reply)
# check for next cache-update from workers
if socks.get(cupd_in) == zmq.POLLIN:
new_c_data = serial.loads(cupd_in.recv())
# tell the worker to exit
#cupd_in.send(serial.dumps('ACK'))
# check if the returned data is usable
if not isinstance(new_c_data, list):
log.error('ConCache Worker returned unusable result')
del new_c_data
continue
# the cache will receive lists of minions
# 1. if the list only has 1 item, its from an MWorker, we append it
# 2. if the list contains another list, its from a CacheWorker and
# the currently cached minions are replaced with that list
# 3. anything else is considered malformed
try:
if not new_c_data:
log.debug('ConCache Got empty update from worker')
continue
data = new_c_data[0]
if isinstance(data, six.string_types):
if data not in self.minions:
log.debug('ConCache Adding minion %s to cache',
new_c_data[0])
self.minions.append(data)
elif isinstance(data, list):
log.debug('ConCache Replacing minion list from worker')
self.minions = data
except IndexError:
log.debug('ConCache Got malformed result dict from worker')
del new_c_data
log.info('ConCache %s entries in cache', len(self.minions))
# check for next timer-event to start new jobs
if socks.get(timer_in) == zmq.POLLIN:
sec_event = serial.loads(timer_in.recv())
# update the list every 30 seconds
if int(sec_event % 30) == 0:
cw = CacheWorker(self.opts)
cw.start()
self.stop()
creq_in.close()
cupd_in.close()
timer_in.close()
context.term()
log.debug('ConCache Shutting down')
def ping_all_connected_minions(opts):
client = salt.client.LocalClient()
if opts['minion_data_cache']:
tgt = list(salt.utils.minions.CkMinions(opts).connected_ids())
form = 'list'
else:
tgt = '*'
form = 'glob'
client.cmd_async(tgt, 'test.ping', tgt_type=form)
def get_master_key(key_user, opts, skip_perm_errors=False):
if key_user == 'root':
if opts.get('user', 'root') != 'root':
key_user = opts.get('user', 'root')
if key_user.startswith('sudo_'):
key_user = opts.get('user', 'root')
if salt.utils.platform.is_windows():
# The username may contain '\' if it is in Windows
# 'DOMAIN\username' format. Fix this for the keyfile path.
key_user = key_user.replace('\\', '_')
keyfile = os.path.join(opts['cachedir'],
'.{0}_key'.format(key_user))
# Make sure all key parent directories are accessible
salt.utils.verify.check_path_traversal(opts['cachedir'],
key_user,
skip_perm_errors)
try:
with salt.utils.files.fopen(keyfile, 'r') as key:
return key.read()
except (OSError, IOError):
# Fall back to eauth
return ''
def get_values_of_matching_keys(pattern_dict, user_name):
'''
Check a whitelist and/or blacklist to see if the value matches it.
'''
ret = []
for expr in pattern_dict:
if salt.utils.stringutils.expr_match(user_name, expr):
ret.extend(pattern_dict[expr])
return ret
# test code for the ConCache class
if __name__ == '__main__':
opts = salt.config.master_config('/etc/salt/master')
conc = ConnectedCache(opts)
conc.start()
|
saltstack/salt
|
salt/utils/master.py
|
get_values_of_matching_keys
|
python
|
def get_values_of_matching_keys(pattern_dict, user_name):
'''
Check a whitelist and/or blacklist to see if the value matches it.
'''
ret = []
for expr in pattern_dict:
if salt.utils.stringutils.expr_match(user_name, expr):
ret.extend(pattern_dict[expr])
return ret
|
Check a whitelist and/or blacklist to see if the value matches it.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L806-L814
|
[
"def expr_match(line, expr):\n '''\n Checks whether or not the passed value matches the specified expression.\n Tries to match expr first as a glob using fnmatch.fnmatch(), and then tries\n to match expr as a regular expression. Originally designed to match minion\n IDs for whitelists/blacklists.\n\n Note that this also does exact matches, as fnmatch.fnmatch() will return\n ``True`` when no glob characters are used and the string is an exact match:\n\n .. code-block:: python\n\n >>> fnmatch.fnmatch('foo', 'foo')\n True\n '''\n try:\n if fnmatch.fnmatch(line, expr):\n return True\n try:\n if re.match(r'\\A{0}\\Z'.format(expr), line):\n return True\n except re.error:\n pass\n except TypeError:\n log.exception('Value %r or expression %r is not a string', line, expr)\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
salt.utils.master
-----------------
Utilities that can only be used on a salt master.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import os
import logging
import signal
from threading import Thread, Event
# Import salt libs
import salt.log
import salt.cache
import salt.client
import salt.pillar
import salt.utils.atomicfile
import salt.utils.files
import salt.utils.minions
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.verify
import salt.payload
from salt.exceptions import SaltException
import salt.config
from salt.utils.cache import CacheCli as cache_cli
from salt.utils.process import MultiprocessingProcess
# pylint: disable=import-error
try:
import salt.utils.psutil_compat as psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
# Import third party libs
from salt.ext import six
from salt.utils.zeromq import zmq
log = logging.getLogger(__name__)
def get_running_jobs(opts):
'''
Return the running jobs on the master
'''
ret = []
proc_dir = os.path.join(opts['cachedir'], 'proc')
if not os.path.isdir(proc_dir):
return ret
for fn_ in os.listdir(proc_dir):
path = os.path.join(proc_dir, fn_)
data = read_proc_file(path, opts)
if not data:
continue
if not is_pid_healthy(data['pid']):
continue
ret.append(data)
return ret
def read_proc_file(path, opts):
'''
Return a dict of JID metadata, or None
'''
serial = salt.payload.Serial(opts)
with salt.utils.files.fopen(path, 'rb') as fp_:
try:
data = serial.load(fp_)
except Exception as err:
# need to add serial exception here
# Could not read proc file
log.warning("Issue deserializing data: %s", err)
return None
if not isinstance(data, dict):
# Invalid serial object
log.warning("Data is not a dict: %s", data)
return None
pid = data.get('pid', None)
if not pid:
# No pid, not a salt proc file
log.warning("No PID found in data")
return None
return data
def is_pid_healthy(pid):
'''
This is a health check that will confirm the PID is running
and executed by salt.
If pusutil is available:
* all architectures are checked
if psutil is not available:
* Linux/Solaris/etc: archs with `/proc/cmdline` available are checked
* AIX/Windows: assume PID is healhty and return True
'''
if HAS_PSUTIL:
try:
proc = psutil.Process(pid)
except psutil.NoSuchProcess:
log.warning("PID %s is no longer running.", pid)
return False
return any(['salt' in cmd for cmd in proc.cmdline()])
if salt.utils.platform.is_aix() or salt.utils.platform.is_windows():
return True
if not salt.utils.process.os_is_running(pid):
log.warning("PID %s is no longer running.", pid)
return False
cmdline_file = os.path.join('proc', str(pid), 'cmdline')
try:
with salt.utils.files.fopen(cmdline_file, 'rb') as fp_:
return b'salt' in fp_.read()
except (OSError, IOError) as err:
log.error("There was a problem reading proc file: %s", err)
return False
class MasterPillarUtil(object):
'''
Helper utility for easy access to targeted minion grain and
pillar data, either from cached data on the master or retrieved
on demand, or (by default) both.
The minion pillar data returned in get_minion_pillar() is
compiled directly from salt.pillar.Pillar on the master to
avoid any possible 'pillar poisoning' from a compromised or
untrusted minion.
** However, the minion grains are still possibly entirely
supplied by the minion. **
Example use case:
For runner modules that need access minion pillar data,
MasterPillarUtil.get_minion_pillar should be used instead
of getting the pillar data by executing the "pillar" module
on the minions:
# my_runner.py
tgt = 'web*'
pillar_util = salt.utils.master.MasterPillarUtil(tgt, tgt_type='glob', opts=__opts__)
pillar_data = pillar_util.get_minion_pillar()
'''
def __init__(self,
tgt='',
tgt_type='glob',
saltenv=None,
use_cached_grains=True,
use_cached_pillar=True,
grains_fallback=True,
pillar_fallback=True,
opts=None):
log.debug('New instance of %s created.',
self.__class__.__name__)
if opts is None:
log.error('%s: Missing master opts init arg.',
self.__class__.__name__)
raise SaltException('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
else:
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.tgt = tgt
self.tgt_type = tgt_type
self.saltenv = saltenv
self.use_cached_grains = use_cached_grains
self.use_cached_pillar = use_cached_pillar
self.grains_fallback = grains_fallback
self.pillar_fallback = pillar_fallback
self.cache = salt.cache.factory(opts)
log.debug(
'Init settings: tgt: \'%s\', tgt_type: \'%s\', saltenv: \'%s\', '
'use_cached_grains: %s, use_cached_pillar: %s, '
'grains_fallback: %s, pillar_fallback: %s',
tgt, tgt_type, saltenv, use_cached_grains, use_cached_pillar,
grains_fallback, pillar_fallback
)
def _get_cached_mine_data(self, *minion_ids):
# Return one dict with the cached mine data of the targeted minions
mine_data = dict([(minion_id, {}) for minion_id in minion_ids])
if (not self.opts.get('minion_data_cache', False)
and not self.opts.get('enforce_mine_cache', False)):
log.debug('Skipping cached mine data minion_data_cache'
'and enfore_mine_cache are both disabled.')
return mine_data
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'mine')
if isinstance(mdata, dict):
mine_data[minion_id] = mdata
return mine_data
def _get_cached_minion_data(self, *minion_ids):
# Return two separate dicts of cached grains and pillar data of the
# minions
grains = dict([(minion_id, {}) for minion_id in minion_ids])
pillars = grains.copy()
if not self.opts.get('minion_data_cache', False):
log.debug('Skipping cached data because minion_data_cache is not '
'enabled.')
return grains, pillars
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'data')
if not isinstance(mdata, dict):
log.warning(
'cache.fetch should always return a dict. ReturnedType: %s, MinionId: %s',
type(mdata).__name__,
minion_id
)
continue
if 'grains' in mdata:
grains[minion_id] = mdata['grains']
if 'pillar' in mdata:
pillars[minion_id] = mdata['pillar']
return grains, pillars
def _get_live_minion_grains(self, minion_ids):
# Returns a dict of grains fetched directly from the minions
log.debug('Getting live grains for minions: "%s"', minion_ids)
client = salt.client.get_local_client(self.opts['conf_file'])
ret = client.cmd(
','.join(minion_ids),
'grains.items',
timeout=self.opts['timeout'],
tgt_type='list')
return ret
def _get_live_minion_pillar(self, minion_id=None, minion_grains=None):
# Returns a dict of pillar data for one minion
if minion_id is None:
return {}
if not minion_grains:
log.warning(
'Cannot get pillar data for %s: no grains supplied.',
minion_id
)
return {}
log.debug('Getting live pillar for %s', minion_id)
pillar = salt.pillar.Pillar(
self.opts,
minion_grains,
minion_id,
self.saltenv,
self.opts['ext_pillar'])
log.debug('Compiling pillar for %s', minion_id)
ret = pillar.compile_pillar()
return ret
def _get_minion_grains(self, *minion_ids, **kwargs):
# Get the minion grains either from cache or from a direct query
# on the minion. By default try to use cached grains first, then
# fall back to querying the minion directly.
ret = {}
cached_grains = kwargs.get('cached_grains', {})
cret = {}
lret = {}
if self.use_cached_grains:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
lret = self._get_live_minion_grains(missed_minions)
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = self._get_live_minion_grains(minion_ids)
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _get_minion_pillar(self, *minion_ids, **kwargs):
# Get the minion pillar either from cache or from a direct query
# on the minion. By default try use the cached pillar first, then
# fall back to rendering pillar on demand with the supplied grains.
ret = {}
grains = kwargs.get('grains', {})
cached_pillar = kwargs.get('cached_pillar', {})
cret = {}
lret = {}
if self.use_cached_pillar:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in missed_minions])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in minion_ids])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _tgt_to_list(self):
# Return a list of minion ids that match the target and tgt_type
minion_ids = []
ckminions = salt.utils.minions.CkMinions(self.opts)
_res = ckminions.check_minions(self.tgt, self.tgt_type)
minion_ids = _res['minions']
if not minion_ids:
log.debug('No minions matched for tgt="%s" and tgt_type="%s"', self.tgt, self.tgt_type)
return {}
log.debug('Matching minions for tgt="%s" and tgt_type="%s": %s', self.tgt, self.tgt_type, minion_ids)
return minion_ids
def get_minion_pillar(self):
'''
Get pillar data for the targeted minions, either by fetching the
cached minion data on the master, or by compiling the minion's
pillar data on the master.
For runner modules that need access minion pillar data, this
function should be used instead of getting the pillar data by
executing the pillar module on the minions.
By default, this function tries hard to get the pillar data:
- Try to get the cached minion grains and pillar if the
master has minion_data_cache: True
- If the pillar data for the minion is cached, use it.
- If there is no cached grains/pillar data for a minion,
then try to get the minion grains directly from the minion.
- Use the minion grains to compile the pillar directly from the
master using salt.pillar.Pillar
'''
minion_pillars = {}
minion_grains = {}
minion_ids = self._tgt_to_list()
if any(arg for arg in [self.use_cached_grains, self.use_cached_pillar, self.grains_fallback, self.pillar_fallback]):
log.debug('Getting cached minion data')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
cached_minion_pillars = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
log.debug('Getting minion pillar data for: %s', minion_ids)
minion_pillars = self._get_minion_pillar(
*minion_ids,
grains=minion_grains,
cached_pillar=cached_minion_pillars)
return minion_pillars
def get_minion_grains(self):
'''
Get grains data for the targeted minions, either by fetching the
cached minion data on the master, or by fetching the grains
directly on the minion.
By default, this function tries hard to get the grains data:
- Try to get the cached minion grains if the master
has minion_data_cache: True
- If the grains data for the minion is cached, use it.
- If there is no cached grains data for a minion,
then try to get the minion grains directly from the minion.
'''
minion_grains = {}
minion_ids = self._tgt_to_list()
if not minion_ids:
return {}
if any(arg for arg in [self.use_cached_grains, self.grains_fallback]):
log.debug('Getting cached minion data.')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
return minion_grains
def get_cached_mine_data(self):
'''
Get cached mine data for the targeted minions.
'''
mine_data = {}
minion_ids = self._tgt_to_list()
log.debug('Getting cached mine data for: %s', minion_ids)
mine_data = self._get_cached_mine_data(*minion_ids)
return mine_data
def clear_cached_minion_data(self,
clear_pillar=False,
clear_grains=False,
clear_mine=False,
clear_mine_func=None):
'''
Clear the cached data/files for the targeted minions.
'''
clear_what = []
if clear_pillar:
clear_what.append('pillar')
if clear_grains:
clear_what.append('grains')
if clear_mine:
clear_what.append('mine')
if clear_mine_func is not None:
clear_what.append('mine_func: \'{0}\''.format(clear_mine_func))
if not clear_what:
log.debug('No cached data types specified for clearing.')
return False
minion_ids = self._tgt_to_list()
log.debug('Clearing cached %s data for: %s',
', '.join(clear_what),
minion_ids)
if clear_pillar == clear_grains:
# clear_pillar and clear_grains are both True or both False.
# This means we don't deal with pillar/grains caches at all.
grains = {}
pillars = {}
else:
# Unless both clear_pillar and clear_grains are True, we need
# to read in the pillar/grains data since they are both stored
# in the same file, 'data.p'
grains, pillars = self._get_cached_minion_data(*minion_ids)
try:
c_minions = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
if minion_id not in c_minions:
# Cache bank for this minion does not exist. Nothing to do.
continue
bank = 'minions/{0}'.format(minion_id)
minion_pillar = pillars.pop(minion_id, False)
minion_grains = grains.pop(minion_id, False)
if ((clear_pillar and clear_grains) or
(clear_pillar and not minion_grains) or
(clear_grains and not minion_pillar)):
# Not saving pillar or grains, so just delete the cache file
self.cache.flush(bank, 'data')
elif clear_pillar and minion_grains:
self.cache.store(bank, 'data', {'grains': minion_grains})
elif clear_grains and minion_pillar:
self.cache.store(bank, 'data', {'pillar': minion_pillar})
if clear_mine:
# Delete the whole mine file
self.cache.flush(bank, 'mine')
elif clear_mine_func is not None:
# Delete a specific function from the mine file
mine_data = self.cache.fetch(bank, 'mine')
if isinstance(mine_data, dict):
if mine_data.pop(clear_mine_func, False):
self.cache.store(bank, 'mine', mine_data)
except (OSError, IOError):
return True
return True
class CacheTimer(Thread):
'''
A basic timer class the fires timer-events every second.
This is used for cleanup by the ConnectedCache()
'''
def __init__(self, opts, event):
Thread.__init__(self)
self.opts = opts
self.stopped = event
self.daemon = True
self.serial = salt.payload.Serial(opts.get('serial', ''))
self.timer_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
def run(self):
'''
main loop that fires the event every second
'''
context = zmq.Context()
# the socket for outgoing timer events
socket = context.socket(zmq.PUB)
socket.setsockopt(zmq.LINGER, 100)
socket.bind('ipc://' + self.timer_sock)
count = 0
log.debug('ConCache-Timer started')
while not self.stopped.wait(1):
socket.send(self.serial.dumps(count))
count += 1
if count >= 60:
count = 0
class CacheWorker(MultiprocessingProcess):
'''
Worker for ConnectedCache which runs in its
own process to prevent blocking of ConnectedCache
main-loop when refreshing minion-list
'''
def __init__(self, opts, **kwargs):
'''
Sets up the zmq-connection to the ConCache
'''
super(CacheWorker, self).__init__(**kwargs)
self.opts = opts
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def run(self):
'''
Gather currently connected minions and update the cache
'''
new_mins = list(salt.utils.minions.CkMinions(self.opts).connected_ids())
cc = cache_cli(self.opts)
cc.get_cached()
cc.put_cache([new_mins])
log.debug('ConCache CacheWorker update finished')
class ConnectedCache(MultiprocessingProcess):
'''
Provides access to all minions ids that the master has
successfully authenticated. The cache is cleaned up regularly by
comparing it to the IPs that have open connections to
the master publisher port.
'''
def __init__(self, opts, **kwargs):
'''
starts the timer and inits the cache itself
'''
super(ConnectedCache, self).__init__(**kwargs)
log.debug('ConCache initializing...')
# the possible settings for the cache
self.opts = opts
# the actual cached minion ids
self.minions = []
self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc')
self.update_sock = os.path.join(self.opts['sock_dir'], 'con_upd.ipc')
self.upd_t_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
self.cleanup()
# the timer provides 1-second intervals to the loop in run()
# to make the cache system most responsive, we do not use a loop-
# delay which makes it hard to get 1-second intervals without a timer
self.timer_stop = Event()
self.timer = CacheTimer(self.opts, self.timer_stop)
self.timer.start()
self.running = True
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def signal_handler(self, sig, frame):
'''
handle signals and shutdown
'''
self.stop()
def cleanup(self):
'''
remove sockets on shutdown
'''
log.debug('ConCache cleaning up')
if os.path.exists(self.cache_sock):
os.remove(self.cache_sock)
if os.path.exists(self.update_sock):
os.remove(self.update_sock)
if os.path.exists(self.upd_t_sock):
os.remove(self.upd_t_sock)
def secure(self):
'''
secure the sockets for root-only access
'''
log.debug('ConCache securing sockets')
if os.path.exists(self.cache_sock):
os.chmod(self.cache_sock, 0o600)
if os.path.exists(self.update_sock):
os.chmod(self.update_sock, 0o600)
if os.path.exists(self.upd_t_sock):
os.chmod(self.upd_t_sock, 0o600)
def stop(self):
'''
shutdown cache process
'''
# avoid getting called twice
self.cleanup()
if self.running:
self.running = False
self.timer_stop.set()
self.timer.join()
def run(self):
'''
Main loop of the ConCache, starts updates in intervals and
answers requests from the MWorkers
'''
context = zmq.Context()
# the socket for incoming cache requests
creq_in = context.socket(zmq.REP)
creq_in.setsockopt(zmq.LINGER, 100)
creq_in.bind('ipc://' + self.cache_sock)
# the socket for incoming cache-updates from workers
cupd_in = context.socket(zmq.SUB)
cupd_in.setsockopt(zmq.SUBSCRIBE, b'')
cupd_in.setsockopt(zmq.LINGER, 100)
cupd_in.bind('ipc://' + self.update_sock)
# the socket for the timer-event
timer_in = context.socket(zmq.SUB)
timer_in.setsockopt(zmq.SUBSCRIBE, b'')
timer_in.setsockopt(zmq.LINGER, 100)
timer_in.connect('ipc://' + self.upd_t_sock)
poller = zmq.Poller()
poller.register(creq_in, zmq.POLLIN)
poller.register(cupd_in, zmq.POLLIN)
poller.register(timer_in, zmq.POLLIN)
# our serializer
serial = salt.payload.Serial(self.opts.get('serial', ''))
# register a signal handler
signal.signal(signal.SIGINT, self.signal_handler)
# secure the sockets from the world
self.secure()
log.info('ConCache started')
while self.running:
# we check for new events with the poller
try:
socks = dict(poller.poll(1))
except KeyboardInterrupt:
self.stop()
except zmq.ZMQError as zmq_err:
log.error('ConCache ZeroMQ-Error occurred')
log.exception(zmq_err)
self.stop()
# check for next cache-request
if socks.get(creq_in) == zmq.POLLIN:
msg = serial.loads(creq_in.recv())
log.debug('ConCache Received request: %s', msg)
# requests to the minion list are send as str's
if isinstance(msg, six.string_types):
if msg == 'minions':
# Send reply back to client
reply = serial.dumps(self.minions)
creq_in.send(reply)
# check for next cache-update from workers
if socks.get(cupd_in) == zmq.POLLIN:
new_c_data = serial.loads(cupd_in.recv())
# tell the worker to exit
#cupd_in.send(serial.dumps('ACK'))
# check if the returned data is usable
if not isinstance(new_c_data, list):
log.error('ConCache Worker returned unusable result')
del new_c_data
continue
# the cache will receive lists of minions
# 1. if the list only has 1 item, its from an MWorker, we append it
# 2. if the list contains another list, its from a CacheWorker and
# the currently cached minions are replaced with that list
# 3. anything else is considered malformed
try:
if not new_c_data:
log.debug('ConCache Got empty update from worker')
continue
data = new_c_data[0]
if isinstance(data, six.string_types):
if data not in self.minions:
log.debug('ConCache Adding minion %s to cache',
new_c_data[0])
self.minions.append(data)
elif isinstance(data, list):
log.debug('ConCache Replacing minion list from worker')
self.minions = data
except IndexError:
log.debug('ConCache Got malformed result dict from worker')
del new_c_data
log.info('ConCache %s entries in cache', len(self.minions))
# check for next timer-event to start new jobs
if socks.get(timer_in) == zmq.POLLIN:
sec_event = serial.loads(timer_in.recv())
# update the list every 30 seconds
if int(sec_event % 30) == 0:
cw = CacheWorker(self.opts)
cw.start()
self.stop()
creq_in.close()
cupd_in.close()
timer_in.close()
context.term()
log.debug('ConCache Shutting down')
def ping_all_connected_minions(opts):
client = salt.client.LocalClient()
if opts['minion_data_cache']:
tgt = list(salt.utils.minions.CkMinions(opts).connected_ids())
form = 'list'
else:
tgt = '*'
form = 'glob'
client.cmd_async(tgt, 'test.ping', tgt_type=form)
def get_master_key(key_user, opts, skip_perm_errors=False):
if key_user == 'root':
if opts.get('user', 'root') != 'root':
key_user = opts.get('user', 'root')
if key_user.startswith('sudo_'):
key_user = opts.get('user', 'root')
if salt.utils.platform.is_windows():
# The username may contain '\' if it is in Windows
# 'DOMAIN\username' format. Fix this for the keyfile path.
key_user = key_user.replace('\\', '_')
keyfile = os.path.join(opts['cachedir'],
'.{0}_key'.format(key_user))
# Make sure all key parent directories are accessible
salt.utils.verify.check_path_traversal(opts['cachedir'],
key_user,
skip_perm_errors)
try:
with salt.utils.files.fopen(keyfile, 'r') as key:
return key.read()
except (OSError, IOError):
# Fall back to eauth
return ''
# test code for the ConCache class
if __name__ == '__main__':
opts = salt.config.master_config('/etc/salt/master')
conc = ConnectedCache(opts)
conc.start()
|
saltstack/salt
|
salt/utils/master.py
|
MasterPillarUtil.get_minion_pillar
|
python
|
def get_minion_pillar(self):
'''
Get pillar data for the targeted minions, either by fetching the
cached minion data on the master, or by compiling the minion's
pillar data on the master.
For runner modules that need access minion pillar data, this
function should be used instead of getting the pillar data by
executing the pillar module on the minions.
By default, this function tries hard to get the pillar data:
- Try to get the cached minion grains and pillar if the
master has minion_data_cache: True
- If the pillar data for the minion is cached, use it.
- If there is no cached grains/pillar data for a minion,
then try to get the minion grains directly from the minion.
- Use the minion grains to compile the pillar directly from the
master using salt.pillar.Pillar
'''
minion_pillars = {}
minion_grains = {}
minion_ids = self._tgt_to_list()
if any(arg for arg in [self.use_cached_grains, self.use_cached_pillar, self.grains_fallback, self.pillar_fallback]):
log.debug('Getting cached minion data')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
cached_minion_pillars = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
log.debug('Getting minion pillar data for: %s', minion_ids)
minion_pillars = self._get_minion_pillar(
*minion_ids,
grains=minion_grains,
cached_pillar=cached_minion_pillars)
return minion_pillars
|
Get pillar data for the targeted minions, either by fetching the
cached minion data on the master, or by compiling the minion's
pillar data on the master.
For runner modules that need access minion pillar data, this
function should be used instead of getting the pillar data by
executing the pillar module on the minions.
By default, this function tries hard to get the pillar data:
- Try to get the cached minion grains and pillar if the
master has minion_data_cache: True
- If the pillar data for the minion is cached, use it.
- If there is no cached grains/pillar data for a minion,
then try to get the minion grains directly from the minion.
- Use the minion grains to compile the pillar directly from the
master using salt.pillar.Pillar
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L332-L369
|
[
"def _tgt_to_list(self):\n # Return a list of minion ids that match the target and tgt_type\n minion_ids = []\n ckminions = salt.utils.minions.CkMinions(self.opts)\n _res = ckminions.check_minions(self.tgt, self.tgt_type)\n minion_ids = _res['minions']\n if not minion_ids:\n log.debug('No minions matched for tgt=\"%s\" and tgt_type=\"%s\"', self.tgt, self.tgt_type)\n return {}\n log.debug('Matching minions for tgt=\"%s\" and tgt_type=\"%s\": %s', self.tgt, self.tgt_type, minion_ids)\n return minion_ids\n"
] |
class MasterPillarUtil(object):
'''
Helper utility for easy access to targeted minion grain and
pillar data, either from cached data on the master or retrieved
on demand, or (by default) both.
The minion pillar data returned in get_minion_pillar() is
compiled directly from salt.pillar.Pillar on the master to
avoid any possible 'pillar poisoning' from a compromised or
untrusted minion.
** However, the minion grains are still possibly entirely
supplied by the minion. **
Example use case:
For runner modules that need access minion pillar data,
MasterPillarUtil.get_minion_pillar should be used instead
of getting the pillar data by executing the "pillar" module
on the minions:
# my_runner.py
tgt = 'web*'
pillar_util = salt.utils.master.MasterPillarUtil(tgt, tgt_type='glob', opts=__opts__)
pillar_data = pillar_util.get_minion_pillar()
'''
def __init__(self,
tgt='',
tgt_type='glob',
saltenv=None,
use_cached_grains=True,
use_cached_pillar=True,
grains_fallback=True,
pillar_fallback=True,
opts=None):
log.debug('New instance of %s created.',
self.__class__.__name__)
if opts is None:
log.error('%s: Missing master opts init arg.',
self.__class__.__name__)
raise SaltException('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
else:
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.tgt = tgt
self.tgt_type = tgt_type
self.saltenv = saltenv
self.use_cached_grains = use_cached_grains
self.use_cached_pillar = use_cached_pillar
self.grains_fallback = grains_fallback
self.pillar_fallback = pillar_fallback
self.cache = salt.cache.factory(opts)
log.debug(
'Init settings: tgt: \'%s\', tgt_type: \'%s\', saltenv: \'%s\', '
'use_cached_grains: %s, use_cached_pillar: %s, '
'grains_fallback: %s, pillar_fallback: %s',
tgt, tgt_type, saltenv, use_cached_grains, use_cached_pillar,
grains_fallback, pillar_fallback
)
def _get_cached_mine_data(self, *minion_ids):
# Return one dict with the cached mine data of the targeted minions
mine_data = dict([(minion_id, {}) for minion_id in minion_ids])
if (not self.opts.get('minion_data_cache', False)
and not self.opts.get('enforce_mine_cache', False)):
log.debug('Skipping cached mine data minion_data_cache'
'and enfore_mine_cache are both disabled.')
return mine_data
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'mine')
if isinstance(mdata, dict):
mine_data[minion_id] = mdata
return mine_data
def _get_cached_minion_data(self, *minion_ids):
# Return two separate dicts of cached grains and pillar data of the
# minions
grains = dict([(minion_id, {}) for minion_id in minion_ids])
pillars = grains.copy()
if not self.opts.get('minion_data_cache', False):
log.debug('Skipping cached data because minion_data_cache is not '
'enabled.')
return grains, pillars
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'data')
if not isinstance(mdata, dict):
log.warning(
'cache.fetch should always return a dict. ReturnedType: %s, MinionId: %s',
type(mdata).__name__,
minion_id
)
continue
if 'grains' in mdata:
grains[minion_id] = mdata['grains']
if 'pillar' in mdata:
pillars[minion_id] = mdata['pillar']
return grains, pillars
def _get_live_minion_grains(self, minion_ids):
# Returns a dict of grains fetched directly from the minions
log.debug('Getting live grains for minions: "%s"', minion_ids)
client = salt.client.get_local_client(self.opts['conf_file'])
ret = client.cmd(
','.join(minion_ids),
'grains.items',
timeout=self.opts['timeout'],
tgt_type='list')
return ret
def _get_live_minion_pillar(self, minion_id=None, minion_grains=None):
# Returns a dict of pillar data for one minion
if minion_id is None:
return {}
if not minion_grains:
log.warning(
'Cannot get pillar data for %s: no grains supplied.',
minion_id
)
return {}
log.debug('Getting live pillar for %s', minion_id)
pillar = salt.pillar.Pillar(
self.opts,
minion_grains,
minion_id,
self.saltenv,
self.opts['ext_pillar'])
log.debug('Compiling pillar for %s', minion_id)
ret = pillar.compile_pillar()
return ret
def _get_minion_grains(self, *minion_ids, **kwargs):
# Get the minion grains either from cache or from a direct query
# on the minion. By default try to use cached grains first, then
# fall back to querying the minion directly.
ret = {}
cached_grains = kwargs.get('cached_grains', {})
cret = {}
lret = {}
if self.use_cached_grains:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
lret = self._get_live_minion_grains(missed_minions)
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = self._get_live_minion_grains(minion_ids)
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _get_minion_pillar(self, *minion_ids, **kwargs):
# Get the minion pillar either from cache or from a direct query
# on the minion. By default try use the cached pillar first, then
# fall back to rendering pillar on demand with the supplied grains.
ret = {}
grains = kwargs.get('grains', {})
cached_pillar = kwargs.get('cached_pillar', {})
cret = {}
lret = {}
if self.use_cached_pillar:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in missed_minions])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in minion_ids])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _tgt_to_list(self):
# Return a list of minion ids that match the target and tgt_type
minion_ids = []
ckminions = salt.utils.minions.CkMinions(self.opts)
_res = ckminions.check_minions(self.tgt, self.tgt_type)
minion_ids = _res['minions']
if not minion_ids:
log.debug('No minions matched for tgt="%s" and tgt_type="%s"', self.tgt, self.tgt_type)
return {}
log.debug('Matching minions for tgt="%s" and tgt_type="%s": %s', self.tgt, self.tgt_type, minion_ids)
return minion_ids
def get_minion_grains(self):
'''
Get grains data for the targeted minions, either by fetching the
cached minion data on the master, or by fetching the grains
directly on the minion.
By default, this function tries hard to get the grains data:
- Try to get the cached minion grains if the master
has minion_data_cache: True
- If the grains data for the minion is cached, use it.
- If there is no cached grains data for a minion,
then try to get the minion grains directly from the minion.
'''
minion_grains = {}
minion_ids = self._tgt_to_list()
if not minion_ids:
return {}
if any(arg for arg in [self.use_cached_grains, self.grains_fallback]):
log.debug('Getting cached minion data.')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
return minion_grains
def get_cached_mine_data(self):
'''
Get cached mine data for the targeted minions.
'''
mine_data = {}
minion_ids = self._tgt_to_list()
log.debug('Getting cached mine data for: %s', minion_ids)
mine_data = self._get_cached_mine_data(*minion_ids)
return mine_data
def clear_cached_minion_data(self,
clear_pillar=False,
clear_grains=False,
clear_mine=False,
clear_mine_func=None):
'''
Clear the cached data/files for the targeted minions.
'''
clear_what = []
if clear_pillar:
clear_what.append('pillar')
if clear_grains:
clear_what.append('grains')
if clear_mine:
clear_what.append('mine')
if clear_mine_func is not None:
clear_what.append('mine_func: \'{0}\''.format(clear_mine_func))
if not clear_what:
log.debug('No cached data types specified for clearing.')
return False
minion_ids = self._tgt_to_list()
log.debug('Clearing cached %s data for: %s',
', '.join(clear_what),
minion_ids)
if clear_pillar == clear_grains:
# clear_pillar and clear_grains are both True or both False.
# This means we don't deal with pillar/grains caches at all.
grains = {}
pillars = {}
else:
# Unless both clear_pillar and clear_grains are True, we need
# to read in the pillar/grains data since they are both stored
# in the same file, 'data.p'
grains, pillars = self._get_cached_minion_data(*minion_ids)
try:
c_minions = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
if minion_id not in c_minions:
# Cache bank for this minion does not exist. Nothing to do.
continue
bank = 'minions/{0}'.format(minion_id)
minion_pillar = pillars.pop(minion_id, False)
minion_grains = grains.pop(minion_id, False)
if ((clear_pillar and clear_grains) or
(clear_pillar and not minion_grains) or
(clear_grains and not minion_pillar)):
# Not saving pillar or grains, so just delete the cache file
self.cache.flush(bank, 'data')
elif clear_pillar and minion_grains:
self.cache.store(bank, 'data', {'grains': minion_grains})
elif clear_grains and minion_pillar:
self.cache.store(bank, 'data', {'pillar': minion_pillar})
if clear_mine:
# Delete the whole mine file
self.cache.flush(bank, 'mine')
elif clear_mine_func is not None:
# Delete a specific function from the mine file
mine_data = self.cache.fetch(bank, 'mine')
if isinstance(mine_data, dict):
if mine_data.pop(clear_mine_func, False):
self.cache.store(bank, 'mine', mine_data)
except (OSError, IOError):
return True
return True
|
saltstack/salt
|
salt/utils/master.py
|
MasterPillarUtil.get_minion_grains
|
python
|
def get_minion_grains(self):
'''
Get grains data for the targeted minions, either by fetching the
cached minion data on the master, or by fetching the grains
directly on the minion.
By default, this function tries hard to get the grains data:
- Try to get the cached minion grains if the master
has minion_data_cache: True
- If the grains data for the minion is cached, use it.
- If there is no cached grains data for a minion,
then try to get the minion grains directly from the minion.
'''
minion_grains = {}
minion_ids = self._tgt_to_list()
if not minion_ids:
return {}
if any(arg for arg in [self.use_cached_grains, self.grains_fallback]):
log.debug('Getting cached minion data.')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
return minion_grains
|
Get grains data for the targeted minions, either by fetching the
cached minion data on the master, or by fetching the grains
directly on the minion.
By default, this function tries hard to get the grains data:
- Try to get the cached minion grains if the master
has minion_data_cache: True
- If the grains data for the minion is cached, use it.
- If there is no cached grains data for a minion,
then try to get the minion grains directly from the minion.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L371-L397
|
[
"def _tgt_to_list(self):\n # Return a list of minion ids that match the target and tgt_type\n minion_ids = []\n ckminions = salt.utils.minions.CkMinions(self.opts)\n _res = ckminions.check_minions(self.tgt, self.tgt_type)\n minion_ids = _res['minions']\n if not minion_ids:\n log.debug('No minions matched for tgt=\"%s\" and tgt_type=\"%s\"', self.tgt, self.tgt_type)\n return {}\n log.debug('Matching minions for tgt=\"%s\" and tgt_type=\"%s\": %s', self.tgt, self.tgt_type, minion_ids)\n return minion_ids\n"
] |
class MasterPillarUtil(object):
'''
Helper utility for easy access to targeted minion grain and
pillar data, either from cached data on the master or retrieved
on demand, or (by default) both.
The minion pillar data returned in get_minion_pillar() is
compiled directly from salt.pillar.Pillar on the master to
avoid any possible 'pillar poisoning' from a compromised or
untrusted minion.
** However, the minion grains are still possibly entirely
supplied by the minion. **
Example use case:
For runner modules that need access minion pillar data,
MasterPillarUtil.get_minion_pillar should be used instead
of getting the pillar data by executing the "pillar" module
on the minions:
# my_runner.py
tgt = 'web*'
pillar_util = salt.utils.master.MasterPillarUtil(tgt, tgt_type='glob', opts=__opts__)
pillar_data = pillar_util.get_minion_pillar()
'''
def __init__(self,
tgt='',
tgt_type='glob',
saltenv=None,
use_cached_grains=True,
use_cached_pillar=True,
grains_fallback=True,
pillar_fallback=True,
opts=None):
log.debug('New instance of %s created.',
self.__class__.__name__)
if opts is None:
log.error('%s: Missing master opts init arg.',
self.__class__.__name__)
raise SaltException('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
else:
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.tgt = tgt
self.tgt_type = tgt_type
self.saltenv = saltenv
self.use_cached_grains = use_cached_grains
self.use_cached_pillar = use_cached_pillar
self.grains_fallback = grains_fallback
self.pillar_fallback = pillar_fallback
self.cache = salt.cache.factory(opts)
log.debug(
'Init settings: tgt: \'%s\', tgt_type: \'%s\', saltenv: \'%s\', '
'use_cached_grains: %s, use_cached_pillar: %s, '
'grains_fallback: %s, pillar_fallback: %s',
tgt, tgt_type, saltenv, use_cached_grains, use_cached_pillar,
grains_fallback, pillar_fallback
)
def _get_cached_mine_data(self, *minion_ids):
# Return one dict with the cached mine data of the targeted minions
mine_data = dict([(minion_id, {}) for minion_id in minion_ids])
if (not self.opts.get('minion_data_cache', False)
and not self.opts.get('enforce_mine_cache', False)):
log.debug('Skipping cached mine data minion_data_cache'
'and enfore_mine_cache are both disabled.')
return mine_data
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'mine')
if isinstance(mdata, dict):
mine_data[minion_id] = mdata
return mine_data
def _get_cached_minion_data(self, *minion_ids):
# Return two separate dicts of cached grains and pillar data of the
# minions
grains = dict([(minion_id, {}) for minion_id in minion_ids])
pillars = grains.copy()
if not self.opts.get('minion_data_cache', False):
log.debug('Skipping cached data because minion_data_cache is not '
'enabled.')
return grains, pillars
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'data')
if not isinstance(mdata, dict):
log.warning(
'cache.fetch should always return a dict. ReturnedType: %s, MinionId: %s',
type(mdata).__name__,
minion_id
)
continue
if 'grains' in mdata:
grains[minion_id] = mdata['grains']
if 'pillar' in mdata:
pillars[minion_id] = mdata['pillar']
return grains, pillars
def _get_live_minion_grains(self, minion_ids):
# Returns a dict of grains fetched directly from the minions
log.debug('Getting live grains for minions: "%s"', minion_ids)
client = salt.client.get_local_client(self.opts['conf_file'])
ret = client.cmd(
','.join(minion_ids),
'grains.items',
timeout=self.opts['timeout'],
tgt_type='list')
return ret
def _get_live_minion_pillar(self, minion_id=None, minion_grains=None):
# Returns a dict of pillar data for one minion
if minion_id is None:
return {}
if not minion_grains:
log.warning(
'Cannot get pillar data for %s: no grains supplied.',
minion_id
)
return {}
log.debug('Getting live pillar for %s', minion_id)
pillar = salt.pillar.Pillar(
self.opts,
minion_grains,
minion_id,
self.saltenv,
self.opts['ext_pillar'])
log.debug('Compiling pillar for %s', minion_id)
ret = pillar.compile_pillar()
return ret
def _get_minion_grains(self, *minion_ids, **kwargs):
# Get the minion grains either from cache or from a direct query
# on the minion. By default try to use cached grains first, then
# fall back to querying the minion directly.
ret = {}
cached_grains = kwargs.get('cached_grains', {})
cret = {}
lret = {}
if self.use_cached_grains:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
lret = self._get_live_minion_grains(missed_minions)
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = self._get_live_minion_grains(minion_ids)
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _get_minion_pillar(self, *minion_ids, **kwargs):
# Get the minion pillar either from cache or from a direct query
# on the minion. By default try use the cached pillar first, then
# fall back to rendering pillar on demand with the supplied grains.
ret = {}
grains = kwargs.get('grains', {})
cached_pillar = kwargs.get('cached_pillar', {})
cret = {}
lret = {}
if self.use_cached_pillar:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in missed_minions])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in minion_ids])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _tgt_to_list(self):
# Return a list of minion ids that match the target and tgt_type
minion_ids = []
ckminions = salt.utils.minions.CkMinions(self.opts)
_res = ckminions.check_minions(self.tgt, self.tgt_type)
minion_ids = _res['minions']
if not minion_ids:
log.debug('No minions matched for tgt="%s" and tgt_type="%s"', self.tgt, self.tgt_type)
return {}
log.debug('Matching minions for tgt="%s" and tgt_type="%s": %s', self.tgt, self.tgt_type, minion_ids)
return minion_ids
def get_minion_pillar(self):
'''
Get pillar data for the targeted minions, either by fetching the
cached minion data on the master, or by compiling the minion's
pillar data on the master.
For runner modules that need access minion pillar data, this
function should be used instead of getting the pillar data by
executing the pillar module on the minions.
By default, this function tries hard to get the pillar data:
- Try to get the cached minion grains and pillar if the
master has minion_data_cache: True
- If the pillar data for the minion is cached, use it.
- If there is no cached grains/pillar data for a minion,
then try to get the minion grains directly from the minion.
- Use the minion grains to compile the pillar directly from the
master using salt.pillar.Pillar
'''
minion_pillars = {}
minion_grains = {}
minion_ids = self._tgt_to_list()
if any(arg for arg in [self.use_cached_grains, self.use_cached_pillar, self.grains_fallback, self.pillar_fallback]):
log.debug('Getting cached minion data')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
cached_minion_pillars = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
log.debug('Getting minion pillar data for: %s', minion_ids)
minion_pillars = self._get_minion_pillar(
*minion_ids,
grains=minion_grains,
cached_pillar=cached_minion_pillars)
return minion_pillars
def get_cached_mine_data(self):
'''
Get cached mine data for the targeted minions.
'''
mine_data = {}
minion_ids = self._tgt_to_list()
log.debug('Getting cached mine data for: %s', minion_ids)
mine_data = self._get_cached_mine_data(*minion_ids)
return mine_data
def clear_cached_minion_data(self,
clear_pillar=False,
clear_grains=False,
clear_mine=False,
clear_mine_func=None):
'''
Clear the cached data/files for the targeted minions.
'''
clear_what = []
if clear_pillar:
clear_what.append('pillar')
if clear_grains:
clear_what.append('grains')
if clear_mine:
clear_what.append('mine')
if clear_mine_func is not None:
clear_what.append('mine_func: \'{0}\''.format(clear_mine_func))
if not clear_what:
log.debug('No cached data types specified for clearing.')
return False
minion_ids = self._tgt_to_list()
log.debug('Clearing cached %s data for: %s',
', '.join(clear_what),
minion_ids)
if clear_pillar == clear_grains:
# clear_pillar and clear_grains are both True or both False.
# This means we don't deal with pillar/grains caches at all.
grains = {}
pillars = {}
else:
# Unless both clear_pillar and clear_grains are True, we need
# to read in the pillar/grains data since they are both stored
# in the same file, 'data.p'
grains, pillars = self._get_cached_minion_data(*minion_ids)
try:
c_minions = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
if minion_id not in c_minions:
# Cache bank for this minion does not exist. Nothing to do.
continue
bank = 'minions/{0}'.format(minion_id)
minion_pillar = pillars.pop(minion_id, False)
minion_grains = grains.pop(minion_id, False)
if ((clear_pillar and clear_grains) or
(clear_pillar and not minion_grains) or
(clear_grains and not minion_pillar)):
# Not saving pillar or grains, so just delete the cache file
self.cache.flush(bank, 'data')
elif clear_pillar and minion_grains:
self.cache.store(bank, 'data', {'grains': minion_grains})
elif clear_grains and minion_pillar:
self.cache.store(bank, 'data', {'pillar': minion_pillar})
if clear_mine:
# Delete the whole mine file
self.cache.flush(bank, 'mine')
elif clear_mine_func is not None:
# Delete a specific function from the mine file
mine_data = self.cache.fetch(bank, 'mine')
if isinstance(mine_data, dict):
if mine_data.pop(clear_mine_func, False):
self.cache.store(bank, 'mine', mine_data)
except (OSError, IOError):
return True
return True
|
saltstack/salt
|
salt/utils/master.py
|
MasterPillarUtil.get_cached_mine_data
|
python
|
def get_cached_mine_data(self):
'''
Get cached mine data for the targeted minions.
'''
mine_data = {}
minion_ids = self._tgt_to_list()
log.debug('Getting cached mine data for: %s', minion_ids)
mine_data = self._get_cached_mine_data(*minion_ids)
return mine_data
|
Get cached mine data for the targeted minions.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L399-L407
|
[
"def _get_cached_mine_data(self, *minion_ids):\n # Return one dict with the cached mine data of the targeted minions\n mine_data = dict([(minion_id, {}) for minion_id in minion_ids])\n if (not self.opts.get('minion_data_cache', False)\n and not self.opts.get('enforce_mine_cache', False)):\n log.debug('Skipping cached mine data minion_data_cache'\n 'and enfore_mine_cache are both disabled.')\n return mine_data\n if not minion_ids:\n minion_ids = self.cache.list('minions')\n for minion_id in minion_ids:\n if not salt.utils.verify.valid_id(self.opts, minion_id):\n continue\n mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'mine')\n if isinstance(mdata, dict):\n mine_data[minion_id] = mdata\n return mine_data\n",
"def _tgt_to_list(self):\n # Return a list of minion ids that match the target and tgt_type\n minion_ids = []\n ckminions = salt.utils.minions.CkMinions(self.opts)\n _res = ckminions.check_minions(self.tgt, self.tgt_type)\n minion_ids = _res['minions']\n if not minion_ids:\n log.debug('No minions matched for tgt=\"%s\" and tgt_type=\"%s\"', self.tgt, self.tgt_type)\n return {}\n log.debug('Matching minions for tgt=\"%s\" and tgt_type=\"%s\": %s', self.tgt, self.tgt_type, minion_ids)\n return minion_ids\n"
] |
class MasterPillarUtil(object):
'''
Helper utility for easy access to targeted minion grain and
pillar data, either from cached data on the master or retrieved
on demand, or (by default) both.
The minion pillar data returned in get_minion_pillar() is
compiled directly from salt.pillar.Pillar on the master to
avoid any possible 'pillar poisoning' from a compromised or
untrusted minion.
** However, the minion grains are still possibly entirely
supplied by the minion. **
Example use case:
For runner modules that need access minion pillar data,
MasterPillarUtil.get_minion_pillar should be used instead
of getting the pillar data by executing the "pillar" module
on the minions:
# my_runner.py
tgt = 'web*'
pillar_util = salt.utils.master.MasterPillarUtil(tgt, tgt_type='glob', opts=__opts__)
pillar_data = pillar_util.get_minion_pillar()
'''
def __init__(self,
tgt='',
tgt_type='glob',
saltenv=None,
use_cached_grains=True,
use_cached_pillar=True,
grains_fallback=True,
pillar_fallback=True,
opts=None):
log.debug('New instance of %s created.',
self.__class__.__name__)
if opts is None:
log.error('%s: Missing master opts init arg.',
self.__class__.__name__)
raise SaltException('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
else:
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.tgt = tgt
self.tgt_type = tgt_type
self.saltenv = saltenv
self.use_cached_grains = use_cached_grains
self.use_cached_pillar = use_cached_pillar
self.grains_fallback = grains_fallback
self.pillar_fallback = pillar_fallback
self.cache = salt.cache.factory(opts)
log.debug(
'Init settings: tgt: \'%s\', tgt_type: \'%s\', saltenv: \'%s\', '
'use_cached_grains: %s, use_cached_pillar: %s, '
'grains_fallback: %s, pillar_fallback: %s',
tgt, tgt_type, saltenv, use_cached_grains, use_cached_pillar,
grains_fallback, pillar_fallback
)
def _get_cached_mine_data(self, *minion_ids):
# Return one dict with the cached mine data of the targeted minions
mine_data = dict([(minion_id, {}) for minion_id in minion_ids])
if (not self.opts.get('minion_data_cache', False)
and not self.opts.get('enforce_mine_cache', False)):
log.debug('Skipping cached mine data minion_data_cache'
'and enfore_mine_cache are both disabled.')
return mine_data
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'mine')
if isinstance(mdata, dict):
mine_data[minion_id] = mdata
return mine_data
def _get_cached_minion_data(self, *minion_ids):
# Return two separate dicts of cached grains and pillar data of the
# minions
grains = dict([(minion_id, {}) for minion_id in minion_ids])
pillars = grains.copy()
if not self.opts.get('minion_data_cache', False):
log.debug('Skipping cached data because minion_data_cache is not '
'enabled.')
return grains, pillars
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'data')
if not isinstance(mdata, dict):
log.warning(
'cache.fetch should always return a dict. ReturnedType: %s, MinionId: %s',
type(mdata).__name__,
minion_id
)
continue
if 'grains' in mdata:
grains[minion_id] = mdata['grains']
if 'pillar' in mdata:
pillars[minion_id] = mdata['pillar']
return grains, pillars
def _get_live_minion_grains(self, minion_ids):
# Returns a dict of grains fetched directly from the minions
log.debug('Getting live grains for minions: "%s"', minion_ids)
client = salt.client.get_local_client(self.opts['conf_file'])
ret = client.cmd(
','.join(minion_ids),
'grains.items',
timeout=self.opts['timeout'],
tgt_type='list')
return ret
def _get_live_minion_pillar(self, minion_id=None, minion_grains=None):
# Returns a dict of pillar data for one minion
if minion_id is None:
return {}
if not minion_grains:
log.warning(
'Cannot get pillar data for %s: no grains supplied.',
minion_id
)
return {}
log.debug('Getting live pillar for %s', minion_id)
pillar = salt.pillar.Pillar(
self.opts,
minion_grains,
minion_id,
self.saltenv,
self.opts['ext_pillar'])
log.debug('Compiling pillar for %s', minion_id)
ret = pillar.compile_pillar()
return ret
def _get_minion_grains(self, *minion_ids, **kwargs):
# Get the minion grains either from cache or from a direct query
# on the minion. By default try to use cached grains first, then
# fall back to querying the minion directly.
ret = {}
cached_grains = kwargs.get('cached_grains', {})
cret = {}
lret = {}
if self.use_cached_grains:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
lret = self._get_live_minion_grains(missed_minions)
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = self._get_live_minion_grains(minion_ids)
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _get_minion_pillar(self, *minion_ids, **kwargs):
# Get the minion pillar either from cache or from a direct query
# on the minion. By default try use the cached pillar first, then
# fall back to rendering pillar on demand with the supplied grains.
ret = {}
grains = kwargs.get('grains', {})
cached_pillar = kwargs.get('cached_pillar', {})
cret = {}
lret = {}
if self.use_cached_pillar:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in missed_minions])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in minion_ids])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _tgt_to_list(self):
# Return a list of minion ids that match the target and tgt_type
minion_ids = []
ckminions = salt.utils.minions.CkMinions(self.opts)
_res = ckminions.check_minions(self.tgt, self.tgt_type)
minion_ids = _res['minions']
if not minion_ids:
log.debug('No minions matched for tgt="%s" and tgt_type="%s"', self.tgt, self.tgt_type)
return {}
log.debug('Matching minions for tgt="%s" and tgt_type="%s": %s', self.tgt, self.tgt_type, minion_ids)
return minion_ids
def get_minion_pillar(self):
'''
Get pillar data for the targeted minions, either by fetching the
cached minion data on the master, or by compiling the minion's
pillar data on the master.
For runner modules that need access minion pillar data, this
function should be used instead of getting the pillar data by
executing the pillar module on the minions.
By default, this function tries hard to get the pillar data:
- Try to get the cached minion grains and pillar if the
master has minion_data_cache: True
- If the pillar data for the minion is cached, use it.
- If there is no cached grains/pillar data for a minion,
then try to get the minion grains directly from the minion.
- Use the minion grains to compile the pillar directly from the
master using salt.pillar.Pillar
'''
minion_pillars = {}
minion_grains = {}
minion_ids = self._tgt_to_list()
if any(arg for arg in [self.use_cached_grains, self.use_cached_pillar, self.grains_fallback, self.pillar_fallback]):
log.debug('Getting cached minion data')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
cached_minion_pillars = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
log.debug('Getting minion pillar data for: %s', minion_ids)
minion_pillars = self._get_minion_pillar(
*minion_ids,
grains=minion_grains,
cached_pillar=cached_minion_pillars)
return minion_pillars
def get_minion_grains(self):
'''
Get grains data for the targeted minions, either by fetching the
cached minion data on the master, or by fetching the grains
directly on the minion.
By default, this function tries hard to get the grains data:
- Try to get the cached minion grains if the master
has minion_data_cache: True
- If the grains data for the minion is cached, use it.
- If there is no cached grains data for a minion,
then try to get the minion grains directly from the minion.
'''
minion_grains = {}
minion_ids = self._tgt_to_list()
if not minion_ids:
return {}
if any(arg for arg in [self.use_cached_grains, self.grains_fallback]):
log.debug('Getting cached minion data.')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
return minion_grains
def clear_cached_minion_data(self,
clear_pillar=False,
clear_grains=False,
clear_mine=False,
clear_mine_func=None):
'''
Clear the cached data/files for the targeted minions.
'''
clear_what = []
if clear_pillar:
clear_what.append('pillar')
if clear_grains:
clear_what.append('grains')
if clear_mine:
clear_what.append('mine')
if clear_mine_func is not None:
clear_what.append('mine_func: \'{0}\''.format(clear_mine_func))
if not clear_what:
log.debug('No cached data types specified for clearing.')
return False
minion_ids = self._tgt_to_list()
log.debug('Clearing cached %s data for: %s',
', '.join(clear_what),
minion_ids)
if clear_pillar == clear_grains:
# clear_pillar and clear_grains are both True or both False.
# This means we don't deal with pillar/grains caches at all.
grains = {}
pillars = {}
else:
# Unless both clear_pillar and clear_grains are True, we need
# to read in the pillar/grains data since they are both stored
# in the same file, 'data.p'
grains, pillars = self._get_cached_minion_data(*minion_ids)
try:
c_minions = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
if minion_id not in c_minions:
# Cache bank for this minion does not exist. Nothing to do.
continue
bank = 'minions/{0}'.format(minion_id)
minion_pillar = pillars.pop(minion_id, False)
minion_grains = grains.pop(minion_id, False)
if ((clear_pillar and clear_grains) or
(clear_pillar and not minion_grains) or
(clear_grains and not minion_pillar)):
# Not saving pillar or grains, so just delete the cache file
self.cache.flush(bank, 'data')
elif clear_pillar and minion_grains:
self.cache.store(bank, 'data', {'grains': minion_grains})
elif clear_grains and minion_pillar:
self.cache.store(bank, 'data', {'pillar': minion_pillar})
if clear_mine:
# Delete the whole mine file
self.cache.flush(bank, 'mine')
elif clear_mine_func is not None:
# Delete a specific function from the mine file
mine_data = self.cache.fetch(bank, 'mine')
if isinstance(mine_data, dict):
if mine_data.pop(clear_mine_func, False):
self.cache.store(bank, 'mine', mine_data)
except (OSError, IOError):
return True
return True
|
saltstack/salt
|
salt/utils/master.py
|
MasterPillarUtil.clear_cached_minion_data
|
python
|
def clear_cached_minion_data(self,
clear_pillar=False,
clear_grains=False,
clear_mine=False,
clear_mine_func=None):
'''
Clear the cached data/files for the targeted minions.
'''
clear_what = []
if clear_pillar:
clear_what.append('pillar')
if clear_grains:
clear_what.append('grains')
if clear_mine:
clear_what.append('mine')
if clear_mine_func is not None:
clear_what.append('mine_func: \'{0}\''.format(clear_mine_func))
if not clear_what:
log.debug('No cached data types specified for clearing.')
return False
minion_ids = self._tgt_to_list()
log.debug('Clearing cached %s data for: %s',
', '.join(clear_what),
minion_ids)
if clear_pillar == clear_grains:
# clear_pillar and clear_grains are both True or both False.
# This means we don't deal with pillar/grains caches at all.
grains = {}
pillars = {}
else:
# Unless both clear_pillar and clear_grains are True, we need
# to read in the pillar/grains data since they are both stored
# in the same file, 'data.p'
grains, pillars = self._get_cached_minion_data(*minion_ids)
try:
c_minions = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
if minion_id not in c_minions:
# Cache bank for this minion does not exist. Nothing to do.
continue
bank = 'minions/{0}'.format(minion_id)
minion_pillar = pillars.pop(minion_id, False)
minion_grains = grains.pop(minion_id, False)
if ((clear_pillar and clear_grains) or
(clear_pillar and not minion_grains) or
(clear_grains and not minion_pillar)):
# Not saving pillar or grains, so just delete the cache file
self.cache.flush(bank, 'data')
elif clear_pillar and minion_grains:
self.cache.store(bank, 'data', {'grains': minion_grains})
elif clear_grains and minion_pillar:
self.cache.store(bank, 'data', {'pillar': minion_pillar})
if clear_mine:
# Delete the whole mine file
self.cache.flush(bank, 'mine')
elif clear_mine_func is not None:
# Delete a specific function from the mine file
mine_data = self.cache.fetch(bank, 'mine')
if isinstance(mine_data, dict):
if mine_data.pop(clear_mine_func, False):
self.cache.store(bank, 'mine', mine_data)
except (OSError, IOError):
return True
return True
|
Clear the cached data/files for the targeted minions.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L409-L476
|
[
"def valid_id(opts, id_):\n '''\n Returns if the passed id is valid\n '''\n try:\n if any(x in id_ for x in ('/', '\\\\', str('\\0'))):\n return False\n return bool(clean_path(opts['pki_dir'], id_))\n except (AttributeError, KeyError, TypeError, UnicodeDecodeError):\n return False\n",
"def _get_cached_minion_data(self, *minion_ids):\n # Return two separate dicts of cached grains and pillar data of the\n # minions\n grains = dict([(minion_id, {}) for minion_id in minion_ids])\n pillars = grains.copy()\n if not self.opts.get('minion_data_cache', False):\n log.debug('Skipping cached data because minion_data_cache is not '\n 'enabled.')\n return grains, pillars\n if not minion_ids:\n minion_ids = self.cache.list('minions')\n for minion_id in minion_ids:\n if not salt.utils.verify.valid_id(self.opts, minion_id):\n continue\n mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'data')\n if not isinstance(mdata, dict):\n log.warning(\n 'cache.fetch should always return a dict. ReturnedType: %s, MinionId: %s',\n type(mdata).__name__,\n minion_id\n )\n continue\n if 'grains' in mdata:\n grains[minion_id] = mdata['grains']\n if 'pillar' in mdata:\n pillars[minion_id] = mdata['pillar']\n return grains, pillars\n",
"def _tgt_to_list(self):\n # Return a list of minion ids that match the target and tgt_type\n minion_ids = []\n ckminions = salt.utils.minions.CkMinions(self.opts)\n _res = ckminions.check_minions(self.tgt, self.tgt_type)\n minion_ids = _res['minions']\n if not minion_ids:\n log.debug('No minions matched for tgt=\"%s\" and tgt_type=\"%s\"', self.tgt, self.tgt_type)\n return {}\n log.debug('Matching minions for tgt=\"%s\" and tgt_type=\"%s\": %s', self.tgt, self.tgt_type, minion_ids)\n return minion_ids\n"
] |
class MasterPillarUtil(object):
'''
Helper utility for easy access to targeted minion grain and
pillar data, either from cached data on the master or retrieved
on demand, or (by default) both.
The minion pillar data returned in get_minion_pillar() is
compiled directly from salt.pillar.Pillar on the master to
avoid any possible 'pillar poisoning' from a compromised or
untrusted minion.
** However, the minion grains are still possibly entirely
supplied by the minion. **
Example use case:
For runner modules that need access minion pillar data,
MasterPillarUtil.get_minion_pillar should be used instead
of getting the pillar data by executing the "pillar" module
on the minions:
# my_runner.py
tgt = 'web*'
pillar_util = salt.utils.master.MasterPillarUtil(tgt, tgt_type='glob', opts=__opts__)
pillar_data = pillar_util.get_minion_pillar()
'''
def __init__(self,
tgt='',
tgt_type='glob',
saltenv=None,
use_cached_grains=True,
use_cached_pillar=True,
grains_fallback=True,
pillar_fallback=True,
opts=None):
log.debug('New instance of %s created.',
self.__class__.__name__)
if opts is None:
log.error('%s: Missing master opts init arg.',
self.__class__.__name__)
raise SaltException('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
else:
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.tgt = tgt
self.tgt_type = tgt_type
self.saltenv = saltenv
self.use_cached_grains = use_cached_grains
self.use_cached_pillar = use_cached_pillar
self.grains_fallback = grains_fallback
self.pillar_fallback = pillar_fallback
self.cache = salt.cache.factory(opts)
log.debug(
'Init settings: tgt: \'%s\', tgt_type: \'%s\', saltenv: \'%s\', '
'use_cached_grains: %s, use_cached_pillar: %s, '
'grains_fallback: %s, pillar_fallback: %s',
tgt, tgt_type, saltenv, use_cached_grains, use_cached_pillar,
grains_fallback, pillar_fallback
)
def _get_cached_mine_data(self, *minion_ids):
# Return one dict with the cached mine data of the targeted minions
mine_data = dict([(minion_id, {}) for minion_id in minion_ids])
if (not self.opts.get('minion_data_cache', False)
and not self.opts.get('enforce_mine_cache', False)):
log.debug('Skipping cached mine data minion_data_cache'
'and enfore_mine_cache are both disabled.')
return mine_data
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'mine')
if isinstance(mdata, dict):
mine_data[minion_id] = mdata
return mine_data
def _get_cached_minion_data(self, *minion_ids):
# Return two separate dicts of cached grains and pillar data of the
# minions
grains = dict([(minion_id, {}) for minion_id in minion_ids])
pillars = grains.copy()
if not self.opts.get('minion_data_cache', False):
log.debug('Skipping cached data because minion_data_cache is not '
'enabled.')
return grains, pillars
if not minion_ids:
minion_ids = self.cache.list('minions')
for minion_id in minion_ids:
if not salt.utils.verify.valid_id(self.opts, minion_id):
continue
mdata = self.cache.fetch('minions/{0}'.format(minion_id), 'data')
if not isinstance(mdata, dict):
log.warning(
'cache.fetch should always return a dict. ReturnedType: %s, MinionId: %s',
type(mdata).__name__,
minion_id
)
continue
if 'grains' in mdata:
grains[minion_id] = mdata['grains']
if 'pillar' in mdata:
pillars[minion_id] = mdata['pillar']
return grains, pillars
def _get_live_minion_grains(self, minion_ids):
# Returns a dict of grains fetched directly from the minions
log.debug('Getting live grains for minions: "%s"', minion_ids)
client = salt.client.get_local_client(self.opts['conf_file'])
ret = client.cmd(
','.join(minion_ids),
'grains.items',
timeout=self.opts['timeout'],
tgt_type='list')
return ret
def _get_live_minion_pillar(self, minion_id=None, minion_grains=None):
# Returns a dict of pillar data for one minion
if minion_id is None:
return {}
if not minion_grains:
log.warning(
'Cannot get pillar data for %s: no grains supplied.',
minion_id
)
return {}
log.debug('Getting live pillar for %s', minion_id)
pillar = salt.pillar.Pillar(
self.opts,
minion_grains,
minion_id,
self.saltenv,
self.opts['ext_pillar'])
log.debug('Compiling pillar for %s', minion_id)
ret = pillar.compile_pillar()
return ret
def _get_minion_grains(self, *minion_ids, **kwargs):
# Get the minion grains either from cache or from a direct query
# on the minion. By default try to use cached grains first, then
# fall back to querying the minion directly.
ret = {}
cached_grains = kwargs.get('cached_grains', {})
cret = {}
lret = {}
if self.use_cached_grains:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
lret = self._get_live_minion_grains(missed_minions)
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = self._get_live_minion_grains(minion_ids)
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion grains for: %s', missed_minions)
if self.grains_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_grains) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _get_minion_pillar(self, *minion_ids, **kwargs):
# Get the minion pillar either from cache or from a direct query
# on the minion. By default try use the cached pillar first, then
# fall back to rendering pillar on demand with the supplied grains.
ret = {}
grains = kwargs.get('grains', {})
cached_pillar = kwargs.get('cached_pillar', {})
cret = {}
lret = {}
if self.use_cached_pillar:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in cret]
log.debug('Missed cached minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in missed_minions])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
else:
lret = dict([(minion_id, self._get_live_minion_pillar(minion_id, grains.get(minion_id, {}))) for minion_id in minion_ids])
missed_minions = [minion_id for minion_id in minion_ids if minion_id not in lret]
log.debug('Missed live minion pillars for: %s', missed_minions)
if self.pillar_fallback and missed_minions:
cret = dict([(minion_id, mcache) for (minion_id, mcache) in six.iteritems(cached_pillar) if mcache])
ret = {key: value for key, value in [(minion_id, {}) for minion_id in minion_ids] + list(six.iteritems(cret)) + list(six.iteritems(lret))}
return ret
def _tgt_to_list(self):
# Return a list of minion ids that match the target and tgt_type
minion_ids = []
ckminions = salt.utils.minions.CkMinions(self.opts)
_res = ckminions.check_minions(self.tgt, self.tgt_type)
minion_ids = _res['minions']
if not minion_ids:
log.debug('No minions matched for tgt="%s" and tgt_type="%s"', self.tgt, self.tgt_type)
return {}
log.debug('Matching minions for tgt="%s" and tgt_type="%s": %s', self.tgt, self.tgt_type, minion_ids)
return minion_ids
def get_minion_pillar(self):
'''
Get pillar data for the targeted minions, either by fetching the
cached minion data on the master, or by compiling the minion's
pillar data on the master.
For runner modules that need access minion pillar data, this
function should be used instead of getting the pillar data by
executing the pillar module on the minions.
By default, this function tries hard to get the pillar data:
- Try to get the cached minion grains and pillar if the
master has minion_data_cache: True
- If the pillar data for the minion is cached, use it.
- If there is no cached grains/pillar data for a minion,
then try to get the minion grains directly from the minion.
- Use the minion grains to compile the pillar directly from the
master using salt.pillar.Pillar
'''
minion_pillars = {}
minion_grains = {}
minion_ids = self._tgt_to_list()
if any(arg for arg in [self.use_cached_grains, self.use_cached_pillar, self.grains_fallback, self.pillar_fallback]):
log.debug('Getting cached minion data')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
cached_minion_pillars = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
log.debug('Getting minion pillar data for: %s', minion_ids)
minion_pillars = self._get_minion_pillar(
*minion_ids,
grains=minion_grains,
cached_pillar=cached_minion_pillars)
return minion_pillars
def get_minion_grains(self):
'''
Get grains data for the targeted minions, either by fetching the
cached minion data on the master, or by fetching the grains
directly on the minion.
By default, this function tries hard to get the grains data:
- Try to get the cached minion grains if the master
has minion_data_cache: True
- If the grains data for the minion is cached, use it.
- If there is no cached grains data for a minion,
then try to get the minion grains directly from the minion.
'''
minion_grains = {}
minion_ids = self._tgt_to_list()
if not minion_ids:
return {}
if any(arg for arg in [self.use_cached_grains, self.grains_fallback]):
log.debug('Getting cached minion data.')
cached_minion_grains, cached_minion_pillars = self._get_cached_minion_data(*minion_ids)
else:
cached_minion_grains = {}
log.debug('Getting minion grain data for: %s', minion_ids)
minion_grains = self._get_minion_grains(
*minion_ids,
cached_grains=cached_minion_grains)
return minion_grains
def get_cached_mine_data(self):
'''
Get cached mine data for the targeted minions.
'''
mine_data = {}
minion_ids = self._tgt_to_list()
log.debug('Getting cached mine data for: %s', minion_ids)
mine_data = self._get_cached_mine_data(*minion_ids)
return mine_data
|
saltstack/salt
|
salt/utils/master.py
|
CacheTimer.run
|
python
|
def run(self):
'''
main loop that fires the event every second
'''
context = zmq.Context()
# the socket for outgoing timer events
socket = context.socket(zmq.PUB)
socket.setsockopt(zmq.LINGER, 100)
socket.bind('ipc://' + self.timer_sock)
count = 0
log.debug('ConCache-Timer started')
while not self.stopped.wait(1):
socket.send(self.serial.dumps(count))
count += 1
if count >= 60:
count = 0
|
main loop that fires the event every second
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L492-L509
| null |
class CacheTimer(Thread):
'''
A basic timer class the fires timer-events every second.
This is used for cleanup by the ConnectedCache()
'''
def __init__(self, opts, event):
Thread.__init__(self)
self.opts = opts
self.stopped = event
self.daemon = True
self.serial = salt.payload.Serial(opts.get('serial', ''))
self.timer_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
|
saltstack/salt
|
salt/utils/master.py
|
CacheWorker.run
|
python
|
def run(self):
'''
Gather currently connected minions and update the cache
'''
new_mins = list(salt.utils.minions.CkMinions(self.opts).connected_ids())
cc = cache_cli(self.opts)
cc.get_cached()
cc.put_cache([new_mins])
log.debug('ConCache CacheWorker update finished')
|
Gather currently connected minions and update the cache
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L544-L552
|
[
"def put_cache(self, minions):\n '''\n published the given minions to the ConCache\n '''\n self.cupd_out.send(self.serial.dumps(minions))\n",
"def get_cached(self):\n '''\n queries the ConCache for a list of currently connected minions\n '''\n msg = self.serial.dumps('minions')\n self.creq_out.send(msg)\n min_list = self.serial.loads(self.creq_out.recv())\n return min_list\n",
"def connected_ids(self, subset=None, show_ip=False, show_ipv4=None, include_localhost=None):\n '''\n Return a set of all connected minion ids, optionally within a subset\n '''\n if include_localhost is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'The \\'include_localhost\\' argument is no longer required; any'\n 'connected localhost minion will always be included.'\n )\n if show_ipv4 is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'The \\'show_ipv4\\' argument has been renamed to \\'show_ip\\' as'\n 'it now also includes IPv6 addresses for IPv6-connected'\n 'minions.'\n )\n minions = set()\n if self.opts.get('minion_data_cache', False):\n search = self.cache.list('minions')\n if search is None:\n return minions\n addrs = salt.utils.network.local_port_tcp(int(self.opts['publish_port']))\n if '127.0.0.1' in addrs:\n # Add in the address of a possible locally-connected minion.\n addrs.discard('127.0.0.1')\n addrs.update(set(salt.utils.network.ip_addrs(include_loopback=False)))\n if '::1' in addrs:\n # Add in the address of a possible locally-connected minion.\n addrs.discard('::1')\n addrs.update(set(salt.utils.network.ip_addrs6(include_loopback=False)))\n if subset:\n search = subset\n for id_ in search:\n try:\n mdata = self.cache.fetch('minions/{0}'.format(id_), 'data')\n except SaltCacheError:\n # If a SaltCacheError is explicitly raised during the fetch operation,\n # permission was denied to open the cached data.p file. Continue on as\n # in the releases <= 2016.3. (An explicit error raise was added in PR\n # #35388. See issue #36867 for more information.\n continue\n if mdata is None:\n continue\n grains = mdata.get('grains', {})\n for ipv4 in grains.get('ipv4', []):\n if ipv4 in addrs:\n if show_ip:\n minions.add((id_, ipv4))\n else:\n minions.add(id_)\n break\n for ipv6 in grains.get('ipv6', []):\n if ipv6 in addrs:\n if show_ip:\n minions.add((id_, ipv6))\n else:\n minions.add(id_)\n break\n return minions\n"
] |
class CacheWorker(MultiprocessingProcess):
'''
Worker for ConnectedCache which runs in its
own process to prevent blocking of ConnectedCache
main-loop when refreshing minion-list
'''
def __init__(self, opts, **kwargs):
'''
Sets up the zmq-connection to the ConCache
'''
super(CacheWorker, self).__init__(**kwargs)
self.opts = opts
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
|
saltstack/salt
|
salt/utils/master.py
|
ConnectedCache.cleanup
|
python
|
def cleanup(self):
'''
remove sockets on shutdown
'''
log.debug('ConCache cleaning up')
if os.path.exists(self.cache_sock):
os.remove(self.cache_sock)
if os.path.exists(self.update_sock):
os.remove(self.update_sock)
if os.path.exists(self.upd_t_sock):
os.remove(self.upd_t_sock)
|
remove sockets on shutdown
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L613-L623
| null |
class ConnectedCache(MultiprocessingProcess):
'''
Provides access to all minions ids that the master has
successfully authenticated. The cache is cleaned up regularly by
comparing it to the IPs that have open connections to
the master publisher port.
'''
def __init__(self, opts, **kwargs):
'''
starts the timer and inits the cache itself
'''
super(ConnectedCache, self).__init__(**kwargs)
log.debug('ConCache initializing...')
# the possible settings for the cache
self.opts = opts
# the actual cached minion ids
self.minions = []
self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc')
self.update_sock = os.path.join(self.opts['sock_dir'], 'con_upd.ipc')
self.upd_t_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
self.cleanup()
# the timer provides 1-second intervals to the loop in run()
# to make the cache system most responsive, we do not use a loop-
# delay which makes it hard to get 1-second intervals without a timer
self.timer_stop = Event()
self.timer = CacheTimer(self.opts, self.timer_stop)
self.timer.start()
self.running = True
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def signal_handler(self, sig, frame):
'''
handle signals and shutdown
'''
self.stop()
def secure(self):
'''
secure the sockets for root-only access
'''
log.debug('ConCache securing sockets')
if os.path.exists(self.cache_sock):
os.chmod(self.cache_sock, 0o600)
if os.path.exists(self.update_sock):
os.chmod(self.update_sock, 0o600)
if os.path.exists(self.upd_t_sock):
os.chmod(self.upd_t_sock, 0o600)
def stop(self):
'''
shutdown cache process
'''
# avoid getting called twice
self.cleanup()
if self.running:
self.running = False
self.timer_stop.set()
self.timer.join()
def run(self):
'''
Main loop of the ConCache, starts updates in intervals and
answers requests from the MWorkers
'''
context = zmq.Context()
# the socket for incoming cache requests
creq_in = context.socket(zmq.REP)
creq_in.setsockopt(zmq.LINGER, 100)
creq_in.bind('ipc://' + self.cache_sock)
# the socket for incoming cache-updates from workers
cupd_in = context.socket(zmq.SUB)
cupd_in.setsockopt(zmq.SUBSCRIBE, b'')
cupd_in.setsockopt(zmq.LINGER, 100)
cupd_in.bind('ipc://' + self.update_sock)
# the socket for the timer-event
timer_in = context.socket(zmq.SUB)
timer_in.setsockopt(zmq.SUBSCRIBE, b'')
timer_in.setsockopt(zmq.LINGER, 100)
timer_in.connect('ipc://' + self.upd_t_sock)
poller = zmq.Poller()
poller.register(creq_in, zmq.POLLIN)
poller.register(cupd_in, zmq.POLLIN)
poller.register(timer_in, zmq.POLLIN)
# our serializer
serial = salt.payload.Serial(self.opts.get('serial', ''))
# register a signal handler
signal.signal(signal.SIGINT, self.signal_handler)
# secure the sockets from the world
self.secure()
log.info('ConCache started')
while self.running:
# we check for new events with the poller
try:
socks = dict(poller.poll(1))
except KeyboardInterrupt:
self.stop()
except zmq.ZMQError as zmq_err:
log.error('ConCache ZeroMQ-Error occurred')
log.exception(zmq_err)
self.stop()
# check for next cache-request
if socks.get(creq_in) == zmq.POLLIN:
msg = serial.loads(creq_in.recv())
log.debug('ConCache Received request: %s', msg)
# requests to the minion list are send as str's
if isinstance(msg, six.string_types):
if msg == 'minions':
# Send reply back to client
reply = serial.dumps(self.minions)
creq_in.send(reply)
# check for next cache-update from workers
if socks.get(cupd_in) == zmq.POLLIN:
new_c_data = serial.loads(cupd_in.recv())
# tell the worker to exit
#cupd_in.send(serial.dumps('ACK'))
# check if the returned data is usable
if not isinstance(new_c_data, list):
log.error('ConCache Worker returned unusable result')
del new_c_data
continue
# the cache will receive lists of minions
# 1. if the list only has 1 item, its from an MWorker, we append it
# 2. if the list contains another list, its from a CacheWorker and
# the currently cached minions are replaced with that list
# 3. anything else is considered malformed
try:
if not new_c_data:
log.debug('ConCache Got empty update from worker')
continue
data = new_c_data[0]
if isinstance(data, six.string_types):
if data not in self.minions:
log.debug('ConCache Adding minion %s to cache',
new_c_data[0])
self.minions.append(data)
elif isinstance(data, list):
log.debug('ConCache Replacing minion list from worker')
self.minions = data
except IndexError:
log.debug('ConCache Got malformed result dict from worker')
del new_c_data
log.info('ConCache %s entries in cache', len(self.minions))
# check for next timer-event to start new jobs
if socks.get(timer_in) == zmq.POLLIN:
sec_event = serial.loads(timer_in.recv())
# update the list every 30 seconds
if int(sec_event % 30) == 0:
cw = CacheWorker(self.opts)
cw.start()
self.stop()
creq_in.close()
cupd_in.close()
timer_in.close()
context.term()
log.debug('ConCache Shutting down')
|
saltstack/salt
|
salt/utils/master.py
|
ConnectedCache.secure
|
python
|
def secure(self):
'''
secure the sockets for root-only access
'''
log.debug('ConCache securing sockets')
if os.path.exists(self.cache_sock):
os.chmod(self.cache_sock, 0o600)
if os.path.exists(self.update_sock):
os.chmod(self.update_sock, 0o600)
if os.path.exists(self.upd_t_sock):
os.chmod(self.upd_t_sock, 0o600)
|
secure the sockets for root-only access
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L625-L635
| null |
class ConnectedCache(MultiprocessingProcess):
'''
Provides access to all minions ids that the master has
successfully authenticated. The cache is cleaned up regularly by
comparing it to the IPs that have open connections to
the master publisher port.
'''
def __init__(self, opts, **kwargs):
'''
starts the timer and inits the cache itself
'''
super(ConnectedCache, self).__init__(**kwargs)
log.debug('ConCache initializing...')
# the possible settings for the cache
self.opts = opts
# the actual cached minion ids
self.minions = []
self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc')
self.update_sock = os.path.join(self.opts['sock_dir'], 'con_upd.ipc')
self.upd_t_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
self.cleanup()
# the timer provides 1-second intervals to the loop in run()
# to make the cache system most responsive, we do not use a loop-
# delay which makes it hard to get 1-second intervals without a timer
self.timer_stop = Event()
self.timer = CacheTimer(self.opts, self.timer_stop)
self.timer.start()
self.running = True
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def signal_handler(self, sig, frame):
'''
handle signals and shutdown
'''
self.stop()
def cleanup(self):
'''
remove sockets on shutdown
'''
log.debug('ConCache cleaning up')
if os.path.exists(self.cache_sock):
os.remove(self.cache_sock)
if os.path.exists(self.update_sock):
os.remove(self.update_sock)
if os.path.exists(self.upd_t_sock):
os.remove(self.upd_t_sock)
def stop(self):
'''
shutdown cache process
'''
# avoid getting called twice
self.cleanup()
if self.running:
self.running = False
self.timer_stop.set()
self.timer.join()
def run(self):
'''
Main loop of the ConCache, starts updates in intervals and
answers requests from the MWorkers
'''
context = zmq.Context()
# the socket for incoming cache requests
creq_in = context.socket(zmq.REP)
creq_in.setsockopt(zmq.LINGER, 100)
creq_in.bind('ipc://' + self.cache_sock)
# the socket for incoming cache-updates from workers
cupd_in = context.socket(zmq.SUB)
cupd_in.setsockopt(zmq.SUBSCRIBE, b'')
cupd_in.setsockopt(zmq.LINGER, 100)
cupd_in.bind('ipc://' + self.update_sock)
# the socket for the timer-event
timer_in = context.socket(zmq.SUB)
timer_in.setsockopt(zmq.SUBSCRIBE, b'')
timer_in.setsockopt(zmq.LINGER, 100)
timer_in.connect('ipc://' + self.upd_t_sock)
poller = zmq.Poller()
poller.register(creq_in, zmq.POLLIN)
poller.register(cupd_in, zmq.POLLIN)
poller.register(timer_in, zmq.POLLIN)
# our serializer
serial = salt.payload.Serial(self.opts.get('serial', ''))
# register a signal handler
signal.signal(signal.SIGINT, self.signal_handler)
# secure the sockets from the world
self.secure()
log.info('ConCache started')
while self.running:
# we check for new events with the poller
try:
socks = dict(poller.poll(1))
except KeyboardInterrupt:
self.stop()
except zmq.ZMQError as zmq_err:
log.error('ConCache ZeroMQ-Error occurred')
log.exception(zmq_err)
self.stop()
# check for next cache-request
if socks.get(creq_in) == zmq.POLLIN:
msg = serial.loads(creq_in.recv())
log.debug('ConCache Received request: %s', msg)
# requests to the minion list are send as str's
if isinstance(msg, six.string_types):
if msg == 'minions':
# Send reply back to client
reply = serial.dumps(self.minions)
creq_in.send(reply)
# check for next cache-update from workers
if socks.get(cupd_in) == zmq.POLLIN:
new_c_data = serial.loads(cupd_in.recv())
# tell the worker to exit
#cupd_in.send(serial.dumps('ACK'))
# check if the returned data is usable
if not isinstance(new_c_data, list):
log.error('ConCache Worker returned unusable result')
del new_c_data
continue
# the cache will receive lists of minions
# 1. if the list only has 1 item, its from an MWorker, we append it
# 2. if the list contains another list, its from a CacheWorker and
# the currently cached minions are replaced with that list
# 3. anything else is considered malformed
try:
if not new_c_data:
log.debug('ConCache Got empty update from worker')
continue
data = new_c_data[0]
if isinstance(data, six.string_types):
if data not in self.minions:
log.debug('ConCache Adding minion %s to cache',
new_c_data[0])
self.minions.append(data)
elif isinstance(data, list):
log.debug('ConCache Replacing minion list from worker')
self.minions = data
except IndexError:
log.debug('ConCache Got malformed result dict from worker')
del new_c_data
log.info('ConCache %s entries in cache', len(self.minions))
# check for next timer-event to start new jobs
if socks.get(timer_in) == zmq.POLLIN:
sec_event = serial.loads(timer_in.recv())
# update the list every 30 seconds
if int(sec_event % 30) == 0:
cw = CacheWorker(self.opts)
cw.start()
self.stop()
creq_in.close()
cupd_in.close()
timer_in.close()
context.term()
log.debug('ConCache Shutting down')
|
saltstack/salt
|
salt/utils/master.py
|
ConnectedCache.stop
|
python
|
def stop(self):
'''
shutdown cache process
'''
# avoid getting called twice
self.cleanup()
if self.running:
self.running = False
self.timer_stop.set()
self.timer.join()
|
shutdown cache process
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L637-L646
| null |
class ConnectedCache(MultiprocessingProcess):
'''
Provides access to all minions ids that the master has
successfully authenticated. The cache is cleaned up regularly by
comparing it to the IPs that have open connections to
the master publisher port.
'''
def __init__(self, opts, **kwargs):
'''
starts the timer and inits the cache itself
'''
super(ConnectedCache, self).__init__(**kwargs)
log.debug('ConCache initializing...')
# the possible settings for the cache
self.opts = opts
# the actual cached minion ids
self.minions = []
self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc')
self.update_sock = os.path.join(self.opts['sock_dir'], 'con_upd.ipc')
self.upd_t_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
self.cleanup()
# the timer provides 1-second intervals to the loop in run()
# to make the cache system most responsive, we do not use a loop-
# delay which makes it hard to get 1-second intervals without a timer
self.timer_stop = Event()
self.timer = CacheTimer(self.opts, self.timer_stop)
self.timer.start()
self.running = True
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def signal_handler(self, sig, frame):
'''
handle signals and shutdown
'''
self.stop()
def cleanup(self):
'''
remove sockets on shutdown
'''
log.debug('ConCache cleaning up')
if os.path.exists(self.cache_sock):
os.remove(self.cache_sock)
if os.path.exists(self.update_sock):
os.remove(self.update_sock)
if os.path.exists(self.upd_t_sock):
os.remove(self.upd_t_sock)
def secure(self):
'''
secure the sockets for root-only access
'''
log.debug('ConCache securing sockets')
if os.path.exists(self.cache_sock):
os.chmod(self.cache_sock, 0o600)
if os.path.exists(self.update_sock):
os.chmod(self.update_sock, 0o600)
if os.path.exists(self.upd_t_sock):
os.chmod(self.upd_t_sock, 0o600)
def run(self):
'''
Main loop of the ConCache, starts updates in intervals and
answers requests from the MWorkers
'''
context = zmq.Context()
# the socket for incoming cache requests
creq_in = context.socket(zmq.REP)
creq_in.setsockopt(zmq.LINGER, 100)
creq_in.bind('ipc://' + self.cache_sock)
# the socket for incoming cache-updates from workers
cupd_in = context.socket(zmq.SUB)
cupd_in.setsockopt(zmq.SUBSCRIBE, b'')
cupd_in.setsockopt(zmq.LINGER, 100)
cupd_in.bind('ipc://' + self.update_sock)
# the socket for the timer-event
timer_in = context.socket(zmq.SUB)
timer_in.setsockopt(zmq.SUBSCRIBE, b'')
timer_in.setsockopt(zmq.LINGER, 100)
timer_in.connect('ipc://' + self.upd_t_sock)
poller = zmq.Poller()
poller.register(creq_in, zmq.POLLIN)
poller.register(cupd_in, zmq.POLLIN)
poller.register(timer_in, zmq.POLLIN)
# our serializer
serial = salt.payload.Serial(self.opts.get('serial', ''))
# register a signal handler
signal.signal(signal.SIGINT, self.signal_handler)
# secure the sockets from the world
self.secure()
log.info('ConCache started')
while self.running:
# we check for new events with the poller
try:
socks = dict(poller.poll(1))
except KeyboardInterrupt:
self.stop()
except zmq.ZMQError as zmq_err:
log.error('ConCache ZeroMQ-Error occurred')
log.exception(zmq_err)
self.stop()
# check for next cache-request
if socks.get(creq_in) == zmq.POLLIN:
msg = serial.loads(creq_in.recv())
log.debug('ConCache Received request: %s', msg)
# requests to the minion list are send as str's
if isinstance(msg, six.string_types):
if msg == 'minions':
# Send reply back to client
reply = serial.dumps(self.minions)
creq_in.send(reply)
# check for next cache-update from workers
if socks.get(cupd_in) == zmq.POLLIN:
new_c_data = serial.loads(cupd_in.recv())
# tell the worker to exit
#cupd_in.send(serial.dumps('ACK'))
# check if the returned data is usable
if not isinstance(new_c_data, list):
log.error('ConCache Worker returned unusable result')
del new_c_data
continue
# the cache will receive lists of minions
# 1. if the list only has 1 item, its from an MWorker, we append it
# 2. if the list contains another list, its from a CacheWorker and
# the currently cached minions are replaced with that list
# 3. anything else is considered malformed
try:
if not new_c_data:
log.debug('ConCache Got empty update from worker')
continue
data = new_c_data[0]
if isinstance(data, six.string_types):
if data not in self.minions:
log.debug('ConCache Adding minion %s to cache',
new_c_data[0])
self.minions.append(data)
elif isinstance(data, list):
log.debug('ConCache Replacing minion list from worker')
self.minions = data
except IndexError:
log.debug('ConCache Got malformed result dict from worker')
del new_c_data
log.info('ConCache %s entries in cache', len(self.minions))
# check for next timer-event to start new jobs
if socks.get(timer_in) == zmq.POLLIN:
sec_event = serial.loads(timer_in.recv())
# update the list every 30 seconds
if int(sec_event % 30) == 0:
cw = CacheWorker(self.opts)
cw.start()
self.stop()
creq_in.close()
cupd_in.close()
timer_in.close()
context.term()
log.debug('ConCache Shutting down')
|
saltstack/salt
|
salt/utils/master.py
|
ConnectedCache.run
|
python
|
def run(self):
'''
Main loop of the ConCache, starts updates in intervals and
answers requests from the MWorkers
'''
context = zmq.Context()
# the socket for incoming cache requests
creq_in = context.socket(zmq.REP)
creq_in.setsockopt(zmq.LINGER, 100)
creq_in.bind('ipc://' + self.cache_sock)
# the socket for incoming cache-updates from workers
cupd_in = context.socket(zmq.SUB)
cupd_in.setsockopt(zmq.SUBSCRIBE, b'')
cupd_in.setsockopt(zmq.LINGER, 100)
cupd_in.bind('ipc://' + self.update_sock)
# the socket for the timer-event
timer_in = context.socket(zmq.SUB)
timer_in.setsockopt(zmq.SUBSCRIBE, b'')
timer_in.setsockopt(zmq.LINGER, 100)
timer_in.connect('ipc://' + self.upd_t_sock)
poller = zmq.Poller()
poller.register(creq_in, zmq.POLLIN)
poller.register(cupd_in, zmq.POLLIN)
poller.register(timer_in, zmq.POLLIN)
# our serializer
serial = salt.payload.Serial(self.opts.get('serial', ''))
# register a signal handler
signal.signal(signal.SIGINT, self.signal_handler)
# secure the sockets from the world
self.secure()
log.info('ConCache started')
while self.running:
# we check for new events with the poller
try:
socks = dict(poller.poll(1))
except KeyboardInterrupt:
self.stop()
except zmq.ZMQError as zmq_err:
log.error('ConCache ZeroMQ-Error occurred')
log.exception(zmq_err)
self.stop()
# check for next cache-request
if socks.get(creq_in) == zmq.POLLIN:
msg = serial.loads(creq_in.recv())
log.debug('ConCache Received request: %s', msg)
# requests to the minion list are send as str's
if isinstance(msg, six.string_types):
if msg == 'minions':
# Send reply back to client
reply = serial.dumps(self.minions)
creq_in.send(reply)
# check for next cache-update from workers
if socks.get(cupd_in) == zmq.POLLIN:
new_c_data = serial.loads(cupd_in.recv())
# tell the worker to exit
#cupd_in.send(serial.dumps('ACK'))
# check if the returned data is usable
if not isinstance(new_c_data, list):
log.error('ConCache Worker returned unusable result')
del new_c_data
continue
# the cache will receive lists of minions
# 1. if the list only has 1 item, its from an MWorker, we append it
# 2. if the list contains another list, its from a CacheWorker and
# the currently cached minions are replaced with that list
# 3. anything else is considered malformed
try:
if not new_c_data:
log.debug('ConCache Got empty update from worker')
continue
data = new_c_data[0]
if isinstance(data, six.string_types):
if data not in self.minions:
log.debug('ConCache Adding minion %s to cache',
new_c_data[0])
self.minions.append(data)
elif isinstance(data, list):
log.debug('ConCache Replacing minion list from worker')
self.minions = data
except IndexError:
log.debug('ConCache Got malformed result dict from worker')
del new_c_data
log.info('ConCache %s entries in cache', len(self.minions))
# check for next timer-event to start new jobs
if socks.get(timer_in) == zmq.POLLIN:
sec_event = serial.loads(timer_in.recv())
# update the list every 30 seconds
if int(sec_event % 30) == 0:
cw = CacheWorker(self.opts)
cw.start()
self.stop()
creq_in.close()
cupd_in.close()
timer_in.close()
context.term()
log.debug('ConCache Shutting down')
|
Main loop of the ConCache, starts updates in intervals and
answers requests from the MWorkers
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/master.py#L648-L767
|
[
"def loads(self, msg, encoding=None, raw=False):\n '''\n Run the correct loads serialization format\n\n :param encoding: Useful for Python 3 support. If the msgpack data\n was encoded using \"use_bin_type=True\", this will\n differentiate between the 'bytes' type and the\n 'str' type by decoding contents with 'str' type\n to what the encoding was set as. Recommended\n encoding is 'utf-8' when using Python 3.\n If the msgpack data was not encoded using\n \"use_bin_type=True\", it will try to decode\n all 'bytes' and 'str' data (the distinction has\n been lost in this case) to what the encoding is\n set as. In this case, it will fail if any of\n the contents cannot be converted.\n '''\n try:\n def ext_type_decoder(code, data):\n if code == 78:\n data = salt.utils.stringutils.to_unicode(data)\n return datetime.datetime.strptime(data, '%Y%m%dT%H:%M:%S.%f')\n return data\n\n gc.disable() # performance optimization for msgpack\n if msgpack.version >= (0, 4, 0):\n # msgpack only supports 'encoding' starting in 0.4.0.\n # Due to this, if we don't need it, don't pass it at all so\n # that under Python 2 we can still work with older versions\n # of msgpack.\n try:\n ret = salt.utils.msgpack.loads(msg, use_list=True,\n ext_hook=ext_type_decoder,\n encoding=encoding,\n _msgpack_module=msgpack)\n except UnicodeDecodeError:\n # msg contains binary data\n ret = msgpack.loads(msg, use_list=True, ext_hook=ext_type_decoder)\n else:\n ret = salt.utils.msgpack.loads(msg, use_list=True,\n ext_hook=ext_type_decoder,\n _msgpack_module=msgpack)\n if six.PY3 and encoding is None and not raw:\n ret = salt.transport.frame.decode_embedded_strs(ret)\n except Exception as exc:\n log.critical(\n 'Could not deserialize msgpack message. This often happens '\n 'when trying to read a file not in binary mode. '\n 'To see message payload, enable debug logging and retry. '\n 'Exception: %s', exc\n )\n log.debug('Msgpack deserialization failure on message: %s', msg)\n gc.collect()\n raise\n finally:\n gc.enable()\n return ret\n",
"def dumps(self, msg, use_bin_type=False):\n '''\n Run the correct dumps serialization format\n\n :param use_bin_type: Useful for Python 3 support. Tells msgpack to\n differentiate between 'str' and 'bytes' types\n by encoding them differently.\n Since this changes the wire protocol, this\n option should not be used outside of IPC.\n '''\n def ext_type_encoder(obj):\n if isinstance(obj, six.integer_types):\n # msgpack can't handle the very long Python longs for jids\n # Convert any very long longs to strings\n return six.text_type(obj)\n elif isinstance(obj, (datetime.datetime, datetime.date)):\n # msgpack doesn't support datetime.datetime and datetime.date datatypes.\n # So here we have converted these types to custom datatype\n # This is msgpack Extended types numbered 78\n return msgpack.ExtType(78, salt.utils.stringutils.to_bytes(\n obj.strftime('%Y%m%dT%H:%M:%S.%f')))\n # The same for immutable types\n elif isinstance(obj, immutabletypes.ImmutableDict):\n return dict(obj)\n elif isinstance(obj, immutabletypes.ImmutableList):\n return list(obj)\n elif isinstance(obj, (set, immutabletypes.ImmutableSet)):\n # msgpack can't handle set so translate it to tuple\n return tuple(obj)\n elif isinstance(obj, CaseInsensitiveDict):\n return dict(obj)\n # Nothing known exceptions found. Let msgpack raise it's own.\n return obj\n\n try:\n if msgpack.version >= (0, 4, 0):\n # msgpack only supports 'use_bin_type' starting in 0.4.0.\n # Due to this, if we don't need it, don't pass it at all so\n # that under Python 2 we can still work with older versions\n # of msgpack.\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n except (OverflowError, msgpack.exceptions.PackValueError):\n # msgpack<=0.4.6 don't call ext encoder on very long integers raising the error instead.\n # Convert any very long longs to strings and call dumps again.\n def verylong_encoder(obj, context):\n # Make sure we catch recursion here.\n objid = id(obj)\n if objid in context:\n return '<Recursion on {} with id={}>'.format(type(obj).__name__, id(obj))\n context.add(objid)\n\n if isinstance(obj, dict):\n for key, value in six.iteritems(obj.copy()):\n obj[key] = verylong_encoder(value, context)\n return dict(obj)\n elif isinstance(obj, (list, tuple)):\n obj = list(obj)\n for idx, entry in enumerate(obj):\n obj[idx] = verylong_encoder(entry, context)\n return obj\n # A value of an Integer object is limited from -(2^63) upto (2^64)-1 by MessagePack\n # spec. Here we care only of JIDs that are positive integers.\n if isinstance(obj, six.integer_types) and obj >= pow(2, 64):\n return six.text_type(obj)\n else:\n return obj\n\n msg = verylong_encoder(msg, set())\n if msgpack.version >= (0, 4, 0):\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n"
] |
class ConnectedCache(MultiprocessingProcess):
'''
Provides access to all minions ids that the master has
successfully authenticated. The cache is cleaned up regularly by
comparing it to the IPs that have open connections to
the master publisher port.
'''
def __init__(self, opts, **kwargs):
'''
starts the timer and inits the cache itself
'''
super(ConnectedCache, self).__init__(**kwargs)
log.debug('ConCache initializing...')
# the possible settings for the cache
self.opts = opts
# the actual cached minion ids
self.minions = []
self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc')
self.update_sock = os.path.join(self.opts['sock_dir'], 'con_upd.ipc')
self.upd_t_sock = os.path.join(self.opts['sock_dir'], 'con_timer.ipc')
self.cleanup()
# the timer provides 1-second intervals to the loop in run()
# to make the cache system most responsive, we do not use a loop-
# delay which makes it hard to get 1-second intervals without a timer
self.timer_stop = Event()
self.timer = CacheTimer(self.opts, self.timer_stop)
self.timer.start()
self.running = True
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def signal_handler(self, sig, frame):
'''
handle signals and shutdown
'''
self.stop()
def cleanup(self):
'''
remove sockets on shutdown
'''
log.debug('ConCache cleaning up')
if os.path.exists(self.cache_sock):
os.remove(self.cache_sock)
if os.path.exists(self.update_sock):
os.remove(self.update_sock)
if os.path.exists(self.upd_t_sock):
os.remove(self.upd_t_sock)
def secure(self):
'''
secure the sockets for root-only access
'''
log.debug('ConCache securing sockets')
if os.path.exists(self.cache_sock):
os.chmod(self.cache_sock, 0o600)
if os.path.exists(self.update_sock):
os.chmod(self.update_sock, 0o600)
if os.path.exists(self.upd_t_sock):
os.chmod(self.upd_t_sock, 0o600)
def stop(self):
'''
shutdown cache process
'''
# avoid getting called twice
self.cleanup()
if self.running:
self.running = False
self.timer_stop.set()
self.timer.join()
|
saltstack/salt
|
salt/returners/sms_return.py
|
returner
|
python
|
def returner(ret):
'''
Return a response in an SMS message
'''
_options = _get_options(ret)
sid = _options.get('sid', None)
token = _options.get('token', None)
sender = _options.get('from', None)
receiver = _options.get('to', None)
if sid is None or token is None:
log.error('Twilio sid/authentication token missing')
return None
if sender is None or receiver is None:
log.error('Twilio to/from fields are missing')
return None
client = TwilioRestClient(sid, token)
try:
message = client.messages.create(
body='Minion: {0}\nCmd: {1}\nSuccess: {2}\n\nJid: {3}'.format(
ret['id'], ret['fun'], ret['success'], ret['jid']
), to=receiver, from_=sender)
except TwilioRestException as e:
log.error(
'Twilio [https://www.twilio.com/docs/errors/%s]',
e.code
)
return False
return True
|
Return a response in an SMS message
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/sms_return.py#L72-L105
|
[
"def _get_options(ret=None):\n '''\n Get the Twilio options from salt.\n '''\n attrs = {'sid': 'sid',\n 'token': 'token',\n 'to': 'to',\n 'from': 'from'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n return _options\n"
] |
# -*- coding: utf-8 -*-
'''
Return data by SMS.
.. versionadded:: 2015.5.0
:maintainer: Damian Myerscough
:maturity: new
:depends: twilio
:platform: all
To enable this returner the minion will need the python twilio library
installed and the following values configured in the minion or master
config:
.. code-block:: yaml
twilio.sid: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
twilio.token: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
twilio.to: '+1415XXXXXXX'
twilio.from: '+1650XXXXXXX'
To use the sms returner, append '--return sms' to the salt command.
.. code-block:: bash
salt '*' test.ping --return sms
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.returners
log = logging.getLogger(__name__)
try:
from twilio.rest import TwilioRestClient
from twilio.rest.exceptions import TwilioRestException
HAS_TWILIO = True
except ImportError:
HAS_TWILIO = False
__virtualname__ = 'sms'
def __virtual__():
if HAS_TWILIO:
return __virtualname__
return False, 'Could not import sms returner; twilio is not installed.'
def _get_options(ret=None):
'''
Get the Twilio options from salt.
'''
attrs = {'sid': 'sid',
'token': 'token',
'to': 'to',
'from': 'from'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
|
saltstack/salt
|
salt/states/keystone_group.py
|
_common
|
python
|
def _common(kwargs):
'''
Returns: None if group wasn't found, otherwise a group object
'''
search_kwargs = {'name': kwargs['name']}
if 'domain' in kwargs:
domain = __salt__['keystoneng.get_entity'](
'domain', name=kwargs.pop('domain'))
domain_id = domain.id if hasattr(domain, 'id') else domain
search_kwargs['filters'] = {'domain_id': domain_id}
kwargs['domain'] = domain
return __salt__['keystoneng.group_get'](**search_kwargs)
|
Returns: None if group wasn't found, otherwise a group object
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_group.py#L41-L53
| null |
# -*- coding: utf-8 -*-
'''
Management of OpenStack Keystone Groups
=======================================
.. versionadded:: 2018.3.0
:depends: shade
:configuration: see :py:mod:`salt.modules.keystoneng` for setup instructions
Example States
.. code-block:: yaml
create group:
keystone_group.present:
- name: group1
delete group:
keystone_group.absent:
- name: group1
create group with optional params:
keystone_group.present:
- name: group1
- domain: domain1
- description: 'my group'
'''
from __future__ import absolute_import, unicode_literals, print_function
__virtualname__ = 'keystone_group'
def __virtual__():
if 'keystoneng.group_get' in __salt__:
return __virtualname__
return (False, 'The keystoneng execution module failed to load: shade python module is not available')
def present(name, auth=None, **kwargs):
'''
Ensure an group exists and is up-to-date
name
Name of the group
domain
The name or id of the domain
description
An arbitrary description of the group
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_cloud'](auth)
kwargs = __utils__['args.clean_kwargs'](**kwargs)
kwargs['name'] = name
group = _common(kwargs)
if group is None:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = kwargs
ret['comment'] = 'Group will be created.'
return ret
group = __salt__['keystoneng.group_create'](**kwargs)
ret['changes'] = group
ret['comment'] = 'Created group'
return ret
changes = __salt__['keystoneng.compare_changes'](group, **kwargs)
if changes:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = changes
ret['comment'] = 'Group will be updated.'
return ret
__salt__['keystoneng.group_update'](**kwargs)
ret['changes'].update(changes)
ret['comment'] = 'Updated group'
return ret
def absent(name, auth=None, **kwargs):
'''
Ensure group does not exist
name
Name of the group
domain
The name or id of the domain
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['keystoneng.setup_cloud'](auth)
kwargs['name'] = name
group = _common(kwargs)
if group:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = {'id': group.id}
ret['comment'] = 'Group will be deleted.'
return ret
__salt__['keystoneng.group_delete'](name=group)
ret['changes']['id'] = group.id
ret['comment'] = 'Deleted group'
return ret
|
saltstack/salt
|
salt/states/keystone_group.py
|
absent
|
python
|
def absent(name, auth=None, **kwargs):
'''
Ensure group does not exist
name
Name of the group
domain
The name or id of the domain
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['keystoneng.setup_cloud'](auth)
kwargs['name'] = name
group = _common(kwargs)
if group:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = {'id': group.id}
ret['comment'] = 'Group will be deleted.'
return ret
__salt__['keystoneng.group_delete'](name=group)
ret['changes']['id'] = group.id
ret['comment'] = 'Deleted group'
return ret
|
Ensure group does not exist
name
Name of the group
domain
The name or id of the domain
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_group.py#L108-L141
|
[
"def _common(kwargs):\n '''\n Returns: None if group wasn't found, otherwise a group object\n '''\n search_kwargs = {'name': kwargs['name']}\n if 'domain' in kwargs:\n domain = __salt__['keystoneng.get_entity'](\n 'domain', name=kwargs.pop('domain'))\n domain_id = domain.id if hasattr(domain, 'id') else domain\n search_kwargs['filters'] = {'domain_id': domain_id}\n kwargs['domain'] = domain\n\n return __salt__['keystoneng.group_get'](**search_kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Management of OpenStack Keystone Groups
=======================================
.. versionadded:: 2018.3.0
:depends: shade
:configuration: see :py:mod:`salt.modules.keystoneng` for setup instructions
Example States
.. code-block:: yaml
create group:
keystone_group.present:
- name: group1
delete group:
keystone_group.absent:
- name: group1
create group with optional params:
keystone_group.present:
- name: group1
- domain: domain1
- description: 'my group'
'''
from __future__ import absolute_import, unicode_literals, print_function
__virtualname__ = 'keystone_group'
def __virtual__():
if 'keystoneng.group_get' in __salt__:
return __virtualname__
return (False, 'The keystoneng execution module failed to load: shade python module is not available')
def _common(kwargs):
'''
Returns: None if group wasn't found, otherwise a group object
'''
search_kwargs = {'name': kwargs['name']}
if 'domain' in kwargs:
domain = __salt__['keystoneng.get_entity'](
'domain', name=kwargs.pop('domain'))
domain_id = domain.id if hasattr(domain, 'id') else domain
search_kwargs['filters'] = {'domain_id': domain_id}
kwargs['domain'] = domain
return __salt__['keystoneng.group_get'](**search_kwargs)
def present(name, auth=None, **kwargs):
'''
Ensure an group exists and is up-to-date
name
Name of the group
domain
The name or id of the domain
description
An arbitrary description of the group
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_cloud'](auth)
kwargs = __utils__['args.clean_kwargs'](**kwargs)
kwargs['name'] = name
group = _common(kwargs)
if group is None:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = kwargs
ret['comment'] = 'Group will be created.'
return ret
group = __salt__['keystoneng.group_create'](**kwargs)
ret['changes'] = group
ret['comment'] = 'Created group'
return ret
changes = __salt__['keystoneng.compare_changes'](group, **kwargs)
if changes:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = changes
ret['comment'] = 'Group will be updated.'
return ret
__salt__['keystoneng.group_update'](**kwargs)
ret['changes'].update(changes)
ret['comment'] = 'Updated group'
return ret
|
saltstack/salt
|
salt/wheel/pillar_roots.py
|
find
|
python
|
def find(path, saltenv='base'):
'''
Return a dict of the files located with the given path and environment
'''
# Return a list of paths + text or bin
ret = []
if saltenv not in __opts__['pillar_roots']:
return ret
for root in __opts__['pillar_roots'][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, 'rb') as fp_:
if salt.utils.files.is_text(fp_):
ret.append({full: 'txt'})
else:
ret.append({full: 'bin'})
return ret
|
Return a dict of the files located with the given path and environment
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/pillar_roots.py#L19-L36
|
[
"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"
] |
# -*- coding: utf-8 -*-
'''
The `pillar_roots` wheel module is used to manage files under the pillar roots
directories on the master server.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import salt libs
import salt.utils.files
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
def list_env(saltenv='base'):
'''
Return all of the file paths found in an environment
'''
ret = {}
if saltenv not in __opts__['pillar_roots']:
return ret
for f_root in __opts__['pillar_roots'][saltenv]:
ret[f_root] = {}
for root, dirs, files in salt.utils.path.os_walk(f_root):
sub = ret[f_root]
if root != f_root:
# grab subroot ref
sroot = root
above = []
# Populate the above dict
while not os.path.samefile(sroot, f_root):
base = os.path.basename(sroot)
if base:
above.insert(0, base)
sroot = os.path.dirname(sroot)
for aroot in above:
sub = sub[aroot]
for dir_ in dirs:
sub[dir_] = {}
for fn_ in files:
sub[fn_] = 'f'
return ret
def list_roots():
'''
Return all of the files names in all available environments
'''
ret = {}
for saltenv in __opts__['pillar_roots']:
ret[saltenv] = []
ret[saltenv].append(list_env(saltenv))
return ret
def read(path, saltenv='base'):
'''
Read the contents of a text file, if the file is binary then
'''
# Return a dict of paths + content
ret = []
files = find(path, saltenv)
for fn_ in files:
full = next(six.iterkeys(fn_))
form = fn_[full]
if form == 'txt':
with salt.utils.files.fopen(full, 'rb') as fp_:
ret.append(
{full: salt.utils.stringutils.to_unicode(fp_.read())}
)
return ret
def write(data, path, saltenv='base', index=0):
'''
Write the named file, by default the first file found is written, but the
index of the file can be specified to write to a lower priority file root
'''
if saltenv not in __opts__['pillar_roots']:
return 'Named environment {0} is not present'.format(saltenv)
if len(__opts__['pillar_roots'][saltenv]) <= index:
return 'Specified index {0} in environment {1} is not present'.format(
index, saltenv)
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
dest = os.path.join(__opts__['pillar_roots'][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
with salt.utils.files.fopen(dest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(data))
return 'Wrote data to file {0}'.format(dest)
|
saltstack/salt
|
salt/wheel/pillar_roots.py
|
list_env
|
python
|
def list_env(saltenv='base'):
'''
Return all of the file paths found in an environment
'''
ret = {}
if saltenv not in __opts__['pillar_roots']:
return ret
for f_root in __opts__['pillar_roots'][saltenv]:
ret[f_root] = {}
for root, dirs, files in salt.utils.path.os_walk(f_root):
sub = ret[f_root]
if root != f_root:
# grab subroot ref
sroot = root
above = []
# Populate the above dict
while not os.path.samefile(sroot, f_root):
base = os.path.basename(sroot)
if base:
above.insert(0, base)
sroot = os.path.dirname(sroot)
for aroot in above:
sub = sub[aroot]
for dir_ in dirs:
sub[dir_] = {}
for fn_ in files:
sub[fn_] = 'f'
return ret
|
Return all of the file paths found in an environment
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/pillar_roots.py#L39-L66
|
[
"def os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n"
] |
# -*- coding: utf-8 -*-
'''
The `pillar_roots` wheel module is used to manage files under the pillar roots
directories on the master server.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import salt libs
import salt.utils.files
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
def find(path, saltenv='base'):
'''
Return a dict of the files located with the given path and environment
'''
# Return a list of paths + text or bin
ret = []
if saltenv not in __opts__['pillar_roots']:
return ret
for root in __opts__['pillar_roots'][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, 'rb') as fp_:
if salt.utils.files.is_text(fp_):
ret.append({full: 'txt'})
else:
ret.append({full: 'bin'})
return ret
def list_roots():
'''
Return all of the files names in all available environments
'''
ret = {}
for saltenv in __opts__['pillar_roots']:
ret[saltenv] = []
ret[saltenv].append(list_env(saltenv))
return ret
def read(path, saltenv='base'):
'''
Read the contents of a text file, if the file is binary then
'''
# Return a dict of paths + content
ret = []
files = find(path, saltenv)
for fn_ in files:
full = next(six.iterkeys(fn_))
form = fn_[full]
if form == 'txt':
with salt.utils.files.fopen(full, 'rb') as fp_:
ret.append(
{full: salt.utils.stringutils.to_unicode(fp_.read())}
)
return ret
def write(data, path, saltenv='base', index=0):
'''
Write the named file, by default the first file found is written, but the
index of the file can be specified to write to a lower priority file root
'''
if saltenv not in __opts__['pillar_roots']:
return 'Named environment {0} is not present'.format(saltenv)
if len(__opts__['pillar_roots'][saltenv]) <= index:
return 'Specified index {0} in environment {1} is not present'.format(
index, saltenv)
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
dest = os.path.join(__opts__['pillar_roots'][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
with salt.utils.files.fopen(dest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(data))
return 'Wrote data to file {0}'.format(dest)
|
saltstack/salt
|
salt/wheel/pillar_roots.py
|
list_roots
|
python
|
def list_roots():
'''
Return all of the files names in all available environments
'''
ret = {}
for saltenv in __opts__['pillar_roots']:
ret[saltenv] = []
ret[saltenv].append(list_env(saltenv))
return ret
|
Return all of the files names in all available environments
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/pillar_roots.py#L69-L77
|
[
"def list_env(saltenv='base'):\n '''\n Return all of the file paths found in an environment\n '''\n ret = {}\n if saltenv not in __opts__['pillar_roots']:\n return ret\n for f_root in __opts__['pillar_roots'][saltenv]:\n ret[f_root] = {}\n for root, dirs, files in salt.utils.path.os_walk(f_root):\n sub = ret[f_root]\n if root != f_root:\n # grab subroot ref\n sroot = root\n above = []\n # Populate the above dict\n while not os.path.samefile(sroot, f_root):\n base = os.path.basename(sroot)\n if base:\n above.insert(0, base)\n sroot = os.path.dirname(sroot)\n for aroot in above:\n sub = sub[aroot]\n for dir_ in dirs:\n sub[dir_] = {}\n for fn_ in files:\n sub[fn_] = 'f'\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
The `pillar_roots` wheel module is used to manage files under the pillar roots
directories on the master server.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import salt libs
import salt.utils.files
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
def find(path, saltenv='base'):
'''
Return a dict of the files located with the given path and environment
'''
# Return a list of paths + text or bin
ret = []
if saltenv not in __opts__['pillar_roots']:
return ret
for root in __opts__['pillar_roots'][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, 'rb') as fp_:
if salt.utils.files.is_text(fp_):
ret.append({full: 'txt'})
else:
ret.append({full: 'bin'})
return ret
def list_env(saltenv='base'):
'''
Return all of the file paths found in an environment
'''
ret = {}
if saltenv not in __opts__['pillar_roots']:
return ret
for f_root in __opts__['pillar_roots'][saltenv]:
ret[f_root] = {}
for root, dirs, files in salt.utils.path.os_walk(f_root):
sub = ret[f_root]
if root != f_root:
# grab subroot ref
sroot = root
above = []
# Populate the above dict
while not os.path.samefile(sroot, f_root):
base = os.path.basename(sroot)
if base:
above.insert(0, base)
sroot = os.path.dirname(sroot)
for aroot in above:
sub = sub[aroot]
for dir_ in dirs:
sub[dir_] = {}
for fn_ in files:
sub[fn_] = 'f'
return ret
def read(path, saltenv='base'):
'''
Read the contents of a text file, if the file is binary then
'''
# Return a dict of paths + content
ret = []
files = find(path, saltenv)
for fn_ in files:
full = next(six.iterkeys(fn_))
form = fn_[full]
if form == 'txt':
with salt.utils.files.fopen(full, 'rb') as fp_:
ret.append(
{full: salt.utils.stringutils.to_unicode(fp_.read())}
)
return ret
def write(data, path, saltenv='base', index=0):
'''
Write the named file, by default the first file found is written, but the
index of the file can be specified to write to a lower priority file root
'''
if saltenv not in __opts__['pillar_roots']:
return 'Named environment {0} is not present'.format(saltenv)
if len(__opts__['pillar_roots'][saltenv]) <= index:
return 'Specified index {0} in environment {1} is not present'.format(
index, saltenv)
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
dest = os.path.join(__opts__['pillar_roots'][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
with salt.utils.files.fopen(dest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(data))
return 'Wrote data to file {0}'.format(dest)
|
saltstack/salt
|
salt/wheel/pillar_roots.py
|
read
|
python
|
def read(path, saltenv='base'):
'''
Read the contents of a text file, if the file is binary then
'''
# Return a dict of paths + content
ret = []
files = find(path, saltenv)
for fn_ in files:
full = next(six.iterkeys(fn_))
form = fn_[full]
if form == 'txt':
with salt.utils.files.fopen(full, 'rb') as fp_:
ret.append(
{full: salt.utils.stringutils.to_unicode(fp_.read())}
)
return ret
|
Read the contents of a text file, if the file is binary then
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/pillar_roots.py#L80-L95
|
[
"def find(path, saltenv='base'):\n '''\n Return a dict of the files located with the given path and environment\n '''\n # Return a list of paths + text or bin\n ret = []\n if saltenv not in __opts__['pillar_roots']:\n return ret\n for root in __opts__['pillar_roots'][saltenv]:\n full = os.path.join(root, path)\n if os.path.isfile(full):\n # Add it to the dict\n with salt.utils.files.fopen(full, 'rb') as fp_:\n if salt.utils.files.is_text(fp_):\n ret.append({full: 'txt'})\n else:\n ret.append({full: 'bin'})\n return ret\n",
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\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 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"
] |
# -*- coding: utf-8 -*-
'''
The `pillar_roots` wheel module is used to manage files under the pillar roots
directories on the master server.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import salt libs
import salt.utils.files
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
def find(path, saltenv='base'):
'''
Return a dict of the files located with the given path and environment
'''
# Return a list of paths + text or bin
ret = []
if saltenv not in __opts__['pillar_roots']:
return ret
for root in __opts__['pillar_roots'][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, 'rb') as fp_:
if salt.utils.files.is_text(fp_):
ret.append({full: 'txt'})
else:
ret.append({full: 'bin'})
return ret
def list_env(saltenv='base'):
'''
Return all of the file paths found in an environment
'''
ret = {}
if saltenv not in __opts__['pillar_roots']:
return ret
for f_root in __opts__['pillar_roots'][saltenv]:
ret[f_root] = {}
for root, dirs, files in salt.utils.path.os_walk(f_root):
sub = ret[f_root]
if root != f_root:
# grab subroot ref
sroot = root
above = []
# Populate the above dict
while not os.path.samefile(sroot, f_root):
base = os.path.basename(sroot)
if base:
above.insert(0, base)
sroot = os.path.dirname(sroot)
for aroot in above:
sub = sub[aroot]
for dir_ in dirs:
sub[dir_] = {}
for fn_ in files:
sub[fn_] = 'f'
return ret
def list_roots():
'''
Return all of the files names in all available environments
'''
ret = {}
for saltenv in __opts__['pillar_roots']:
ret[saltenv] = []
ret[saltenv].append(list_env(saltenv))
return ret
def write(data, path, saltenv='base', index=0):
'''
Write the named file, by default the first file found is written, but the
index of the file can be specified to write to a lower priority file root
'''
if saltenv not in __opts__['pillar_roots']:
return 'Named environment {0} is not present'.format(saltenv)
if len(__opts__['pillar_roots'][saltenv]) <= index:
return 'Specified index {0} in environment {1} is not present'.format(
index, saltenv)
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
dest = os.path.join(__opts__['pillar_roots'][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
with salt.utils.files.fopen(dest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(data))
return 'Wrote data to file {0}'.format(dest)
|
saltstack/salt
|
salt/wheel/pillar_roots.py
|
write
|
python
|
def write(data, path, saltenv='base', index=0):
'''
Write the named file, by default the first file found is written, but the
index of the file can be specified to write to a lower priority file root
'''
if saltenv not in __opts__['pillar_roots']:
return 'Named environment {0} is not present'.format(saltenv)
if len(__opts__['pillar_roots'][saltenv]) <= index:
return 'Specified index {0} in environment {1} is not present'.format(
index, saltenv)
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
dest = os.path.join(__opts__['pillar_roots'][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
with salt.utils.files.fopen(dest, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(data))
return 'Wrote data to file {0}'.format(dest)
|
Write the named file, by default the first file found is written, but the
index of the file can be specified to write to a lower priority file root
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/pillar_roots.py#L98-L117
|
[
"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_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"
] |
# -*- coding: utf-8 -*-
'''
The `pillar_roots` wheel module is used to manage files under the pillar roots
directories on the master server.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import salt libs
import salt.utils.files
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
def find(path, saltenv='base'):
'''
Return a dict of the files located with the given path and environment
'''
# Return a list of paths + text or bin
ret = []
if saltenv not in __opts__['pillar_roots']:
return ret
for root in __opts__['pillar_roots'][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, 'rb') as fp_:
if salt.utils.files.is_text(fp_):
ret.append({full: 'txt'})
else:
ret.append({full: 'bin'})
return ret
def list_env(saltenv='base'):
'''
Return all of the file paths found in an environment
'''
ret = {}
if saltenv not in __opts__['pillar_roots']:
return ret
for f_root in __opts__['pillar_roots'][saltenv]:
ret[f_root] = {}
for root, dirs, files in salt.utils.path.os_walk(f_root):
sub = ret[f_root]
if root != f_root:
# grab subroot ref
sroot = root
above = []
# Populate the above dict
while not os.path.samefile(sroot, f_root):
base = os.path.basename(sroot)
if base:
above.insert(0, base)
sroot = os.path.dirname(sroot)
for aroot in above:
sub = sub[aroot]
for dir_ in dirs:
sub[dir_] = {}
for fn_ in files:
sub[fn_] = 'f'
return ret
def list_roots():
'''
Return all of the files names in all available environments
'''
ret = {}
for saltenv in __opts__['pillar_roots']:
ret[saltenv] = []
ret[saltenv].append(list_env(saltenv))
return ret
def read(path, saltenv='base'):
'''
Read the contents of a text file, if the file is binary then
'''
# Return a dict of paths + content
ret = []
files = find(path, saltenv)
for fn_ in files:
full = next(six.iterkeys(fn_))
form = fn_[full]
if form == 'txt':
with salt.utils.files.fopen(full, 'rb') as fp_:
ret.append(
{full: salt.utils.stringutils.to_unicode(fp_.read())}
)
return ret
|
saltstack/salt
|
salt/states/azurearm_resource.py
|
resource_group_present
|
python
|
def resource_group_present(name, location, managed_by=None, tags=None, connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a resource group exists.
:param name:
Name of the resource group.
:param location:
The Azure location in which to create the resource group. This value cannot be updated once
the resource group is created.
:param managed_by:
The ID of the resource that manages this resource group. This value cannot be updated once
the resource group is created.
:param tags:
A dictionary of strings can be passed as tag metadata to the resource group object.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure resource group exists:
azurearm_resource.resource_group_present:
- name: group1
- location: eastus
- tags:
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
group = {}
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if present:
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
ret['changes'] = __utils__['dictdiffer.deep_diff'](group.get('tags', {}), tags or {})
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Resource group {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Resource group {0} tags would be updated.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': group.get('tags', {}),
'new': tags
}
return ret
elif __opts__['test']:
ret['comment'] = 'Resource group {0} would be created.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': {},
'new': {
'name': name,
'location': location,
'managed_by': managed_by,
'tags': tags,
}
}
return ret
group_kwargs = kwargs.copy()
group_kwargs.update(connection_auth)
group = __salt__['azurearm_resource.resource_group_create_or_update'](
name,
location,
managed_by=managed_by,
tags=tags,
**group_kwargs
)
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if present:
ret['result'] = True
ret['comment'] = 'Resource group {0} has been created.'.format(name)
ret['changes'] = {
'old': {},
'new': group
}
return ret
ret['comment'] = 'Failed to create resource group {0}! ({1})'.format(name, group.get('error'))
return ret
|
.. versionadded:: 2019.2.0
Ensure a resource group exists.
:param name:
Name of the resource group.
:param location:
The Azure location in which to create the resource group. This value cannot be updated once
the resource group is created.
:param managed_by:
The ID of the resource that manages this resource group. This value cannot be updated once
the resource group is created.
:param tags:
A dictionary of strings can be passed as tag metadata to the resource group object.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure resource group exists:
azurearm_resource.resource_group_present:
- name: group1
- location: eastus
- tags:
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_resource.py#L104-L210
| null |
# -*- coding: utf-8 -*-
'''
Azure (ARM) Resource State Module
.. versionadded:: 2019.2.0
:maintainer: <devops@decisionlab.io>
:maturity: new
:depends:
* `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0
* `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8
* `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0
* `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0
* `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1
* `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0
* `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0
* `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0
* `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3
* `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21
:platform: linux
:configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of
keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication
parameters are sensitive, it's recommended to pass them to the states via pillar.
Required provider parameters:
if using username and password:
* ``subscription_id``
* ``username``
* ``password``
if using a service principal:
* ``subscription_id``
* ``tenant``
* ``client_id``
* ``secret``
Optional provider parameters:
**cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values:
* ``AZURE_PUBLIC_CLOUD`` (default)
* ``AZURE_CHINA_CLOUD``
* ``AZURE_US_GOV_CLOUD``
* ``AZURE_GERMAN_CLOUD``
Example Pillar for Azure Resource Manager authentication:
.. code-block:: yaml
azurearm:
user_pass_auth:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
username: fletch
password: 123pass
mysubscription:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
secret: XXXXXXXXXXXXXXXXXXXXXXXX
cloud_environment: AZURE_PUBLIC_CLOUD
Example states using Azure Resource Manager authentication:
.. code-block:: jinja
{% set profile = salt['pillar.get']('azurearm:mysubscription') %}
Ensure resource group exists:
azurearm_resource.resource_group_present:
- name: my_rg
- location: westus
- tags:
how_awesome: very
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
Ensure resource group is absent:
azurearm_resource.resource_group_absent:
- name: other_rg
- connection_auth: {{ profile }}
'''
# Import Python libs
from __future__ import absolute_import
import json
import logging
# Import Salt libs
import salt.utils.files
__virtualname__ = 'azurearm_resource'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only make this state available if the azurearm_resource module is available.
'''
return __virtualname__ if 'azurearm_resource.resource_group_check_existence' in __salt__ else False
def resource_group_absent(name, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a resource group does not exist in the current subscription.
:param name:
Name of the resource group.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
group = {}
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if not present:
ret['result'] = True
ret['comment'] = 'Resource group {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
ret['comment'] = 'Resource group {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': group,
'new': {},
}
return ret
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
deleted = __salt__['azurearm_resource.resource_group_delete'](name, **connection_auth)
if deleted:
present = False
else:
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if not present:
ret['result'] = True
ret['comment'] = 'Resource group {0} has been deleted.'.format(name)
ret['changes'] = {
'old': group,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete resource group {0}!'.format(name)
return ret
def policy_definition_present(name, policy_rule=None, policy_type=None, mode=None, display_name=None, description=None,
metadata=None, parameters=None, policy_rule_json=None, policy_rule_file=None,
template='jinja', source_hash=None, source_hash_name=None, skip_verify=False,
connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a security policy definition exists.
:param name:
Name of the policy definition.
:param policy_rule:
A YAML dictionary defining the policy rule. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used.
:param policy_rule_json:
A text field defining the entirety of a policy definition in JSON. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used. Note that the `name` field in the JSON will override the
``name`` parameter in the state.
:param policy_rule_file:
The source of a JSON file defining the entirety of a policy definition. See `Azure Policy Definition
documentation <https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for
details on the structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required,
in that order of precedence for use if multiple parameters are used. Note that the `name` field in the JSON
will override the ``name`` parameter in the state.
:param skip_verify:
Used for the ``policy_rule_file`` parameter. If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored.
:param source_hash:
This can be a source hash string or the URI of a file that contains source hash strings.
:param source_hash_name:
When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the
filename/URI associated with that hash.
:param policy_type:
The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom. Only used with the
``policy_rule`` parameter.
:param mode:
The policy definition mode. Possible values are NotSpecified, Indexed, and All. Only used with the
``policy_rule`` parameter.
:param display_name:
The display name of the policy definition. Only used with the ``policy_rule`` parameter.
:param description:
The policy definition description. Only used with the ``policy_rule`` parameter.
:param metadata:
The policy definition metadata defined as a dictionary. Only used with the ``policy_rule`` parameter.
:param parameters:
Required dictionary if a parameter is used in the policy rule. Only used with the ``policy_rule`` parameter.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy definition exists:
azurearm_resource.policy_definition_present:
- name: testpolicy
- display_name: Test Policy
- description: Test policy for testing policies.
- policy_rule:
if:
allOf:
- equals: Microsoft.Compute/virtualMachines/write
source: action
- field: location
in:
- eastus
- eastus2
- centralus
then:
effect: deny
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
if not policy_rule and not policy_rule_json and not policy_rule_file:
ret['comment'] = 'One of "policy_rule", "policy_rule_json", or "policy_rule_file" is required!'
return ret
if sum(x is not None for x in [policy_rule, policy_rule_json, policy_rule_file]) > 1:
ret['comment'] = 'Only one of "policy_rule", "policy_rule_json", or "policy_rule_file" is allowed!'
return ret
if ((policy_rule_json or policy_rule_file) and
(policy_type or mode or display_name or description or metadata or parameters)):
ret['comment'] = 'Policy definitions cannot be passed when "policy_rule_json" or "policy_rule_file" is defined!'
return ret
temp_rule = {}
if policy_rule_json:
try:
temp_rule = json.loads(policy_rule_json)
except Exception as exc:
ret['comment'] = 'Unable to load policy rule json! ({0})'.format(exc)
return ret
elif policy_rule_file:
try:
# pylint: disable=unused-variable
sfn, source_sum, comment_ = __salt__['file.get_managed'](
None,
template,
policy_rule_file,
source_hash,
source_hash_name,
None,
None,
None,
__env__,
None,
None,
skip_verify=skip_verify,
**kwargs
)
except Exception as exc:
ret['comment'] = 'Unable to locate policy rule file "{0}"! ({1})'.format(policy_rule_file, exc)
return ret
if not sfn:
ret['comment'] = 'Unable to locate policy rule file "{0}"!)'.format(policy_rule_file)
return ret
try:
with salt.utils.files.fopen(sfn, 'r') as prf:
temp_rule = json.load(prf)
except Exception as exc:
ret['comment'] = 'Unable to load policy rule file "{0}"! ({1})'.format(policy_rule_file, exc)
return ret
if sfn:
salt.utils.files.remove(sfn)
policy_name = name
if policy_rule_json or policy_rule_file:
if temp_rule.get('name'):
policy_name = temp_rule.get('name')
policy_rule = temp_rule.get('properties', {}).get('policyRule')
policy_type = temp_rule.get('properties', {}).get('policyType')
mode = temp_rule.get('properties', {}).get('mode')
display_name = temp_rule.get('properties', {}).get('displayName')
description = temp_rule.get('properties', {}).get('description')
metadata = temp_rule.get('properties', {}).get('metadata')
parameters = temp_rule.get('properties', {}).get('parameters')
policy = __salt__['azurearm_resource.policy_definition_get'](name, azurearm_log_level='info', **connection_auth)
if 'error' not in policy:
if policy_type and policy_type.lower() != policy.get('policy_type', '').lower():
ret['changes']['policy_type'] = {
'old': policy.get('policy_type'),
'new': policy_type
}
if (mode or '').lower() != policy.get('mode', '').lower():
ret['changes']['mode'] = {
'old': policy.get('mode'),
'new': mode
}
if (display_name or '').lower() != policy.get('display_name', '').lower():
ret['changes']['display_name'] = {
'old': policy.get('display_name'),
'new': display_name
}
if (description or '').lower() != policy.get('description', '').lower():
ret['changes']['description'] = {
'old': policy.get('description'),
'new': description
}
rule_changes = __utils__['dictdiffer.deep_diff'](policy.get('policy_rule', {}), policy_rule or {})
if rule_changes:
ret['changes']['policy_rule'] = rule_changes
meta_changes = __utils__['dictdiffer.deep_diff'](policy.get('metadata', {}), metadata or {})
if meta_changes:
ret['changes']['metadata'] = meta_changes
param_changes = __utils__['dictdiffer.deep_diff'](policy.get('parameters', {}), parameters or {})
if param_changes:
ret['changes']['parameters'] = param_changes
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Policy definition {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy definition {0} would be updated.'.format(name)
ret['result'] = None
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': policy_name,
'policy_type': policy_type,
'mode': mode,
'display_name': display_name,
'description': description,
'metadata': metadata,
'parameters': parameters,
'policy_rule': policy_rule,
}
}
if __opts__['test']:
ret['comment'] = 'Policy definition {0} would be created.'.format(name)
ret['result'] = None
return ret
# Convert OrderedDict to dict
if isinstance(metadata, dict):
metadata = json.loads(json.dumps(metadata))
if isinstance(parameters, dict):
parameters = json.loads(json.dumps(parameters))
policy_kwargs = kwargs.copy()
policy_kwargs.update(connection_auth)
policy = __salt__['azurearm_resource.policy_definition_create_or_update'](
name=policy_name,
policy_rule=policy_rule,
policy_type=policy_type,
mode=mode,
display_name=display_name,
description=description,
metadata=metadata,
parameters=parameters,
**policy_kwargs
)
if 'error' not in policy:
ret['result'] = True
ret['comment'] = 'Policy definition {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create policy definition {0}! ({1})'.format(name, policy.get('error'))
return ret
def policy_definition_absent(name, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a policy definition does not exist in the current subscription.
:param name:
Name of the policy definition.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_definition_get'](name, azurearm_log_level='info', **connection_auth)
if 'error' in policy:
ret['result'] = True
ret['comment'] = 'Policy definition {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Policy definition {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': policy,
'new': {},
}
return ret
deleted = __salt__['azurearm_resource.policy_definition_delete'](name, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Policy definition {0} has been deleted.'.format(name)
ret['changes'] = {
'old': policy,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete policy definition {0}!'.format(name)
return ret
def policy_assignment_present(name, scope, definition_name, display_name=None, description=None, assignment_type=None,
parameters=None, connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a security policy assignment exists.
:param name:
Name of the policy assignment.
:param scope:
The scope of the policy assignment.
:param definition_name:
The name of the policy definition to assign.
:param display_name:
The display name of the policy assignment.
:param description:
The policy assignment description.
:param assignment_type:
The type of policy assignment.
:param parameters:
Required dictionary if a parameter is used in the policy rule.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy assignment exists:
azurearm_resource.policy_assignment_present:
- name: testassign
- scope: /subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852
- definition_name: testpolicy
- display_name: Test Assignment
- description: Test assignment for testing assignments.
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_assignment_get'](
name,
scope,
azurearm_log_level='info',
**connection_auth
)
if 'error' not in policy:
if assignment_type and assignment_type.lower() != policy.get('type', '').lower():
ret['changes']['type'] = {
'old': policy.get('type'),
'new': assignment_type
}
if scope.lower() != policy['scope'].lower():
ret['changes']['scope'] = {
'old': policy['scope'],
'new': scope
}
pa_name = policy['policy_definition_id'].split('/')[-1]
if definition_name.lower() != pa_name.lower():
ret['changes']['definition_name'] = {
'old': pa_name,
'new': definition_name
}
if (display_name or '').lower() != policy.get('display_name', '').lower():
ret['changes']['display_name'] = {
'old': policy.get('display_name'),
'new': display_name
}
if (description or '').lower() != policy.get('description', '').lower():
ret['changes']['description'] = {
'old': policy.get('description'),
'new': description
}
param_changes = __utils__['dictdiffer.deep_diff'](policy.get('parameters', {}), parameters or {})
if param_changes:
ret['changes']['parameters'] = param_changes
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be updated.'.format(name)
ret['result'] = None
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': name,
'scope': scope,
'definition_name': definition_name,
'type': assignment_type,
'display_name': display_name,
'description': description,
'parameters': parameters,
}
}
if __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be created.'.format(name)
ret['result'] = None
return ret
if isinstance(parameters, dict):
parameters = json.loads(json.dumps(parameters))
policy_kwargs = kwargs.copy()
policy_kwargs.update(connection_auth)
policy = __salt__['azurearm_resource.policy_assignment_create'](
name=name,
scope=scope,
definition_name=definition_name,
type=assignment_type,
display_name=display_name,
description=description,
parameters=parameters,
**policy_kwargs
)
if 'error' not in policy:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create policy assignment {0}! ({1})'.format(name, policy.get('error'))
return ret
def policy_assignment_absent(name, scope, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a policy assignment does not exist in the provided scope.
:param name:
Name of the policy assignment.
:param scope:
The scope of the policy assignment.
connection_auth
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_assignment_get'](
name,
scope,
azurearm_log_level='info',
**connection_auth
)
if 'error' in policy:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': policy,
'new': {},
}
return ret
deleted = __salt__['azurearm_resource.policy_assignment_delete'](name, scope, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} has been deleted.'.format(name)
ret['changes'] = {
'old': policy,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete policy assignment {0}!'.format(name)
return ret
|
saltstack/salt
|
salt/states/azurearm_resource.py
|
resource_group_absent
|
python
|
def resource_group_absent(name, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a resource group does not exist in the current subscription.
:param name:
Name of the resource group.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
group = {}
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if not present:
ret['result'] = True
ret['comment'] = 'Resource group {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
ret['comment'] = 'Resource group {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': group,
'new': {},
}
return ret
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
deleted = __salt__['azurearm_resource.resource_group_delete'](name, **connection_auth)
if deleted:
present = False
else:
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if not present:
ret['result'] = True
ret['comment'] = 'Resource group {0} has been deleted.'.format(name)
ret['changes'] = {
'old': group,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete resource group {0}!'.format(name)
return ret
|
.. versionadded:: 2019.2.0
Ensure a resource group does not exist in the current subscription.
:param name:
Name of the resource group.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_resource.py#L213-L275
| null |
# -*- coding: utf-8 -*-
'''
Azure (ARM) Resource State Module
.. versionadded:: 2019.2.0
:maintainer: <devops@decisionlab.io>
:maturity: new
:depends:
* `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0
* `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8
* `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0
* `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0
* `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1
* `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0
* `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0
* `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0
* `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3
* `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21
:platform: linux
:configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of
keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication
parameters are sensitive, it's recommended to pass them to the states via pillar.
Required provider parameters:
if using username and password:
* ``subscription_id``
* ``username``
* ``password``
if using a service principal:
* ``subscription_id``
* ``tenant``
* ``client_id``
* ``secret``
Optional provider parameters:
**cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values:
* ``AZURE_PUBLIC_CLOUD`` (default)
* ``AZURE_CHINA_CLOUD``
* ``AZURE_US_GOV_CLOUD``
* ``AZURE_GERMAN_CLOUD``
Example Pillar for Azure Resource Manager authentication:
.. code-block:: yaml
azurearm:
user_pass_auth:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
username: fletch
password: 123pass
mysubscription:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
secret: XXXXXXXXXXXXXXXXXXXXXXXX
cloud_environment: AZURE_PUBLIC_CLOUD
Example states using Azure Resource Manager authentication:
.. code-block:: jinja
{% set profile = salt['pillar.get']('azurearm:mysubscription') %}
Ensure resource group exists:
azurearm_resource.resource_group_present:
- name: my_rg
- location: westus
- tags:
how_awesome: very
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
Ensure resource group is absent:
azurearm_resource.resource_group_absent:
- name: other_rg
- connection_auth: {{ profile }}
'''
# Import Python libs
from __future__ import absolute_import
import json
import logging
# Import Salt libs
import salt.utils.files
__virtualname__ = 'azurearm_resource'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only make this state available if the azurearm_resource module is available.
'''
return __virtualname__ if 'azurearm_resource.resource_group_check_existence' in __salt__ else False
def resource_group_present(name, location, managed_by=None, tags=None, connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a resource group exists.
:param name:
Name of the resource group.
:param location:
The Azure location in which to create the resource group. This value cannot be updated once
the resource group is created.
:param managed_by:
The ID of the resource that manages this resource group. This value cannot be updated once
the resource group is created.
:param tags:
A dictionary of strings can be passed as tag metadata to the resource group object.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure resource group exists:
azurearm_resource.resource_group_present:
- name: group1
- location: eastus
- tags:
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
group = {}
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if present:
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
ret['changes'] = __utils__['dictdiffer.deep_diff'](group.get('tags', {}), tags or {})
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Resource group {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Resource group {0} tags would be updated.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': group.get('tags', {}),
'new': tags
}
return ret
elif __opts__['test']:
ret['comment'] = 'Resource group {0} would be created.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': {},
'new': {
'name': name,
'location': location,
'managed_by': managed_by,
'tags': tags,
}
}
return ret
group_kwargs = kwargs.copy()
group_kwargs.update(connection_auth)
group = __salt__['azurearm_resource.resource_group_create_or_update'](
name,
location,
managed_by=managed_by,
tags=tags,
**group_kwargs
)
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if present:
ret['result'] = True
ret['comment'] = 'Resource group {0} has been created.'.format(name)
ret['changes'] = {
'old': {},
'new': group
}
return ret
ret['comment'] = 'Failed to create resource group {0}! ({1})'.format(name, group.get('error'))
return ret
def policy_definition_present(name, policy_rule=None, policy_type=None, mode=None, display_name=None, description=None,
metadata=None, parameters=None, policy_rule_json=None, policy_rule_file=None,
template='jinja', source_hash=None, source_hash_name=None, skip_verify=False,
connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a security policy definition exists.
:param name:
Name of the policy definition.
:param policy_rule:
A YAML dictionary defining the policy rule. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used.
:param policy_rule_json:
A text field defining the entirety of a policy definition in JSON. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used. Note that the `name` field in the JSON will override the
``name`` parameter in the state.
:param policy_rule_file:
The source of a JSON file defining the entirety of a policy definition. See `Azure Policy Definition
documentation <https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for
details on the structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required,
in that order of precedence for use if multiple parameters are used. Note that the `name` field in the JSON
will override the ``name`` parameter in the state.
:param skip_verify:
Used for the ``policy_rule_file`` parameter. If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored.
:param source_hash:
This can be a source hash string or the URI of a file that contains source hash strings.
:param source_hash_name:
When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the
filename/URI associated with that hash.
:param policy_type:
The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom. Only used with the
``policy_rule`` parameter.
:param mode:
The policy definition mode. Possible values are NotSpecified, Indexed, and All. Only used with the
``policy_rule`` parameter.
:param display_name:
The display name of the policy definition. Only used with the ``policy_rule`` parameter.
:param description:
The policy definition description. Only used with the ``policy_rule`` parameter.
:param metadata:
The policy definition metadata defined as a dictionary. Only used with the ``policy_rule`` parameter.
:param parameters:
Required dictionary if a parameter is used in the policy rule. Only used with the ``policy_rule`` parameter.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy definition exists:
azurearm_resource.policy_definition_present:
- name: testpolicy
- display_name: Test Policy
- description: Test policy for testing policies.
- policy_rule:
if:
allOf:
- equals: Microsoft.Compute/virtualMachines/write
source: action
- field: location
in:
- eastus
- eastus2
- centralus
then:
effect: deny
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
if not policy_rule and not policy_rule_json and not policy_rule_file:
ret['comment'] = 'One of "policy_rule", "policy_rule_json", or "policy_rule_file" is required!'
return ret
if sum(x is not None for x in [policy_rule, policy_rule_json, policy_rule_file]) > 1:
ret['comment'] = 'Only one of "policy_rule", "policy_rule_json", or "policy_rule_file" is allowed!'
return ret
if ((policy_rule_json or policy_rule_file) and
(policy_type or mode or display_name or description or metadata or parameters)):
ret['comment'] = 'Policy definitions cannot be passed when "policy_rule_json" or "policy_rule_file" is defined!'
return ret
temp_rule = {}
if policy_rule_json:
try:
temp_rule = json.loads(policy_rule_json)
except Exception as exc:
ret['comment'] = 'Unable to load policy rule json! ({0})'.format(exc)
return ret
elif policy_rule_file:
try:
# pylint: disable=unused-variable
sfn, source_sum, comment_ = __salt__['file.get_managed'](
None,
template,
policy_rule_file,
source_hash,
source_hash_name,
None,
None,
None,
__env__,
None,
None,
skip_verify=skip_verify,
**kwargs
)
except Exception as exc:
ret['comment'] = 'Unable to locate policy rule file "{0}"! ({1})'.format(policy_rule_file, exc)
return ret
if not sfn:
ret['comment'] = 'Unable to locate policy rule file "{0}"!)'.format(policy_rule_file)
return ret
try:
with salt.utils.files.fopen(sfn, 'r') as prf:
temp_rule = json.load(prf)
except Exception as exc:
ret['comment'] = 'Unable to load policy rule file "{0}"! ({1})'.format(policy_rule_file, exc)
return ret
if sfn:
salt.utils.files.remove(sfn)
policy_name = name
if policy_rule_json or policy_rule_file:
if temp_rule.get('name'):
policy_name = temp_rule.get('name')
policy_rule = temp_rule.get('properties', {}).get('policyRule')
policy_type = temp_rule.get('properties', {}).get('policyType')
mode = temp_rule.get('properties', {}).get('mode')
display_name = temp_rule.get('properties', {}).get('displayName')
description = temp_rule.get('properties', {}).get('description')
metadata = temp_rule.get('properties', {}).get('metadata')
parameters = temp_rule.get('properties', {}).get('parameters')
policy = __salt__['azurearm_resource.policy_definition_get'](name, azurearm_log_level='info', **connection_auth)
if 'error' not in policy:
if policy_type and policy_type.lower() != policy.get('policy_type', '').lower():
ret['changes']['policy_type'] = {
'old': policy.get('policy_type'),
'new': policy_type
}
if (mode or '').lower() != policy.get('mode', '').lower():
ret['changes']['mode'] = {
'old': policy.get('mode'),
'new': mode
}
if (display_name or '').lower() != policy.get('display_name', '').lower():
ret['changes']['display_name'] = {
'old': policy.get('display_name'),
'new': display_name
}
if (description or '').lower() != policy.get('description', '').lower():
ret['changes']['description'] = {
'old': policy.get('description'),
'new': description
}
rule_changes = __utils__['dictdiffer.deep_diff'](policy.get('policy_rule', {}), policy_rule or {})
if rule_changes:
ret['changes']['policy_rule'] = rule_changes
meta_changes = __utils__['dictdiffer.deep_diff'](policy.get('metadata', {}), metadata or {})
if meta_changes:
ret['changes']['metadata'] = meta_changes
param_changes = __utils__['dictdiffer.deep_diff'](policy.get('parameters', {}), parameters or {})
if param_changes:
ret['changes']['parameters'] = param_changes
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Policy definition {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy definition {0} would be updated.'.format(name)
ret['result'] = None
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': policy_name,
'policy_type': policy_type,
'mode': mode,
'display_name': display_name,
'description': description,
'metadata': metadata,
'parameters': parameters,
'policy_rule': policy_rule,
}
}
if __opts__['test']:
ret['comment'] = 'Policy definition {0} would be created.'.format(name)
ret['result'] = None
return ret
# Convert OrderedDict to dict
if isinstance(metadata, dict):
metadata = json.loads(json.dumps(metadata))
if isinstance(parameters, dict):
parameters = json.loads(json.dumps(parameters))
policy_kwargs = kwargs.copy()
policy_kwargs.update(connection_auth)
policy = __salt__['azurearm_resource.policy_definition_create_or_update'](
name=policy_name,
policy_rule=policy_rule,
policy_type=policy_type,
mode=mode,
display_name=display_name,
description=description,
metadata=metadata,
parameters=parameters,
**policy_kwargs
)
if 'error' not in policy:
ret['result'] = True
ret['comment'] = 'Policy definition {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create policy definition {0}! ({1})'.format(name, policy.get('error'))
return ret
def policy_definition_absent(name, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a policy definition does not exist in the current subscription.
:param name:
Name of the policy definition.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_definition_get'](name, azurearm_log_level='info', **connection_auth)
if 'error' in policy:
ret['result'] = True
ret['comment'] = 'Policy definition {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Policy definition {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': policy,
'new': {},
}
return ret
deleted = __salt__['azurearm_resource.policy_definition_delete'](name, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Policy definition {0} has been deleted.'.format(name)
ret['changes'] = {
'old': policy,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete policy definition {0}!'.format(name)
return ret
def policy_assignment_present(name, scope, definition_name, display_name=None, description=None, assignment_type=None,
parameters=None, connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a security policy assignment exists.
:param name:
Name of the policy assignment.
:param scope:
The scope of the policy assignment.
:param definition_name:
The name of the policy definition to assign.
:param display_name:
The display name of the policy assignment.
:param description:
The policy assignment description.
:param assignment_type:
The type of policy assignment.
:param parameters:
Required dictionary if a parameter is used in the policy rule.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy assignment exists:
azurearm_resource.policy_assignment_present:
- name: testassign
- scope: /subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852
- definition_name: testpolicy
- display_name: Test Assignment
- description: Test assignment for testing assignments.
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_assignment_get'](
name,
scope,
azurearm_log_level='info',
**connection_auth
)
if 'error' not in policy:
if assignment_type and assignment_type.lower() != policy.get('type', '').lower():
ret['changes']['type'] = {
'old': policy.get('type'),
'new': assignment_type
}
if scope.lower() != policy['scope'].lower():
ret['changes']['scope'] = {
'old': policy['scope'],
'new': scope
}
pa_name = policy['policy_definition_id'].split('/')[-1]
if definition_name.lower() != pa_name.lower():
ret['changes']['definition_name'] = {
'old': pa_name,
'new': definition_name
}
if (display_name or '').lower() != policy.get('display_name', '').lower():
ret['changes']['display_name'] = {
'old': policy.get('display_name'),
'new': display_name
}
if (description or '').lower() != policy.get('description', '').lower():
ret['changes']['description'] = {
'old': policy.get('description'),
'new': description
}
param_changes = __utils__['dictdiffer.deep_diff'](policy.get('parameters', {}), parameters or {})
if param_changes:
ret['changes']['parameters'] = param_changes
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be updated.'.format(name)
ret['result'] = None
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': name,
'scope': scope,
'definition_name': definition_name,
'type': assignment_type,
'display_name': display_name,
'description': description,
'parameters': parameters,
}
}
if __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be created.'.format(name)
ret['result'] = None
return ret
if isinstance(parameters, dict):
parameters = json.loads(json.dumps(parameters))
policy_kwargs = kwargs.copy()
policy_kwargs.update(connection_auth)
policy = __salt__['azurearm_resource.policy_assignment_create'](
name=name,
scope=scope,
definition_name=definition_name,
type=assignment_type,
display_name=display_name,
description=description,
parameters=parameters,
**policy_kwargs
)
if 'error' not in policy:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create policy assignment {0}! ({1})'.format(name, policy.get('error'))
return ret
def policy_assignment_absent(name, scope, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a policy assignment does not exist in the provided scope.
:param name:
Name of the policy assignment.
:param scope:
The scope of the policy assignment.
connection_auth
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_assignment_get'](
name,
scope,
azurearm_log_level='info',
**connection_auth
)
if 'error' in policy:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': policy,
'new': {},
}
return ret
deleted = __salt__['azurearm_resource.policy_assignment_delete'](name, scope, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} has been deleted.'.format(name)
ret['changes'] = {
'old': policy,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete policy assignment {0}!'.format(name)
return ret
|
saltstack/salt
|
salt/states/azurearm_resource.py
|
policy_definition_present
|
python
|
def policy_definition_present(name, policy_rule=None, policy_type=None, mode=None, display_name=None, description=None,
metadata=None, parameters=None, policy_rule_json=None, policy_rule_file=None,
template='jinja', source_hash=None, source_hash_name=None, skip_verify=False,
connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a security policy definition exists.
:param name:
Name of the policy definition.
:param policy_rule:
A YAML dictionary defining the policy rule. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used.
:param policy_rule_json:
A text field defining the entirety of a policy definition in JSON. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used. Note that the `name` field in the JSON will override the
``name`` parameter in the state.
:param policy_rule_file:
The source of a JSON file defining the entirety of a policy definition. See `Azure Policy Definition
documentation <https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for
details on the structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required,
in that order of precedence for use if multiple parameters are used. Note that the `name` field in the JSON
will override the ``name`` parameter in the state.
:param skip_verify:
Used for the ``policy_rule_file`` parameter. If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored.
:param source_hash:
This can be a source hash string or the URI of a file that contains source hash strings.
:param source_hash_name:
When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the
filename/URI associated with that hash.
:param policy_type:
The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom. Only used with the
``policy_rule`` parameter.
:param mode:
The policy definition mode. Possible values are NotSpecified, Indexed, and All. Only used with the
``policy_rule`` parameter.
:param display_name:
The display name of the policy definition. Only used with the ``policy_rule`` parameter.
:param description:
The policy definition description. Only used with the ``policy_rule`` parameter.
:param metadata:
The policy definition metadata defined as a dictionary. Only used with the ``policy_rule`` parameter.
:param parameters:
Required dictionary if a parameter is used in the policy rule. Only used with the ``policy_rule`` parameter.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy definition exists:
azurearm_resource.policy_definition_present:
- name: testpolicy
- display_name: Test Policy
- description: Test policy for testing policies.
- policy_rule:
if:
allOf:
- equals: Microsoft.Compute/virtualMachines/write
source: action
- field: location
in:
- eastus
- eastus2
- centralus
then:
effect: deny
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
if not policy_rule and not policy_rule_json and not policy_rule_file:
ret['comment'] = 'One of "policy_rule", "policy_rule_json", or "policy_rule_file" is required!'
return ret
if sum(x is not None for x in [policy_rule, policy_rule_json, policy_rule_file]) > 1:
ret['comment'] = 'Only one of "policy_rule", "policy_rule_json", or "policy_rule_file" is allowed!'
return ret
if ((policy_rule_json or policy_rule_file) and
(policy_type or mode or display_name or description or metadata or parameters)):
ret['comment'] = 'Policy definitions cannot be passed when "policy_rule_json" or "policy_rule_file" is defined!'
return ret
temp_rule = {}
if policy_rule_json:
try:
temp_rule = json.loads(policy_rule_json)
except Exception as exc:
ret['comment'] = 'Unable to load policy rule json! ({0})'.format(exc)
return ret
elif policy_rule_file:
try:
# pylint: disable=unused-variable
sfn, source_sum, comment_ = __salt__['file.get_managed'](
None,
template,
policy_rule_file,
source_hash,
source_hash_name,
None,
None,
None,
__env__,
None,
None,
skip_verify=skip_verify,
**kwargs
)
except Exception as exc:
ret['comment'] = 'Unable to locate policy rule file "{0}"! ({1})'.format(policy_rule_file, exc)
return ret
if not sfn:
ret['comment'] = 'Unable to locate policy rule file "{0}"!)'.format(policy_rule_file)
return ret
try:
with salt.utils.files.fopen(sfn, 'r') as prf:
temp_rule = json.load(prf)
except Exception as exc:
ret['comment'] = 'Unable to load policy rule file "{0}"! ({1})'.format(policy_rule_file, exc)
return ret
if sfn:
salt.utils.files.remove(sfn)
policy_name = name
if policy_rule_json or policy_rule_file:
if temp_rule.get('name'):
policy_name = temp_rule.get('name')
policy_rule = temp_rule.get('properties', {}).get('policyRule')
policy_type = temp_rule.get('properties', {}).get('policyType')
mode = temp_rule.get('properties', {}).get('mode')
display_name = temp_rule.get('properties', {}).get('displayName')
description = temp_rule.get('properties', {}).get('description')
metadata = temp_rule.get('properties', {}).get('metadata')
parameters = temp_rule.get('properties', {}).get('parameters')
policy = __salt__['azurearm_resource.policy_definition_get'](name, azurearm_log_level='info', **connection_auth)
if 'error' not in policy:
if policy_type and policy_type.lower() != policy.get('policy_type', '').lower():
ret['changes']['policy_type'] = {
'old': policy.get('policy_type'),
'new': policy_type
}
if (mode or '').lower() != policy.get('mode', '').lower():
ret['changes']['mode'] = {
'old': policy.get('mode'),
'new': mode
}
if (display_name or '').lower() != policy.get('display_name', '').lower():
ret['changes']['display_name'] = {
'old': policy.get('display_name'),
'new': display_name
}
if (description or '').lower() != policy.get('description', '').lower():
ret['changes']['description'] = {
'old': policy.get('description'),
'new': description
}
rule_changes = __utils__['dictdiffer.deep_diff'](policy.get('policy_rule', {}), policy_rule or {})
if rule_changes:
ret['changes']['policy_rule'] = rule_changes
meta_changes = __utils__['dictdiffer.deep_diff'](policy.get('metadata', {}), metadata or {})
if meta_changes:
ret['changes']['metadata'] = meta_changes
param_changes = __utils__['dictdiffer.deep_diff'](policy.get('parameters', {}), parameters or {})
if param_changes:
ret['changes']['parameters'] = param_changes
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Policy definition {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy definition {0} would be updated.'.format(name)
ret['result'] = None
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': policy_name,
'policy_type': policy_type,
'mode': mode,
'display_name': display_name,
'description': description,
'metadata': metadata,
'parameters': parameters,
'policy_rule': policy_rule,
}
}
if __opts__['test']:
ret['comment'] = 'Policy definition {0} would be created.'.format(name)
ret['result'] = None
return ret
# Convert OrderedDict to dict
if isinstance(metadata, dict):
metadata = json.loads(json.dumps(metadata))
if isinstance(parameters, dict):
parameters = json.loads(json.dumps(parameters))
policy_kwargs = kwargs.copy()
policy_kwargs.update(connection_auth)
policy = __salt__['azurearm_resource.policy_definition_create_or_update'](
name=policy_name,
policy_rule=policy_rule,
policy_type=policy_type,
mode=mode,
display_name=display_name,
description=description,
metadata=metadata,
parameters=parameters,
**policy_kwargs
)
if 'error' not in policy:
ret['result'] = True
ret['comment'] = 'Policy definition {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create policy definition {0}! ({1})'.format(name, policy.get('error'))
return ret
|
.. versionadded:: 2019.2.0
Ensure a security policy definition exists.
:param name:
Name of the policy definition.
:param policy_rule:
A YAML dictionary defining the policy rule. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used.
:param policy_rule_json:
A text field defining the entirety of a policy definition in JSON. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used. Note that the `name` field in the JSON will override the
``name`` parameter in the state.
:param policy_rule_file:
The source of a JSON file defining the entirety of a policy definition. See `Azure Policy Definition
documentation <https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for
details on the structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required,
in that order of precedence for use if multiple parameters are used. Note that the `name` field in the JSON
will override the ``name`` parameter in the state.
:param skip_verify:
Used for the ``policy_rule_file`` parameter. If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored.
:param source_hash:
This can be a source hash string or the URI of a file that contains source hash strings.
:param source_hash_name:
When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the
filename/URI associated with that hash.
:param policy_type:
The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom. Only used with the
``policy_rule`` parameter.
:param mode:
The policy definition mode. Possible values are NotSpecified, Indexed, and All. Only used with the
``policy_rule`` parameter.
:param display_name:
The display name of the policy definition. Only used with the ``policy_rule`` parameter.
:param description:
The policy definition description. Only used with the ``policy_rule`` parameter.
:param metadata:
The policy definition metadata defined as a dictionary. Only used with the ``policy_rule`` parameter.
:param parameters:
Required dictionary if a parameter is used in the policy rule. Only used with the ``policy_rule`` parameter.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy definition exists:
azurearm_resource.policy_definition_present:
- name: testpolicy
- display_name: Test Policy
- description: Test policy for testing policies.
- policy_rule:
if:
allOf:
- equals: Microsoft.Compute/virtualMachines/write
source: action
- field: location
in:
- eastus
- eastus2
- centralus
then:
effect: deny
- connection_auth: {{ profile }}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_resource.py#L278-L544
| null |
# -*- coding: utf-8 -*-
'''
Azure (ARM) Resource State Module
.. versionadded:: 2019.2.0
:maintainer: <devops@decisionlab.io>
:maturity: new
:depends:
* `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0
* `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8
* `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0
* `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0
* `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1
* `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0
* `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0
* `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0
* `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3
* `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21
:platform: linux
:configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of
keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication
parameters are sensitive, it's recommended to pass them to the states via pillar.
Required provider parameters:
if using username and password:
* ``subscription_id``
* ``username``
* ``password``
if using a service principal:
* ``subscription_id``
* ``tenant``
* ``client_id``
* ``secret``
Optional provider parameters:
**cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values:
* ``AZURE_PUBLIC_CLOUD`` (default)
* ``AZURE_CHINA_CLOUD``
* ``AZURE_US_GOV_CLOUD``
* ``AZURE_GERMAN_CLOUD``
Example Pillar for Azure Resource Manager authentication:
.. code-block:: yaml
azurearm:
user_pass_auth:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
username: fletch
password: 123pass
mysubscription:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
secret: XXXXXXXXXXXXXXXXXXXXXXXX
cloud_environment: AZURE_PUBLIC_CLOUD
Example states using Azure Resource Manager authentication:
.. code-block:: jinja
{% set profile = salt['pillar.get']('azurearm:mysubscription') %}
Ensure resource group exists:
azurearm_resource.resource_group_present:
- name: my_rg
- location: westus
- tags:
how_awesome: very
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
Ensure resource group is absent:
azurearm_resource.resource_group_absent:
- name: other_rg
- connection_auth: {{ profile }}
'''
# Import Python libs
from __future__ import absolute_import
import json
import logging
# Import Salt libs
import salt.utils.files
__virtualname__ = 'azurearm_resource'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only make this state available if the azurearm_resource module is available.
'''
return __virtualname__ if 'azurearm_resource.resource_group_check_existence' in __salt__ else False
def resource_group_present(name, location, managed_by=None, tags=None, connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a resource group exists.
:param name:
Name of the resource group.
:param location:
The Azure location in which to create the resource group. This value cannot be updated once
the resource group is created.
:param managed_by:
The ID of the resource that manages this resource group. This value cannot be updated once
the resource group is created.
:param tags:
A dictionary of strings can be passed as tag metadata to the resource group object.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure resource group exists:
azurearm_resource.resource_group_present:
- name: group1
- location: eastus
- tags:
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
group = {}
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if present:
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
ret['changes'] = __utils__['dictdiffer.deep_diff'](group.get('tags', {}), tags or {})
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Resource group {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Resource group {0} tags would be updated.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': group.get('tags', {}),
'new': tags
}
return ret
elif __opts__['test']:
ret['comment'] = 'Resource group {0} would be created.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': {},
'new': {
'name': name,
'location': location,
'managed_by': managed_by,
'tags': tags,
}
}
return ret
group_kwargs = kwargs.copy()
group_kwargs.update(connection_auth)
group = __salt__['azurearm_resource.resource_group_create_or_update'](
name,
location,
managed_by=managed_by,
tags=tags,
**group_kwargs
)
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if present:
ret['result'] = True
ret['comment'] = 'Resource group {0} has been created.'.format(name)
ret['changes'] = {
'old': {},
'new': group
}
return ret
ret['comment'] = 'Failed to create resource group {0}! ({1})'.format(name, group.get('error'))
return ret
def resource_group_absent(name, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a resource group does not exist in the current subscription.
:param name:
Name of the resource group.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
group = {}
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if not present:
ret['result'] = True
ret['comment'] = 'Resource group {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
ret['comment'] = 'Resource group {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': group,
'new': {},
}
return ret
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
deleted = __salt__['azurearm_resource.resource_group_delete'](name, **connection_auth)
if deleted:
present = False
else:
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if not present:
ret['result'] = True
ret['comment'] = 'Resource group {0} has been deleted.'.format(name)
ret['changes'] = {
'old': group,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete resource group {0}!'.format(name)
return ret
def policy_definition_absent(name, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a policy definition does not exist in the current subscription.
:param name:
Name of the policy definition.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_definition_get'](name, azurearm_log_level='info', **connection_auth)
if 'error' in policy:
ret['result'] = True
ret['comment'] = 'Policy definition {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Policy definition {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': policy,
'new': {},
}
return ret
deleted = __salt__['azurearm_resource.policy_definition_delete'](name, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Policy definition {0} has been deleted.'.format(name)
ret['changes'] = {
'old': policy,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete policy definition {0}!'.format(name)
return ret
def policy_assignment_present(name, scope, definition_name, display_name=None, description=None, assignment_type=None,
parameters=None, connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a security policy assignment exists.
:param name:
Name of the policy assignment.
:param scope:
The scope of the policy assignment.
:param definition_name:
The name of the policy definition to assign.
:param display_name:
The display name of the policy assignment.
:param description:
The policy assignment description.
:param assignment_type:
The type of policy assignment.
:param parameters:
Required dictionary if a parameter is used in the policy rule.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy assignment exists:
azurearm_resource.policy_assignment_present:
- name: testassign
- scope: /subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852
- definition_name: testpolicy
- display_name: Test Assignment
- description: Test assignment for testing assignments.
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_assignment_get'](
name,
scope,
azurearm_log_level='info',
**connection_auth
)
if 'error' not in policy:
if assignment_type and assignment_type.lower() != policy.get('type', '').lower():
ret['changes']['type'] = {
'old': policy.get('type'),
'new': assignment_type
}
if scope.lower() != policy['scope'].lower():
ret['changes']['scope'] = {
'old': policy['scope'],
'new': scope
}
pa_name = policy['policy_definition_id'].split('/')[-1]
if definition_name.lower() != pa_name.lower():
ret['changes']['definition_name'] = {
'old': pa_name,
'new': definition_name
}
if (display_name or '').lower() != policy.get('display_name', '').lower():
ret['changes']['display_name'] = {
'old': policy.get('display_name'),
'new': display_name
}
if (description or '').lower() != policy.get('description', '').lower():
ret['changes']['description'] = {
'old': policy.get('description'),
'new': description
}
param_changes = __utils__['dictdiffer.deep_diff'](policy.get('parameters', {}), parameters or {})
if param_changes:
ret['changes']['parameters'] = param_changes
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be updated.'.format(name)
ret['result'] = None
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': name,
'scope': scope,
'definition_name': definition_name,
'type': assignment_type,
'display_name': display_name,
'description': description,
'parameters': parameters,
}
}
if __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be created.'.format(name)
ret['result'] = None
return ret
if isinstance(parameters, dict):
parameters = json.loads(json.dumps(parameters))
policy_kwargs = kwargs.copy()
policy_kwargs.update(connection_auth)
policy = __salt__['azurearm_resource.policy_assignment_create'](
name=name,
scope=scope,
definition_name=definition_name,
type=assignment_type,
display_name=display_name,
description=description,
parameters=parameters,
**policy_kwargs
)
if 'error' not in policy:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create policy assignment {0}! ({1})'.format(name, policy.get('error'))
return ret
def policy_assignment_absent(name, scope, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a policy assignment does not exist in the provided scope.
:param name:
Name of the policy assignment.
:param scope:
The scope of the policy assignment.
connection_auth
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_assignment_get'](
name,
scope,
azurearm_log_level='info',
**connection_auth
)
if 'error' in policy:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': policy,
'new': {},
}
return ret
deleted = __salt__['azurearm_resource.policy_assignment_delete'](name, scope, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} has been deleted.'.format(name)
ret['changes'] = {
'old': policy,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete policy assignment {0}!'.format(name)
return ret
|
saltstack/salt
|
salt/states/azurearm_resource.py
|
policy_definition_absent
|
python
|
def policy_definition_absent(name, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a policy definition does not exist in the current subscription.
:param name:
Name of the policy definition.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_definition_get'](name, azurearm_log_level='info', **connection_auth)
if 'error' in policy:
ret['result'] = True
ret['comment'] = 'Policy definition {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Policy definition {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': policy,
'new': {},
}
return ret
deleted = __salt__['azurearm_resource.policy_definition_delete'](name, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Policy definition {0} has been deleted.'.format(name)
ret['changes'] = {
'old': policy,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete policy definition {0}!'.format(name)
return ret
|
.. versionadded:: 2019.2.0
Ensure a policy definition does not exist in the current subscription.
:param name:
Name of the policy definition.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_resource.py#L547-L599
| null |
# -*- coding: utf-8 -*-
'''
Azure (ARM) Resource State Module
.. versionadded:: 2019.2.0
:maintainer: <devops@decisionlab.io>
:maturity: new
:depends:
* `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0
* `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8
* `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0
* `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0
* `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1
* `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0
* `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0
* `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0
* `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3
* `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21
:platform: linux
:configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of
keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication
parameters are sensitive, it's recommended to pass them to the states via pillar.
Required provider parameters:
if using username and password:
* ``subscription_id``
* ``username``
* ``password``
if using a service principal:
* ``subscription_id``
* ``tenant``
* ``client_id``
* ``secret``
Optional provider parameters:
**cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values:
* ``AZURE_PUBLIC_CLOUD`` (default)
* ``AZURE_CHINA_CLOUD``
* ``AZURE_US_GOV_CLOUD``
* ``AZURE_GERMAN_CLOUD``
Example Pillar for Azure Resource Manager authentication:
.. code-block:: yaml
azurearm:
user_pass_auth:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
username: fletch
password: 123pass
mysubscription:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
secret: XXXXXXXXXXXXXXXXXXXXXXXX
cloud_environment: AZURE_PUBLIC_CLOUD
Example states using Azure Resource Manager authentication:
.. code-block:: jinja
{% set profile = salt['pillar.get']('azurearm:mysubscription') %}
Ensure resource group exists:
azurearm_resource.resource_group_present:
- name: my_rg
- location: westus
- tags:
how_awesome: very
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
Ensure resource group is absent:
azurearm_resource.resource_group_absent:
- name: other_rg
- connection_auth: {{ profile }}
'''
# Import Python libs
from __future__ import absolute_import
import json
import logging
# Import Salt libs
import salt.utils.files
__virtualname__ = 'azurearm_resource'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only make this state available if the azurearm_resource module is available.
'''
return __virtualname__ if 'azurearm_resource.resource_group_check_existence' in __salt__ else False
def resource_group_present(name, location, managed_by=None, tags=None, connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a resource group exists.
:param name:
Name of the resource group.
:param location:
The Azure location in which to create the resource group. This value cannot be updated once
the resource group is created.
:param managed_by:
The ID of the resource that manages this resource group. This value cannot be updated once
the resource group is created.
:param tags:
A dictionary of strings can be passed as tag metadata to the resource group object.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure resource group exists:
azurearm_resource.resource_group_present:
- name: group1
- location: eastus
- tags:
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
group = {}
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if present:
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
ret['changes'] = __utils__['dictdiffer.deep_diff'](group.get('tags', {}), tags or {})
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Resource group {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Resource group {0} tags would be updated.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': group.get('tags', {}),
'new': tags
}
return ret
elif __opts__['test']:
ret['comment'] = 'Resource group {0} would be created.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': {},
'new': {
'name': name,
'location': location,
'managed_by': managed_by,
'tags': tags,
}
}
return ret
group_kwargs = kwargs.copy()
group_kwargs.update(connection_auth)
group = __salt__['azurearm_resource.resource_group_create_or_update'](
name,
location,
managed_by=managed_by,
tags=tags,
**group_kwargs
)
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if present:
ret['result'] = True
ret['comment'] = 'Resource group {0} has been created.'.format(name)
ret['changes'] = {
'old': {},
'new': group
}
return ret
ret['comment'] = 'Failed to create resource group {0}! ({1})'.format(name, group.get('error'))
return ret
def resource_group_absent(name, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a resource group does not exist in the current subscription.
:param name:
Name of the resource group.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
group = {}
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if not present:
ret['result'] = True
ret['comment'] = 'Resource group {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
ret['comment'] = 'Resource group {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': group,
'new': {},
}
return ret
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
deleted = __salt__['azurearm_resource.resource_group_delete'](name, **connection_auth)
if deleted:
present = False
else:
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if not present:
ret['result'] = True
ret['comment'] = 'Resource group {0} has been deleted.'.format(name)
ret['changes'] = {
'old': group,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete resource group {0}!'.format(name)
return ret
def policy_definition_present(name, policy_rule=None, policy_type=None, mode=None, display_name=None, description=None,
metadata=None, parameters=None, policy_rule_json=None, policy_rule_file=None,
template='jinja', source_hash=None, source_hash_name=None, skip_verify=False,
connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a security policy definition exists.
:param name:
Name of the policy definition.
:param policy_rule:
A YAML dictionary defining the policy rule. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used.
:param policy_rule_json:
A text field defining the entirety of a policy definition in JSON. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used. Note that the `name` field in the JSON will override the
``name`` parameter in the state.
:param policy_rule_file:
The source of a JSON file defining the entirety of a policy definition. See `Azure Policy Definition
documentation <https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for
details on the structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required,
in that order of precedence for use if multiple parameters are used. Note that the `name` field in the JSON
will override the ``name`` parameter in the state.
:param skip_verify:
Used for the ``policy_rule_file`` parameter. If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored.
:param source_hash:
This can be a source hash string or the URI of a file that contains source hash strings.
:param source_hash_name:
When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the
filename/URI associated with that hash.
:param policy_type:
The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom. Only used with the
``policy_rule`` parameter.
:param mode:
The policy definition mode. Possible values are NotSpecified, Indexed, and All. Only used with the
``policy_rule`` parameter.
:param display_name:
The display name of the policy definition. Only used with the ``policy_rule`` parameter.
:param description:
The policy definition description. Only used with the ``policy_rule`` parameter.
:param metadata:
The policy definition metadata defined as a dictionary. Only used with the ``policy_rule`` parameter.
:param parameters:
Required dictionary if a parameter is used in the policy rule. Only used with the ``policy_rule`` parameter.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy definition exists:
azurearm_resource.policy_definition_present:
- name: testpolicy
- display_name: Test Policy
- description: Test policy for testing policies.
- policy_rule:
if:
allOf:
- equals: Microsoft.Compute/virtualMachines/write
source: action
- field: location
in:
- eastus
- eastus2
- centralus
then:
effect: deny
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
if not policy_rule and not policy_rule_json and not policy_rule_file:
ret['comment'] = 'One of "policy_rule", "policy_rule_json", or "policy_rule_file" is required!'
return ret
if sum(x is not None for x in [policy_rule, policy_rule_json, policy_rule_file]) > 1:
ret['comment'] = 'Only one of "policy_rule", "policy_rule_json", or "policy_rule_file" is allowed!'
return ret
if ((policy_rule_json or policy_rule_file) and
(policy_type or mode or display_name or description or metadata or parameters)):
ret['comment'] = 'Policy definitions cannot be passed when "policy_rule_json" or "policy_rule_file" is defined!'
return ret
temp_rule = {}
if policy_rule_json:
try:
temp_rule = json.loads(policy_rule_json)
except Exception as exc:
ret['comment'] = 'Unable to load policy rule json! ({0})'.format(exc)
return ret
elif policy_rule_file:
try:
# pylint: disable=unused-variable
sfn, source_sum, comment_ = __salt__['file.get_managed'](
None,
template,
policy_rule_file,
source_hash,
source_hash_name,
None,
None,
None,
__env__,
None,
None,
skip_verify=skip_verify,
**kwargs
)
except Exception as exc:
ret['comment'] = 'Unable to locate policy rule file "{0}"! ({1})'.format(policy_rule_file, exc)
return ret
if not sfn:
ret['comment'] = 'Unable to locate policy rule file "{0}"!)'.format(policy_rule_file)
return ret
try:
with salt.utils.files.fopen(sfn, 'r') as prf:
temp_rule = json.load(prf)
except Exception as exc:
ret['comment'] = 'Unable to load policy rule file "{0}"! ({1})'.format(policy_rule_file, exc)
return ret
if sfn:
salt.utils.files.remove(sfn)
policy_name = name
if policy_rule_json or policy_rule_file:
if temp_rule.get('name'):
policy_name = temp_rule.get('name')
policy_rule = temp_rule.get('properties', {}).get('policyRule')
policy_type = temp_rule.get('properties', {}).get('policyType')
mode = temp_rule.get('properties', {}).get('mode')
display_name = temp_rule.get('properties', {}).get('displayName')
description = temp_rule.get('properties', {}).get('description')
metadata = temp_rule.get('properties', {}).get('metadata')
parameters = temp_rule.get('properties', {}).get('parameters')
policy = __salt__['azurearm_resource.policy_definition_get'](name, azurearm_log_level='info', **connection_auth)
if 'error' not in policy:
if policy_type and policy_type.lower() != policy.get('policy_type', '').lower():
ret['changes']['policy_type'] = {
'old': policy.get('policy_type'),
'new': policy_type
}
if (mode or '').lower() != policy.get('mode', '').lower():
ret['changes']['mode'] = {
'old': policy.get('mode'),
'new': mode
}
if (display_name or '').lower() != policy.get('display_name', '').lower():
ret['changes']['display_name'] = {
'old': policy.get('display_name'),
'new': display_name
}
if (description or '').lower() != policy.get('description', '').lower():
ret['changes']['description'] = {
'old': policy.get('description'),
'new': description
}
rule_changes = __utils__['dictdiffer.deep_diff'](policy.get('policy_rule', {}), policy_rule or {})
if rule_changes:
ret['changes']['policy_rule'] = rule_changes
meta_changes = __utils__['dictdiffer.deep_diff'](policy.get('metadata', {}), metadata or {})
if meta_changes:
ret['changes']['metadata'] = meta_changes
param_changes = __utils__['dictdiffer.deep_diff'](policy.get('parameters', {}), parameters or {})
if param_changes:
ret['changes']['parameters'] = param_changes
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Policy definition {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy definition {0} would be updated.'.format(name)
ret['result'] = None
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': policy_name,
'policy_type': policy_type,
'mode': mode,
'display_name': display_name,
'description': description,
'metadata': metadata,
'parameters': parameters,
'policy_rule': policy_rule,
}
}
if __opts__['test']:
ret['comment'] = 'Policy definition {0} would be created.'.format(name)
ret['result'] = None
return ret
# Convert OrderedDict to dict
if isinstance(metadata, dict):
metadata = json.loads(json.dumps(metadata))
if isinstance(parameters, dict):
parameters = json.loads(json.dumps(parameters))
policy_kwargs = kwargs.copy()
policy_kwargs.update(connection_auth)
policy = __salt__['azurearm_resource.policy_definition_create_or_update'](
name=policy_name,
policy_rule=policy_rule,
policy_type=policy_type,
mode=mode,
display_name=display_name,
description=description,
metadata=metadata,
parameters=parameters,
**policy_kwargs
)
if 'error' not in policy:
ret['result'] = True
ret['comment'] = 'Policy definition {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create policy definition {0}! ({1})'.format(name, policy.get('error'))
return ret
def policy_assignment_present(name, scope, definition_name, display_name=None, description=None, assignment_type=None,
parameters=None, connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a security policy assignment exists.
:param name:
Name of the policy assignment.
:param scope:
The scope of the policy assignment.
:param definition_name:
The name of the policy definition to assign.
:param display_name:
The display name of the policy assignment.
:param description:
The policy assignment description.
:param assignment_type:
The type of policy assignment.
:param parameters:
Required dictionary if a parameter is used in the policy rule.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy assignment exists:
azurearm_resource.policy_assignment_present:
- name: testassign
- scope: /subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852
- definition_name: testpolicy
- display_name: Test Assignment
- description: Test assignment for testing assignments.
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_assignment_get'](
name,
scope,
azurearm_log_level='info',
**connection_auth
)
if 'error' not in policy:
if assignment_type and assignment_type.lower() != policy.get('type', '').lower():
ret['changes']['type'] = {
'old': policy.get('type'),
'new': assignment_type
}
if scope.lower() != policy['scope'].lower():
ret['changes']['scope'] = {
'old': policy['scope'],
'new': scope
}
pa_name = policy['policy_definition_id'].split('/')[-1]
if definition_name.lower() != pa_name.lower():
ret['changes']['definition_name'] = {
'old': pa_name,
'new': definition_name
}
if (display_name or '').lower() != policy.get('display_name', '').lower():
ret['changes']['display_name'] = {
'old': policy.get('display_name'),
'new': display_name
}
if (description or '').lower() != policy.get('description', '').lower():
ret['changes']['description'] = {
'old': policy.get('description'),
'new': description
}
param_changes = __utils__['dictdiffer.deep_diff'](policy.get('parameters', {}), parameters or {})
if param_changes:
ret['changes']['parameters'] = param_changes
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be updated.'.format(name)
ret['result'] = None
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': name,
'scope': scope,
'definition_name': definition_name,
'type': assignment_type,
'display_name': display_name,
'description': description,
'parameters': parameters,
}
}
if __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be created.'.format(name)
ret['result'] = None
return ret
if isinstance(parameters, dict):
parameters = json.loads(json.dumps(parameters))
policy_kwargs = kwargs.copy()
policy_kwargs.update(connection_auth)
policy = __salt__['azurearm_resource.policy_assignment_create'](
name=name,
scope=scope,
definition_name=definition_name,
type=assignment_type,
display_name=display_name,
description=description,
parameters=parameters,
**policy_kwargs
)
if 'error' not in policy:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create policy assignment {0}! ({1})'.format(name, policy.get('error'))
return ret
def policy_assignment_absent(name, scope, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a policy assignment does not exist in the provided scope.
:param name:
Name of the policy assignment.
:param scope:
The scope of the policy assignment.
connection_auth
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_assignment_get'](
name,
scope,
azurearm_log_level='info',
**connection_auth
)
if 'error' in policy:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': policy,
'new': {},
}
return ret
deleted = __salt__['azurearm_resource.policy_assignment_delete'](name, scope, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} has been deleted.'.format(name)
ret['changes'] = {
'old': policy,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete policy assignment {0}!'.format(name)
return ret
|
saltstack/salt
|
salt/states/azurearm_resource.py
|
policy_assignment_present
|
python
|
def policy_assignment_present(name, scope, definition_name, display_name=None, description=None, assignment_type=None,
parameters=None, connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a security policy assignment exists.
:param name:
Name of the policy assignment.
:param scope:
The scope of the policy assignment.
:param definition_name:
The name of the policy definition to assign.
:param display_name:
The display name of the policy assignment.
:param description:
The policy assignment description.
:param assignment_type:
The type of policy assignment.
:param parameters:
Required dictionary if a parameter is used in the policy rule.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy assignment exists:
azurearm_resource.policy_assignment_present:
- name: testassign
- scope: /subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852
- definition_name: testpolicy
- display_name: Test Assignment
- description: Test assignment for testing assignments.
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_assignment_get'](
name,
scope,
azurearm_log_level='info',
**connection_auth
)
if 'error' not in policy:
if assignment_type and assignment_type.lower() != policy.get('type', '').lower():
ret['changes']['type'] = {
'old': policy.get('type'),
'new': assignment_type
}
if scope.lower() != policy['scope'].lower():
ret['changes']['scope'] = {
'old': policy['scope'],
'new': scope
}
pa_name = policy['policy_definition_id'].split('/')[-1]
if definition_name.lower() != pa_name.lower():
ret['changes']['definition_name'] = {
'old': pa_name,
'new': definition_name
}
if (display_name or '').lower() != policy.get('display_name', '').lower():
ret['changes']['display_name'] = {
'old': policy.get('display_name'),
'new': display_name
}
if (description or '').lower() != policy.get('description', '').lower():
ret['changes']['description'] = {
'old': policy.get('description'),
'new': description
}
param_changes = __utils__['dictdiffer.deep_diff'](policy.get('parameters', {}), parameters or {})
if param_changes:
ret['changes']['parameters'] = param_changes
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be updated.'.format(name)
ret['result'] = None
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': name,
'scope': scope,
'definition_name': definition_name,
'type': assignment_type,
'display_name': display_name,
'description': description,
'parameters': parameters,
}
}
if __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be created.'.format(name)
ret['result'] = None
return ret
if isinstance(parameters, dict):
parameters = json.loads(json.dumps(parameters))
policy_kwargs = kwargs.copy()
policy_kwargs.update(connection_auth)
policy = __salt__['azurearm_resource.policy_assignment_create'](
name=name,
scope=scope,
definition_name=definition_name,
type=assignment_type,
display_name=display_name,
description=description,
parameters=parameters,
**policy_kwargs
)
if 'error' not in policy:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create policy assignment {0}! ({1})'.format(name, policy.get('error'))
return ret
|
.. versionadded:: 2019.2.0
Ensure a security policy assignment exists.
:param name:
Name of the policy assignment.
:param scope:
The scope of the policy assignment.
:param definition_name:
The name of the policy definition to assign.
:param display_name:
The display name of the policy assignment.
:param description:
The policy assignment description.
:param assignment_type:
The type of policy assignment.
:param parameters:
Required dictionary if a parameter is used in the policy rule.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy assignment exists:
azurearm_resource.policy_assignment_present:
- name: testassign
- scope: /subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852
- definition_name: testpolicy
- display_name: Test Assignment
- description: Test assignment for testing assignments.
- connection_auth: {{ profile }}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_resource.py#L602-L753
| null |
# -*- coding: utf-8 -*-
'''
Azure (ARM) Resource State Module
.. versionadded:: 2019.2.0
:maintainer: <devops@decisionlab.io>
:maturity: new
:depends:
* `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0
* `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8
* `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0
* `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0
* `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1
* `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0
* `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0
* `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0
* `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3
* `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21
:platform: linux
:configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of
keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication
parameters are sensitive, it's recommended to pass them to the states via pillar.
Required provider parameters:
if using username and password:
* ``subscription_id``
* ``username``
* ``password``
if using a service principal:
* ``subscription_id``
* ``tenant``
* ``client_id``
* ``secret``
Optional provider parameters:
**cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values:
* ``AZURE_PUBLIC_CLOUD`` (default)
* ``AZURE_CHINA_CLOUD``
* ``AZURE_US_GOV_CLOUD``
* ``AZURE_GERMAN_CLOUD``
Example Pillar for Azure Resource Manager authentication:
.. code-block:: yaml
azurearm:
user_pass_auth:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
username: fletch
password: 123pass
mysubscription:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
secret: XXXXXXXXXXXXXXXXXXXXXXXX
cloud_environment: AZURE_PUBLIC_CLOUD
Example states using Azure Resource Manager authentication:
.. code-block:: jinja
{% set profile = salt['pillar.get']('azurearm:mysubscription') %}
Ensure resource group exists:
azurearm_resource.resource_group_present:
- name: my_rg
- location: westus
- tags:
how_awesome: very
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
Ensure resource group is absent:
azurearm_resource.resource_group_absent:
- name: other_rg
- connection_auth: {{ profile }}
'''
# Import Python libs
from __future__ import absolute_import
import json
import logging
# Import Salt libs
import salt.utils.files
__virtualname__ = 'azurearm_resource'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only make this state available if the azurearm_resource module is available.
'''
return __virtualname__ if 'azurearm_resource.resource_group_check_existence' in __salt__ else False
def resource_group_present(name, location, managed_by=None, tags=None, connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a resource group exists.
:param name:
Name of the resource group.
:param location:
The Azure location in which to create the resource group. This value cannot be updated once
the resource group is created.
:param managed_by:
The ID of the resource that manages this resource group. This value cannot be updated once
the resource group is created.
:param tags:
A dictionary of strings can be passed as tag metadata to the resource group object.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure resource group exists:
azurearm_resource.resource_group_present:
- name: group1
- location: eastus
- tags:
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
group = {}
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if present:
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
ret['changes'] = __utils__['dictdiffer.deep_diff'](group.get('tags', {}), tags or {})
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Resource group {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Resource group {0} tags would be updated.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': group.get('tags', {}),
'new': tags
}
return ret
elif __opts__['test']:
ret['comment'] = 'Resource group {0} would be created.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': {},
'new': {
'name': name,
'location': location,
'managed_by': managed_by,
'tags': tags,
}
}
return ret
group_kwargs = kwargs.copy()
group_kwargs.update(connection_auth)
group = __salt__['azurearm_resource.resource_group_create_or_update'](
name,
location,
managed_by=managed_by,
tags=tags,
**group_kwargs
)
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if present:
ret['result'] = True
ret['comment'] = 'Resource group {0} has been created.'.format(name)
ret['changes'] = {
'old': {},
'new': group
}
return ret
ret['comment'] = 'Failed to create resource group {0}! ({1})'.format(name, group.get('error'))
return ret
def resource_group_absent(name, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a resource group does not exist in the current subscription.
:param name:
Name of the resource group.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
group = {}
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if not present:
ret['result'] = True
ret['comment'] = 'Resource group {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
ret['comment'] = 'Resource group {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': group,
'new': {},
}
return ret
group = __salt__['azurearm_resource.resource_group_get'](name, **connection_auth)
deleted = __salt__['azurearm_resource.resource_group_delete'](name, **connection_auth)
if deleted:
present = False
else:
present = __salt__['azurearm_resource.resource_group_check_existence'](name, **connection_auth)
if not present:
ret['result'] = True
ret['comment'] = 'Resource group {0} has been deleted.'.format(name)
ret['changes'] = {
'old': group,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete resource group {0}!'.format(name)
return ret
def policy_definition_present(name, policy_rule=None, policy_type=None, mode=None, display_name=None, description=None,
metadata=None, parameters=None, policy_rule_json=None, policy_rule_file=None,
template='jinja', source_hash=None, source_hash_name=None, skip_verify=False,
connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a security policy definition exists.
:param name:
Name of the policy definition.
:param policy_rule:
A YAML dictionary defining the policy rule. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used.
:param policy_rule_json:
A text field defining the entirety of a policy definition in JSON. See `Azure Policy Definition documentation
<https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for details on the
structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required, in that order of
precedence for use if multiple parameters are used. Note that the `name` field in the JSON will override the
``name`` parameter in the state.
:param policy_rule_file:
The source of a JSON file defining the entirety of a policy definition. See `Azure Policy Definition
documentation <https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_ for
details on the structure. One of ``policy_rule``, ``policy_rule_json``, or ``policy_rule_file`` is required,
in that order of precedence for use if multiple parameters are used. Note that the `name` field in the JSON
will override the ``name`` parameter in the state.
:param skip_verify:
Used for the ``policy_rule_file`` parameter. If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored.
:param source_hash:
This can be a source hash string or the URI of a file that contains source hash strings.
:param source_hash_name:
When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the
filename/URI associated with that hash.
:param policy_type:
The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom. Only used with the
``policy_rule`` parameter.
:param mode:
The policy definition mode. Possible values are NotSpecified, Indexed, and All. Only used with the
``policy_rule`` parameter.
:param display_name:
The display name of the policy definition. Only used with the ``policy_rule`` parameter.
:param description:
The policy definition description. Only used with the ``policy_rule`` parameter.
:param metadata:
The policy definition metadata defined as a dictionary. Only used with the ``policy_rule`` parameter.
:param parameters:
Required dictionary if a parameter is used in the policy rule. Only used with the ``policy_rule`` parameter.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure policy definition exists:
azurearm_resource.policy_definition_present:
- name: testpolicy
- display_name: Test Policy
- description: Test policy for testing policies.
- policy_rule:
if:
allOf:
- equals: Microsoft.Compute/virtualMachines/write
source: action
- field: location
in:
- eastus
- eastus2
- centralus
then:
effect: deny
- connection_auth: {{ profile }}
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
if not policy_rule and not policy_rule_json and not policy_rule_file:
ret['comment'] = 'One of "policy_rule", "policy_rule_json", or "policy_rule_file" is required!'
return ret
if sum(x is not None for x in [policy_rule, policy_rule_json, policy_rule_file]) > 1:
ret['comment'] = 'Only one of "policy_rule", "policy_rule_json", or "policy_rule_file" is allowed!'
return ret
if ((policy_rule_json or policy_rule_file) and
(policy_type or mode or display_name or description or metadata or parameters)):
ret['comment'] = 'Policy definitions cannot be passed when "policy_rule_json" or "policy_rule_file" is defined!'
return ret
temp_rule = {}
if policy_rule_json:
try:
temp_rule = json.loads(policy_rule_json)
except Exception as exc:
ret['comment'] = 'Unable to load policy rule json! ({0})'.format(exc)
return ret
elif policy_rule_file:
try:
# pylint: disable=unused-variable
sfn, source_sum, comment_ = __salt__['file.get_managed'](
None,
template,
policy_rule_file,
source_hash,
source_hash_name,
None,
None,
None,
__env__,
None,
None,
skip_verify=skip_verify,
**kwargs
)
except Exception as exc:
ret['comment'] = 'Unable to locate policy rule file "{0}"! ({1})'.format(policy_rule_file, exc)
return ret
if not sfn:
ret['comment'] = 'Unable to locate policy rule file "{0}"!)'.format(policy_rule_file)
return ret
try:
with salt.utils.files.fopen(sfn, 'r') as prf:
temp_rule = json.load(prf)
except Exception as exc:
ret['comment'] = 'Unable to load policy rule file "{0}"! ({1})'.format(policy_rule_file, exc)
return ret
if sfn:
salt.utils.files.remove(sfn)
policy_name = name
if policy_rule_json or policy_rule_file:
if temp_rule.get('name'):
policy_name = temp_rule.get('name')
policy_rule = temp_rule.get('properties', {}).get('policyRule')
policy_type = temp_rule.get('properties', {}).get('policyType')
mode = temp_rule.get('properties', {}).get('mode')
display_name = temp_rule.get('properties', {}).get('displayName')
description = temp_rule.get('properties', {}).get('description')
metadata = temp_rule.get('properties', {}).get('metadata')
parameters = temp_rule.get('properties', {}).get('parameters')
policy = __salt__['azurearm_resource.policy_definition_get'](name, azurearm_log_level='info', **connection_auth)
if 'error' not in policy:
if policy_type and policy_type.lower() != policy.get('policy_type', '').lower():
ret['changes']['policy_type'] = {
'old': policy.get('policy_type'),
'new': policy_type
}
if (mode or '').lower() != policy.get('mode', '').lower():
ret['changes']['mode'] = {
'old': policy.get('mode'),
'new': mode
}
if (display_name or '').lower() != policy.get('display_name', '').lower():
ret['changes']['display_name'] = {
'old': policy.get('display_name'),
'new': display_name
}
if (description or '').lower() != policy.get('description', '').lower():
ret['changes']['description'] = {
'old': policy.get('description'),
'new': description
}
rule_changes = __utils__['dictdiffer.deep_diff'](policy.get('policy_rule', {}), policy_rule or {})
if rule_changes:
ret['changes']['policy_rule'] = rule_changes
meta_changes = __utils__['dictdiffer.deep_diff'](policy.get('metadata', {}), metadata or {})
if meta_changes:
ret['changes']['metadata'] = meta_changes
param_changes = __utils__['dictdiffer.deep_diff'](policy.get('parameters', {}), parameters or {})
if param_changes:
ret['changes']['parameters'] = param_changes
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Policy definition {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy definition {0} would be updated.'.format(name)
ret['result'] = None
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': policy_name,
'policy_type': policy_type,
'mode': mode,
'display_name': display_name,
'description': description,
'metadata': metadata,
'parameters': parameters,
'policy_rule': policy_rule,
}
}
if __opts__['test']:
ret['comment'] = 'Policy definition {0} would be created.'.format(name)
ret['result'] = None
return ret
# Convert OrderedDict to dict
if isinstance(metadata, dict):
metadata = json.loads(json.dumps(metadata))
if isinstance(parameters, dict):
parameters = json.loads(json.dumps(parameters))
policy_kwargs = kwargs.copy()
policy_kwargs.update(connection_auth)
policy = __salt__['azurearm_resource.policy_definition_create_or_update'](
name=policy_name,
policy_rule=policy_rule,
policy_type=policy_type,
mode=mode,
display_name=display_name,
description=description,
metadata=metadata,
parameters=parameters,
**policy_kwargs
)
if 'error' not in policy:
ret['result'] = True
ret['comment'] = 'Policy definition {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create policy definition {0}! ({1})'.format(name, policy.get('error'))
return ret
def policy_definition_absent(name, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a policy definition does not exist in the current subscription.
:param name:
Name of the policy definition.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_definition_get'](name, azurearm_log_level='info', **connection_auth)
if 'error' in policy:
ret['result'] = True
ret['comment'] = 'Policy definition {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Policy definition {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': policy,
'new': {},
}
return ret
deleted = __salt__['azurearm_resource.policy_definition_delete'](name, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Policy definition {0} has been deleted.'.format(name)
ret['changes'] = {
'old': policy,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete policy definition {0}!'.format(name)
return ret
def policy_assignment_absent(name, scope, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a policy assignment does not exist in the provided scope.
:param name:
Name of the policy assignment.
:param scope:
The scope of the policy assignment.
connection_auth
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
policy = __salt__['azurearm_resource.policy_assignment_get'](
name,
scope,
azurearm_log_level='info',
**connection_auth
)
if 'error' in policy:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} is already absent.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Policy assignment {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': policy,
'new': {},
}
return ret
deleted = __salt__['azurearm_resource.policy_assignment_delete'](name, scope, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Policy assignment {0} has been deleted.'.format(name)
ret['changes'] = {
'old': policy,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete policy assignment {0}!'.format(name)
return ret
|
saltstack/salt
|
salt/returners/xmpp_return.py
|
returner
|
python
|
def returner(ret):
'''
Send an xmpp message with the data
'''
_options = _get_options(ret)
from_jid = _options.get('from_jid')
password = _options.get('password')
recipient_jid = _options.get('recipient_jid')
if not from_jid:
log.error('xmpp.jid not defined in salt config')
return
if not password:
log.error('xmpp.password not defined in salt config')
return
if not recipient_jid:
log.error('xmpp.recipient not defined in salt config')
return
message = ('id: {0}\r\n'
'function: {1}\r\n'
'function args: {2}\r\n'
'jid: {3}\r\n'
'return: {4}\r\n').format(
ret.get('id'),
ret.get('fun'),
ret.get('fun_args'),
ret.get('jid'),
pprint.pformat(ret.get('return')))
xmpp = SendMsgBot(from_jid, password, recipient_jid, message)
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0199') # XMPP Ping
if xmpp.connect():
xmpp.process(block=True)
return True
return False
|
Send an xmpp message with the data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/xmpp_return.py#L157-L198
|
[
"def _get_options(ret=None):\n '''\n Get the xmpp options from salt.\n '''\n attrs = {'xmpp_profile': 'profile',\n 'from_jid': 'jid',\n 'password': 'password',\n 'recipient_jid': 'recipient'}\n\n profile_attr = 'xmpp_profile'\n\n profile_attrs = {'from_jid': 'jid',\n 'password': 'password'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n profile_attr=profile_attr,\n profile_attrs=profile_attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n return _options\n"
] |
# -*- coding: utf-8 -*-
'''
Return salt data via xmpp
:depends: sleekxmpp >= 1.3.1
The following fields can be set in the minion conf file::
xmpp.jid (required)
xmpp.password (required)
xmpp.recipient (required)
xmpp.profile (optional)
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location::
xmpp.jid
xmpp.password
xmpp.recipient
xmpp.profile
XMPP settings may also be configured as::
xmpp:
jid: user@xmpp.domain.com/resource
password: password
recipient: user@xmpp.example.com
alternative.xmpp:
jid: user@xmpp.domain.com/resource
password: password
recipient: someone@xmpp.example.com
xmpp_profile:
xmpp.jid: user@xmpp.domain.com/resource
xmpp.password: password
xmpp:
profile: xmpp_profile
recipient: user@xmpp.example.com
alternative.xmpp:
profile: xmpp_profile
recipient: someone-else@xmpp.example.com
To use the XMPP returner, append '--return xmpp' to the salt command.
.. code-block:: bash
salt '*' test.ping --return xmpp
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return xmpp --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return xmpp --return_kwargs '{"recipient": "someone-else@xmpp.example.com"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import pprint
# Import salt libs
import salt.returners
from salt.utils.versions import LooseVersion as _LooseVersion
HAS_LIBS = False
try:
from sleekxmpp import ClientXMPP as _ClientXMPP # pylint: disable=import-error
HAS_LIBS = True
except ImportError:
class _ClientXMPP(object):
'''
Fake class in order not to raise errors
'''
log = logging.getLogger(__name__)
__virtualname__ = 'xmpp'
def _get_options(ret=None):
'''
Get the xmpp options from salt.
'''
attrs = {'xmpp_profile': 'profile',
'from_jid': 'jid',
'password': 'password',
'recipient_jid': 'recipient'}
profile_attr = 'xmpp_profile'
profile_attrs = {'from_jid': 'jid',
'password': 'password'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
profile_attr=profile_attr,
profile_attrs=profile_attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def __virtual__():
'''
Only load this module if right version of sleekxmpp is installed on this minion.
'''
min_version = '1.3.1'
if HAS_LIBS:
import sleekxmpp # pylint: disable=3rd-party-module-not-gated
# Certain XMPP functionaility we're using doesn't work with versions under 1.3.1
sleekxmpp_version = _LooseVersion(sleekxmpp.__version__)
valid_version = _LooseVersion(min_version)
if sleekxmpp_version >= valid_version:
return __virtualname__
return False, 'Could not import xmpp returner; sleekxmpp python client is not ' \
'installed or is older than version \'{0}\'.'.format(min_version)
class SendMsgBot(_ClientXMPP):
def __init__(self, jid, password, recipient, msg): # pylint: disable=E1002
# PyLint wrongly reports an error when calling super, hence the above
# disable call
super(SendMsgBot, self).__init__(jid, password)
self.recipient = recipient
self.msg = msg
self.add_event_handler('session_start', self.start)
def start(self, event):
self.send_presence()
self.send_message(mto=self.recipient,
mbody=self.msg,
mtype='chat')
self.disconnect(wait=True)
|
saltstack/salt
|
salt/states/win_iis.py
|
_get_binding_info
|
python
|
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
|
Combine the host header, IP address, and TCP port into bindingInformation format.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L31-L37
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
deployed
|
python
|
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
|
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L40-L110
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
remove_site
|
python
|
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
|
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L113-L147
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
create_binding
|
python
|
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
|
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L150-L209
|
[
"def _get_binding_info(hostheader='', ipaddress='*', port=80):\n '''\n Combine the host header, IP address, and TCP port into bindingInformation format.\n '''\n ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
remove_binding
|
python
|
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
|
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L212-L261
|
[
"def _get_binding_info(hostheader='', ipaddress='*', port=80):\n '''\n Combine the host header, IP address, and TCP port into bindingInformation format.\n '''\n ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
create_cert_binding
|
python
|
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
|
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L264-L331
|
[
"def _get_binding_info(hostheader='', ipaddress='*', port=80):\n '''\n Combine the host header, IP address, and TCP port into bindingInformation format.\n '''\n ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
remove_cert_binding
|
python
|
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
|
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L334-L396
|
[
"def _get_binding_info(hostheader='', ipaddress='*', port=80):\n '''\n Combine the host header, IP address, and TCP port into bindingInformation format.\n '''\n ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
create_apppool
|
python
|
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
|
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L399-L439
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
remove_apppool
|
python
|
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
|
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L442-L477
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
container_setting
|
python
|
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L480-L573
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
create_app
|
python
|
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
|
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L576-L632
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
remove_app
|
python
|
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
|
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L635-L670
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
create_vdir
|
python
|
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
|
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L673-L730
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
remove_vdir
|
python
|
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
|
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L733-L780
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
set_app
|
python
|
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L783-L871
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/win_iis.py
|
webconfiguration_settings
|
python
|
def webconfiguration_settings(name, location='', settings=None):
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
settings_list = list()
for filter, filter_settings in settings.items():
for setting_name, value in filter_settings.items():
settings_list.append({'filter': filter, 'name': setting_name, 'value': value})
current_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and list(map(dict, setting['value'])) != list(map(dict, current_settings_list[idx]['value'])))
or (not is_collection and str(setting['value']) != str(current_settings_list[idx]['value']))):
ret_settings['changes'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': settings_list[idx]['value']}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webconfiguration_settings'](name=name, settings=settings_list, location=location)
new_settings_list = __salt__['win_iis.get_webconfiguration_settings'](name=name,
settings=settings_list, location=location)
for idx, setting in enumerate(settings_list):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((is_collection and setting['value'] != new_settings_list[idx]['value'])
or (not is_collection and str(setting['value']) != str(new_settings_list[idx]['value']))):
ret_settings['failures'][setting['filter'] + '.' + setting['name']] = {'old': current_settings_list[idx]['value'],
'new': new_settings_list[idx]['value']}
ret_settings['changes'].pop(setting['filter'] + '.' + setting['name'], None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
r'''
Set the value of webconfiguration settings.
:param str name: The name of the IIS PSPath containing the settings.
Possible PSPaths are :
MACHINE, MACHINE/WEBROOT, IIS:\, IIS:\Sites\sitename, ...
:param str location: The location of the settings.
:param dict settings: Dictionaries of dictionaries.
You can match a specific item in a collection with this syntax inside a key:
'Collection[{name: site0}].logFile.directory'
Example of usage for the ``MACHINE/WEBROOT`` PSPath:
.. code-block:: yaml
MACHINE-WEBROOT-level-security:
win_iis.webconfiguration_settings:
- name: 'MACHINE/WEBROOT'
- settings:
system.web/authentication/forms:
requireSSL: True
protection: "All"
credentials.passwordFormat: "SHA1"
system.web/httpCookies:
httpOnlyCookies: True
Example of usage for the ``IIS:\Sites\site0`` PSPath:
.. code-block:: yaml
site0-IIS-Sites-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\Sites\site0'
- settings:
system.webServer/httpErrors:
errorMode: "DetailedLocalOnly"
system.webServer/security/requestFiltering:
allowDoubleEscaping: False
verbs.Collection:
- verb: TRACE
allowed: False
fileExtensions.allowUnlisted: False
Example of usage for the ``IIS:\`` PSPath with a collection matching:
.. code-block:: yaml
site0-IIS-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:\'
- settings:
system.applicationHost/sites:
'Collection[{name: site0}].logFile.directory': 'C:\logs\iis\site0'
Example of usage with a location:
.. code-block:: yaml
site0-IIS-location-level-security:
win_iis.webconfiguration_settings:
- name: 'IIS:/'
- location: 'site0'
- settings:
system.webServer/security/authentication/basicAuthentication:
enabled: True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_iis.py#L874-L1006
| null |
# -*- coding: utf-8 -*-
'''
Microsoft IIS site management
This module provides the ability to add/remove websites and application pools
from Microsoft IIS.
.. versionadded:: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.ext.six.moves import map
# Define the module's virtual name
__virtualname__ = 'win_iis'
def __virtual__():
'''
Load only on minions that have the win_iis module.
'''
if 'win_iis.create_site' in __salt__:
return __virtualname__
return False
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret
def deployed(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http', preload=''):
'''
Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:param str sourcepath: The physical path of the IIS site.
:param str apppool: The name of the IIS application pool.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param bool preload: Whether Preloading should be enabled
.. note:
If an application pool is specified, and that application pool does not already exist,
it will be created.
Example of usage with only the required arguments. This will default to using the default application pool
assigned by IIS:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-deployed:
win_iis.deployed:
- name: site0
- sourcepath: C:\\inetpub\\site0
- apppool: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- preload: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name in current_sites:
ret['comment'] = 'Site already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created site: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_site'](name, sourcepath, apppool,
hostheader, ipaddress, port,
protocol, preload)
return ret
def remove_site(name):
'''
Delete a website from IIS.
:param str name: The IIS site name.
Usage:
.. code-block:: yaml
defaultwebsite-remove:
win_iis.remove_site:
- name: Default Web Site
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_sites = __salt__['win_iis.list_sites']()
if name not in current_sites:
ret['comment'] = 'Site has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Site will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed site: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_site'](name)
return ret
def create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):
'''
Create an IIS binding.
.. note:
This function only validates against the binding ipaddress:port:hostheader combination,
and will return True even if the binding already exists with a different configuration.
It will not modify the configuration of an existing binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str protocol: The application protocol of the binding.
:param str sslflags: The flags representing certificate type and storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding:
win_iis.create_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
- protocol: https
- sslflags: 0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info in current_bindings:
ret['comment'] = 'Binding already present: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be created: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
else:
ret['comment'] = 'Created binding: {0}'.format(binding_info)
ret['changes'] = {'old': None,
'new': binding_info}
ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress,
port, protocol, sslflags)
return ret
def remove_binding(name, site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-https-binding-remove:
win_iis.remove_binding:
- site: site0
- hostheader: site0.local
- ipaddress: '*'
- port: 443
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_bindings = __salt__['win_iis.list_bindings'](site)
if binding_info not in current_bindings:
ret['comment'] = 'Binding has already been removed: {0}'.format(binding_info)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Binding will be removed: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
else:
ret['comment'] = 'Removed binding: {0}'.format(binding_info)
ret['changes'] = {'old': binding_info,
'new': None}
ret['result'] = __salt__['win_iis.remove_binding'](site, hostheader,
ipaddress, port)
return ret
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):
'''
Assign a certificate to an IIS binding.
.. note:
The web binding that the certificate is being assigned to must already exist.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
:param str sslflags: Flags representing certificate type and certificate storage of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding:
win_iis.create_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
- sslflags: 1
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info in current_cert_bindings:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Certificate binding already present: {0}'.format(name)
ret['result'] = True
return ret
ret['comment'] = ('Certificate binding already present with a different'
' thumbprint: {0}'.format(current_name))
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created certificate binding: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_cert_binding'](name, site, hostheader,
ipaddress, port, sslflags)
return ret
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certificate.
:param str site: The IIS site name.
:param str hostheader: The host header of the binding.
:param str ipaddress: The IP address of the binding.
:param str port: The TCP port of the binding.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-binding-remove:
win_iis.remove_cert_binding:
- name: 9988776655443322111000AAABBBCCCDDDEEEFFF
- site: site0
- hostheader: site0.local
- ipaddress: 192.168.1.199
- port: 443
.. versionadded:: 2016.11.0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_cert_bindings = __salt__['win_iis.list_cert_bindings'](site)
if binding_info not in current_cert_bindings:
ret['comment'] = 'Certificate binding has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Certificate binding will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
current_name = current_cert_bindings[binding_info]['certificatehash']
if name == current_name:
ret['comment'] = 'Removed certificate binding: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_cert_binding'](name, site, hostheader,
ipaddress, port)
return ret
def create_apppool(name):
'''
Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
site0-apppool:
win_iis.create_apppool:
- name: site0
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name in current_apppools:
ret['comment'] = 'Application pool already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application pool: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_apppool'](name)
return ret
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
current_apppools = __salt__['win_iis.list_apppools']()
if name not in current_apppools:
ret['comment'] = 'Application pool has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application pool will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application pool: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_apppool'](name)
return ret
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A dictionary of the setting names and their values.
Example of usage for the ``AppPools`` container:
.. code-block:: yaml
site0-apppool-setting:
win_iis.container_setting:
- name: site0
- container: AppPools
- settings:
managedPipelineMode: Integrated
processModel.maxProcesses: 1
processModel.userName: TestUser
processModel.password: TestPassword
processModel.identityType: SpecificUser
Example of usage for the ``Sites`` container:
.. code-block:: yaml
site0-site-setting:
win_iis.container_setting:
- name: site0
- container: Sites
- settings:
logFile.logFormat: W3C
logFile.period: Daily
limits.maxUrlSegments: 32
'''
identityType_map2string = {0: 'LocalSystem', 1: 'LocalService', 2: 'NetworkService', 3: 'SpecificUser', 4: 'ApplicationPoolIdentity'}
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_container_setting'](name=name, container=container, settings=settings)
new_settings = __salt__['win_iis.get_container_setting'](name=name,
container=container,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note:
This function only validates against the application name, and will return True
even if the application already exists with a different configuration. It will not
modify the configuration of an existing application.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str apppool: The name of the IIS application pool.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-v1-app:
win_iis.create_app:
- name: v1
- site: site0
- sourcepath: C:\\inetpub\\site0\\v1
- apppool: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name in current_apps:
ret['comment'] = 'Application already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created application: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_app'](name, site, sourcepath,
apppool)
return ret
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_apps = __salt__['win_iis.list_apps'](site)
if name not in current_apps:
ret['comment'] = 'Application has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Application will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed application: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_app'](name, site)
return ret
def create_vdir(name, site, sourcepath, app='/'):
'''
Create an IIS virtual directory.
.. note:
This function only validates against the virtual directory name, and will return
True even if the virtual directory already exists with a different configuration.
It will not modify the configuration of an existing virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str sourcepath: The physical path.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir:
win_iis.create_vdir:
- name: foo
- site: site0
- sourcepath: C:\\inetpub\\vdirs\\foo
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name in current_vdirs:
ret['comment'] = 'Virtual directory already present: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be created: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
else:
ret['comment'] = 'Created virtual directory: {0}'.format(name)
ret['changes'] = {'old': None,
'new': name}
ret['result'] = __salt__['win_iis.create_vdir'](name, site, sourcepath,
app)
return ret
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-foo-vdir-remove:
win_iis.remove_vdir:
- name: foo
- site: site0
- app: v1
'''
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
current_vdirs = __salt__['win_iis.list_vdirs'](site, app)
if name not in current_vdirs:
ret['comment'] = 'Virtual directory has already been removed: {0}'.format(name)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = 'Virtual directory will be removed: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
else:
ret['comment'] = 'Removed virtual directory: {0}'.format(name)
ret['changes'] = {'old': name,
'new': None}
ret['result'] = __salt__['win_iis.remove_vdir'](name, site, app)
return ret
def set_app(name, site, settings=None):
# pylint: disable=anomalous-backslash-in-string
'''
.. versionadded:: 2017.7.0
Set the value of the setting for an IIS web application.
.. note::
This function only configures existing app. Params are case sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
Available settings:
- ``physicalPath`` - The physical path of the webapp
- ``applicationPool`` - The application pool for the webapp
- ``userName`` "connectAs" user
- ``password`` "connectAs" password for user
:rtype: bool
Example of usage:
.. code-block:: yaml
site0-webapp-setting:
win_iis.set_app:
- name: app0
- site: Default Web Site
- settings:
userName: domain\\user
password: pass
physicalPath: c:\inetpub\wwwroot
applicationPool: appPool0
'''
# pylint: enable=anomalous-backslash-in-string
ret = {'name': name,
'changes': {},
'comment': str(),
'result': None}
if not settings:
ret['comment'] = 'No settings to change provided.'
ret['result'] = True
return ret
ret_settings = {
'changes': {},
'failures': {},
}
current_settings = __salt__['win_iis.get_webapp_settings'](name=name,
site=site,
settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(current_settings[setting]):
ret_settings['changes'][setting] = {'old': current_settings[setting],
'new': settings[setting]}
if not ret_settings['changes']:
ret['comment'] = 'Settings already contain the provided values.'
ret['result'] = True
return ret
elif __opts__['test']:
ret['comment'] = 'Settings will be changed.'
ret['changes'] = ret_settings
return ret
__salt__['win_iis.set_webapp_settings'](name=name, site=site,
settings=settings)
new_settings = __salt__['win_iis.get_webapp_settings'](name=name, site=site, settings=settings.keys())
for setting in settings:
if str(settings[setting]) != str(new_settings[setting]):
ret_settings['failures'][setting] = {'old': current_settings[setting],
'new': new_settings[setting]}
ret_settings['changes'].pop(setting, None)
if ret_settings['failures']:
ret['comment'] = 'Some settings failed to change.'
ret['changes'] = ret_settings
ret['result'] = False
else:
ret['comment'] = 'Set settings to contain the provided values.'
ret['changes'] = ret_settings['changes']
ret['result'] = True
return ret
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.